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
|
---|---|---|---|---|---|
a31dbcbf5dc5f194801540041c6872068b0291ae | 995 | package org.modelcatalogue.letter.annotator;
/**
* Abstract implementation of Highlighter which allows to set custom head and tail.
*/
public abstract class AbstractHighlighter implements Highlighter {
private String head = "";
private String tail = "";
/**
* Sets the custom head for the highlighter which should be prepended to the highlighted text.
* @param head the custom head for the highlighter which should be prepended to the highlighted text
*/
public void setHead(String head) {
this.head = head;
}
/**
* Sets the custom tail for the highlighter which should be appended to the highlighted text.
* @param tail the custom tail for the highlighter which should be appended to the highlighted text
*/
public void setTail(String tail) {
this.tail = tail;
}
@Override
public String getTail() {
return tail;
}
@Override
public String getHead() {
return head;
}
}
| 26.184211 | 104 | 0.667337 |
dc2f3ef41597da0b9b16053bf87c029f97676272 | 5,490 | /*
* L2Operand.java
* Copyright © 1993-2018, The Avail Foundation, LLC.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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.
*
* * Neither the name of the copyright holder nor the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* 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 com.avail.interpreter.levelTwo.operand;
import com.avail.interpreter.levelTwo.L2Instruction;
import com.avail.interpreter.levelTwo.L2OperandDispatcher;
import com.avail.interpreter.levelTwo.L2OperandType;
import com.avail.interpreter.levelTwo.register.L2Register;
import com.avail.optimizer.L2BasicBlock;
import com.avail.optimizer.L2ValueManifest;
import com.avail.utility.PublicCloneable;
import java.util.List;
import java.util.Map;
/**
* An {@code L2Operand} knows its {@link L2OperandType} and any specific value
* that needs to be captured for that type of operand.
*
* @author Mark van Gulik <[email protected]>
*/
public abstract class L2Operand
extends PublicCloneable<L2Operand>
{
/**
* Answer this operand's {@link L2OperandType}.
*
* @return An {@code L2OperandType}.
*/
public abstract L2OperandType operandType ();
/**
* Dispatch this {@code L2Operand} to the provided {@link
* L2OperandDispatcher}.
*
* @param dispatcher
* The {@code L2OperandDispatcher} visiting the receiver.
*/
public abstract void dispatchOperand (
final L2OperandDispatcher dispatcher);
/**
* This is an operand of the given instruction, which was just added to its
* basic block.
*
* @param instruction
* The {@link L2Instruction} that was just added.
* @param manifest
* The {@link L2ValueManifest} that is active where this {@link
* L2Instruction} was just added to its {@link L2BasicBlock}.
*/
@SuppressWarnings("EmptyMethod")
public void instructionWasAdded (
final L2Instruction instruction,
final L2ValueManifest manifest)
{
// Do nothing by default.
}
/**
* This is an operand of the given instruction, which was just inserted into
* its basic block as part of an optimization pass.
*
* @param instruction
* The {@link L2Instruction} that was just inserted.
* @param manifest
* The {@link L2ValueManifest} that is active where this {@link
* L2Instruction} was just inserted into its {@link L2BasicBlock}.
*/
public void instructionWasInserted (
final L2Instruction instruction,
final L2ValueManifest manifest)
{
instructionWasAdded(instruction, manifest);
}
/**
* This is an operand of the given instruction, which was just removed from
* its basic block.
*
* @param instruction
* The {@link L2Instruction} that was just added.
*/
@SuppressWarnings("EmptyMethod")
public void instructionWasRemoved (
final L2Instruction instruction)
{
// Do nothing by default.
}
/**
* Replace occurrences in this operand of each register that is a key of
* this map with the register that is the corresponding value. Do nothing
* to registers that are not keys of the map. Update all secondary
* structures, such as the instruction's source/destination collections.
*
* @param registerRemap
* A mapping to transform registers in-place.
* @param instruction
* The instruction containing this operand.
*/
@SuppressWarnings({"unused", "EmptyMethod"})
public void replaceRegisters (
final Map<L2Register, L2Register> registerRemap,
final L2Instruction instruction)
{
// By default do nothing.
}
/**
* Move any registers used as sources within me into the provided list.
*
* @param sourceRegisters The {@link List} to update.
*/
@SuppressWarnings({"unused", "EmptyMethod"})
public void addSourceRegistersTo (
final List<L2Register> sourceRegisters)
{
// Do nothing by default.
}
/**
* Move any registers used as destinations within me into the provided list.
*
* @param destinationRegisters The {@link List} to update.
*/
@SuppressWarnings({"unused", "EmptyMethod"})
public void addDestinationRegistersTo (
final List<L2Register> destinationRegisters)
{
// Do nothing by default.
}
@Override
public abstract String toString ();
}
| 32.874251 | 80 | 0.733698 |
147e7b6275450c47664339d396a8d62f949362cd | 817 | import java.lang.Exception;
class threadX extends Thread {
int i;
String str;
threadX(int i,String str) {
this.i = i;
this.str = str;
}
public void run() {
try {
System.out.println(str+" is "+i);
}
catch(Exception e) {
System.out.println("Exception ocurred "+e);
}
}
}
class threadY implements Runnable {
int i;
String str;
threadY(int i ,String str) {
this.i = i;
this.str = str;
Thread t = new Thread(this,"Thread");
t.start();
}
public void run() {
try {
for(int i=0;i<5;i++) {
System.out.println(str+ " is "+i);
Thread.sleep(1000);
}
}
catch(Exception e) {
System.out.println("Exception ocurred "+e);
}
}
}
class ThreadProg {
public static void main(String args[]) {
threadX t1 = new threadX(100,"Dolo-650");
t1.start();
threadY t2 = new threadY(120,"Aspirin");
}
}
| 17.382979 | 44 | 0.631579 |
0f43692dd9d3f4306927019d0862e32b453a84b8 | 2,279 | package de.srendi.advancedperipherals.common.blocks.tileentity;
import com.refinedmods.refinedstorage.api.network.node.INetworkNodeProxy;
import com.refinedmods.refinedstorage.tile.NetworkNodeTile;
import com.refinedmods.refinedstorage.tile.config.IRedstoneConfigurable;
import dan200.computercraft.api.peripheral.IPeripheral;
import de.srendi.advancedperipherals.AdvancedPeripherals;
import de.srendi.advancedperipherals.common.addons.computercraft.peripheral.RsBridgePeripheral;
import de.srendi.advancedperipherals.common.addons.refinedstorage.RefinedStorageNode;
import de.srendi.advancedperipherals.common.setup.TileEntityTypes;
import net.minecraft.tileentity.TileEntityType;
import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.util.LazyOptional;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static dan200.computercraft.shared.Capabilities.CAPABILITY_PERIPHERAL;
public class RsBridgeTile extends NetworkNodeTile<RefinedStorageNode> implements INetworkNodeProxy<RefinedStorageNode>, IRedstoneConfigurable {
protected RsBridgePeripheral peripheral = new RsBridgePeripheral("rsBridge", this);
private LazyOptional<IPeripheral> peripheralCap;
public RsBridgeTile() {
this(TileEntityTypes.RS_BRIDGE.get());
}
public RsBridgeTile(TileEntityType<?> tileType) {
super(tileType);
}
@NotNull
public <T1> LazyOptional<T1> getCapability(@NotNull Capability<T1> cap, @Nullable Direction direction) {
if (cap == CAPABILITY_PERIPHERAL) {
if (peripheral.isEnabled()) {
if (peripheralCap == null) {
peripheralCap = LazyOptional.of(() -> peripheral);
}
return peripheralCap.cast();
} else {
AdvancedPeripherals.debug(peripheral.getType() + " is disabled, you can enable it in the Configuration.");
}
}
return super.getCapability(cap, direction);
}
public RefinedStorageNode createNode(World world, BlockPos blockPos) {
return new RefinedStorageNode(world, blockPos);
}
} | 41.436364 | 143 | 0.754278 |
245dd23f99a7445a1be461b406198a45f82ab489 | 7,264 | package ru.stqa.pft.addressbook.appmanager;
import org.testng.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import ru.stqa.pft.addressbook.model.ContactData;
import ru.stqa.pft.addressbook.model.Contacts;
import ru.stqa.pft.addressbook.model.GroupData;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ContactHelper extends HelperBase {
public ContactHelper(WebDriver wd) {
super(wd);
}
public void delete(int index) {
selectContact(index);
click(By.xpath("//input[@value='Delete']"));
wd.switchTo().alert().accept();
wd.findElement(By.cssSelector("div.msgbox"));
click(By.id("logo"));
}
public void delete(ContactData contact) {
selectContactById(contact.getId());
click(By.xpath("//input[@value='Delete']"));
wd.switchTo().alert().accept();
wd.findElement(By.cssSelector("div.msgbox"));
click(By.id("logo"));
}
public void selectContact(int index) {
wd.findElements(By.name("selected[]")).get(index).click();
}
public void selectContactById(int id) {
wd.findElement(By.cssSelector("tr[name='entry'] input[value ='" + id + "']")).click();
}
public void initContactModification(int index) {
wd.findElements(By.xpath("//img[@alt='Edit']")).get(index).click();
}
public void initContactModificationById(int id) {
wd.findElement(By.cssSelector(String.format("a[href ='edit.php?id=%s']", id))).click();
}
public void selectContactNotInGroup(ContactData contact) {
wd.findElement(By.xpath(String.format("//input[@type='checkbox']", contact.getId()))).click();
}
public void submitContactCreation() {
click(By.name("submit"));
}
public void fillContactForm(ContactData contactData) {
type(By.name("firstname"), contactData.getFirstname());
type(By.name("middlename"), contactData.getMiddlename());
type(By.name("lastname"), contactData.getLastname());
//attach(By.name("photo"), contactData.getPhoto()); Закомментирвал при выполнении задания 15
/*if (creation) {
new Select(wd.findElement(By.name("new_group"))).selectByVisibleText(contactData.getGroup());
}
else {
Assert.assertFalse(isElementPresent(By.name("new_group")));
}*/
}
public void initContactCreation() {
click(By.linkText("add new"));
}
public void submitContactModification() {
click(By.name("update"));
}
public void create(ContactData contact, boolean creation) {
fillContactForm(contact);
submitContactCreation();
}
public void modify(int index, ContactData contact) {
initContactModification(index);
fillContactForm(contact);
submitContactModification();
}
public void modifyById(ContactData contact) {
initContactModificationById(contact.getId());
fillContactForm(contact);
submitContactModification();
}
public boolean isThereAContact() {
return isElementPresent(By.name("selected[]"));
}
public int getContactCount() {
return (wd.findElements(By.name("selected[]")).size());
}
/*
public List<ContactData> list() {
List<ContactData> contacts = new ArrayList<ContactData>();
List<WebElement> rows = wd.findElements(By.cssSelector("tr[name='entry']"));
for (WebElement row : rows) {
int id = Integer.parseInt(row.findElement(By.cssSelector("td:nth-child(1) input")).
getAttribute("value"));
String lastname = row.findElement(By.cssSelector("td:nth-child(2)")).getText();
String firstname = row.findElement(By.cssSelector("td:nth-child(3)")).getText();
contacts.add(new ContactData().withId(id).withFirstname(firstname).withLastname(lastname));
}
return contacts;
}*/
public Contacts all() {
Contacts contacts = new Contacts();
List<WebElement> rows = wd.findElements(By.cssSelector("tr[name='entry']"));
for (WebElement row : rows) {
int id = Integer.parseInt(row.findElement(By.cssSelector("td:nth-child(1) input")).
getAttribute("value"));
String lastname = row.findElement(By.cssSelector("td:nth-child(2)")).getText();
String firstname = row.findElement(By.cssSelector("td:nth-child(3)")).getText();
String allPhones = row.findElement(By.cssSelector("td:nth-child(6)")).getText();
String allEmail = row.findElement(By.cssSelector("td:nth-child(5)")).getText();
String address = row.findElement(By.cssSelector("td:nth-child(4)")).getText();
contacts.add(new ContactData().withId(id).withFirstname(firstname).withLastname(lastname)
.withAllPhones(allPhones).withAddress(address).withAllEmail(allEmail));
}
return contacts;
}
public ContactData infoFromEditForm(ContactData contact) {
initContactModificationById(contact.getId());
String firstname = wd.findElement(By.name("firstname")).getAttribute("value");
String lastname = wd.findElement(By.name("lastname")).getAttribute("value");
String homephone = wd.findElement(By.name("home")).getAttribute("value");
String mobilephone = wd.findElement(By.name("mobile")).getAttribute("value");
String workphone = wd.findElement(By.name("work")).getAttribute("value");
String address = wd.findElement(By.name("address")).getAttribute("value");
String email = wd.findElement(By.name("email")).getAttribute("value");
String email2 = wd.findElement(By.name("email2")).getAttribute("value");
String email3 = wd.findElement(By.name("email3")).getAttribute("value");
wd.navigate().back();
return new ContactData().withId(contact.getId())
.withFirstname(firstname)
.withLastname(lastname)
.withHomephone(homephone)
.withMobilephone(mobilephone)
.withWorkphone(workphone)
.withEmail(email)
.withEmail2(email2)
.withEmail3(email3)
.withAddress(address);
}
public void selectGroup(GroupData group) {
wd.findElement(By.xpath(String.format("//select[@name='to_group']/option[@value='%s']", group.getId()))).click();
}
public void pushButtonAddToGroup() {
wd.findElement(By.xpath("//input[@name='add']")).click();
}
public void getGroupData(GroupData groupData) {
WebElement element = wd.findElement(By.xpath(String.format("//select[@name='group']/option[text() = '%s']", groupData.getName())));
element.click();
}
public void pushButtonRemoveFromGroup() {
wd.findElement(By.xpath("//input[@name='remove']")).click();
}
/*
public void selectDisplayGroup(String name) {
new Select(wd.findElement(By.name("group"))).selectByVisibleText(name);
}
public void addContactToGroup(ContactData contact, GroupData group) {
selectContactById(contact.getId());
new Select(wd.findElement(By.name("to_group"))).selectByVisibleText(group.getName());
click(By.name("add"));
}
public void removeContactFromGroup(ContactData contact, GroupData group) {
selectDisplayGroup(group.getName());
selectContactById(contact.getId());
removeFromGroup(group.getName());
}
private void removeFromGroup(String name) {
click(By.name("remove"));
}*/
}
| 34.103286 | 135 | 0.685573 |
21e4a5d0a4e1e295e585311dfad1b4637f34f412 | 1,981 | package Y2020.Day6;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class CustomCustoms {
private List<List<String>> data = new ArrayList<>();
public CustomCustoms() throws FileNotFoundException {
Scanner sc = new Scanner(new File("./src/Y2020/Day6/input.txt"));
this.data.add(new ArrayList<>());
while (sc.hasNextLine()) {
String answers = sc.nextLine();
if (answers.isEmpty()) {
this.data.add(new ArrayList<>());
answers = sc.nextLine();
}
this.data.get(this.data.size() - 1).add(answers);
}
this.part1();
this.part2();
}
private void part1() {
int count = 0;
for (List<String> groupAns : this.data) {
Set<Character> ans = new HashSet<>();
groupAns.forEach(s -> s.chars().mapToObj(i -> (char)i).forEach(ans::add));
count += ans.size();
}
System.out.println(count);
}
private void part2() {
int count = 0;
for (List<String> groupAns : this.data) {
groupAns.sort(Comparator.comparingInt(String::length));
List<Character> ans = new ArrayList<>();
groupAns.get(0).chars().mapToObj(i -> (char)i).forEach(c -> {
if (!ans.contains(c)) ans.add(c);
});
for (int i = 1; i < groupAns.size(); i++) {
String s = groupAns.get(i);
for (int j = ans.size() - 1; j >= 0; j--) {
char c = ans.get(j);
if (!s.contains(c + ""))
ans.remove((Character) c);
}
}
count += ans.size();
}
System.out.println(count);
}
public static void main(String[] args) throws FileNotFoundException {
new CustomCustoms();
}
}
| 30.953125 | 87 | 0.485109 |
cfa1777a20bc629148664a63043e6419c2394cbf | 2,911 | package com.blakebr0.pickletweaks.feature.item;
import com.blakebr0.cucumber.helper.NBTHelper;
import com.blakebr0.cucumber.iface.IEnableable;
import com.blakebr0.cucumber.item.BaseItem;
import com.blakebr0.pickletweaks.config.ModConfigs;
import com.blakebr0.pickletweaks.lib.ModTooltips;
import net.minecraft.network.chat.Component;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.ExperienceOrb;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.level.Level;
import java.util.List;
import java.util.function.Function;
public class MagnetItem extends BaseItem implements IEnableable {
public MagnetItem(Function<Properties, Properties> properties) {
super(properties.compose(p -> p.stacksTo(1)));
}
@Override
public boolean isFoil(ItemStack stack) {
return NBTHelper.getBoolean(stack, "Enabled");
}
@Override
public InteractionResultHolder<ItemStack> use(Level level, Player player, InteractionHand hand) {
var stack = player.getItemInHand(hand);
player.playSound(SoundEvents.EXPERIENCE_ORB_PICKUP, 0.5F, NBTHelper.getBoolean(stack, "Enabled") ? 0.5F : 1.0F);
NBTHelper.flipBoolean(stack, "Enabled");
return new InteractionResultHolder<>(InteractionResult.SUCCESS, stack);
}
@Override
public void appendHoverText(ItemStack stack, Level level, List<Component> tooltip, TooltipFlag advanced) {
if (NBTHelper.getBoolean(stack, "Enabled")) {
tooltip.add(ModTooltips.ENABLED.build());
} else {
tooltip.add(ModTooltips.DISABLED.build());
}
}
@Override
public void inventoryTick(ItemStack stack, Level level, Entity entity, int slot, boolean isSelected) {
if (entity instanceof Player && NBTHelper.getBoolean(stack, "Enabled")) {
double range = ModConfigs.MAGNET_RANGE.get();
var items = level.getEntitiesOfClass(ItemEntity.class, entity.getBoundingBox().inflate(range));
for (var item : items) {
if (!item.isAlive() || NBTHelper.getBoolean(stack, "PreventRemoteMovement"))
continue;
if (item.getThrower() != null && item.getThrower().equals(entity.getUUID()) && item.hasPickUpDelay())
continue;
if (!level.isClientSide()) {
item.setNoPickUpDelay();
item.setPos(entity.getX(), entity.getY(), entity.getZ());
}
}
var orbs = level.getEntitiesOfClass(ExperienceOrb.class, entity.getBoundingBox().inflate(range));
for (var orb : orbs) {
if (!level.isClientSide()) {
orb.setPos(entity.getX(), entity.getY(), entity.getZ());
}
}
}
}
@Override
public boolean isEnabled() {
return ModConfigs.ENABLE_MAGNET.get();
}
}
| 33.079545 | 114 | 0.754036 |
aa92fd78a0763202de31c935766923e9d2868b46 | 9,576 | /**
* Copyright 2013 Canada Health Infoway, 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.
*
* Author: $LastChangedBy: tmcgrady $
* Last modified: $LastChangedDate: 2011-05-04 16:47:15 -0300 (Wed, 04 May 2011) $
* Revision: $LastChangedRevision: 2623 $
*/
package ca.infoway.messagebuilder.datatype.lang;
import java.math.BigDecimal;
import java.util.Date;
import org.junit.Assert;
import org.junit.Test;
import ca.infoway.messagebuilder.datatype.lang.util.OrganizationNamePartType;
import ca.infoway.messagebuilder.datatype.lang.util.PersonNamePartType;
import ca.infoway.messagebuilder.datatype.lang.util.PostalAddressPartType;
import ca.infoway.messagebuilder.domainvalue.basic.Currency;
import ca.infoway.messagebuilder.domainvalue.basic.EntityNamePartQualifier;
import ca.infoway.messagebuilder.domainvalue.basic.EntityNameUse;
import ca.infoway.messagebuilder.domainvalue.basic.TelecommunicationAddressUse;
import ca.infoway.messagebuilder.domainvalue.basic.URLScheme;
import ca.infoway.messagebuilder.domainvalue.basic.UnitsOfMeasureCaseSensitive;
import ca.infoway.messagebuilder.domainvalue.basic.X_BasicPostalAddressUse;
import ca.infoway.messagebuilder.domainvalue.controlact.ActStatus;
public class DatatypeEqualsTest {
@Test
public void TestTrivialNameEquals()
{
TrivialName trivialName1 = new TrivialName("aName");
trivialName1.addUse(EntityNameUse.PHONETIC);
TrivialName trivialName2 = new TrivialName("aName");
trivialName2.addUse(EntityNameUse.PHONETIC);
Assert.assertEquals(trivialName1, trivialName2);
}
@Test
public void TestTelecomAddressEquals()
{
TelecommunicationAddress telecomAddress1 = new TelecommunicationAddress();
telecomAddress1.setAddress("192.168.0.27");
telecomAddress1.setUrlScheme(URLScheme.HTTP);
telecomAddress1.addAddressUse(TelecommunicationAddressUse.ANSWERING_MACHINE);
TelecommunicationAddress telecomAddress2 = new TelecommunicationAddress();
telecomAddress2.setAddress("192.168.0.27");
telecomAddress2.setUrlScheme(URLScheme.HTTP);
telecomAddress2.addAddressUse(TelecommunicationAddressUse.ANSWERING_MACHINE);
Assert.assertEquals(telecomAddress1, telecomAddress2);
}
@Test
public void TestPhysicalQuantityEquals()
{
PhysicalQuantity pq1 = new PhysicalQuantity(new BigDecimal(1.5), UnitsOfMeasureCaseSensitive.CENTIMETRE);
PhysicalQuantity pq2 = new PhysicalQuantity(new BigDecimal(1.5), UnitsOfMeasureCaseSensitive.CENTIMETRE);
Assert.assertEquals(pq1, pq2);
}
@Test
public void TestOrganizationNameEquals()
{
OrganizationName orgName1 = new OrganizationName();
orgName1.addUse(EntityNameUse.LEGAL);
orgName1.addNamePart(new EntityNamePart("aName", OrganizationNamePartType.PREFIX, EntityNamePartQualifier.LEGALSTATUS));
OrganizationName orgName2 = new OrganizationName();
orgName2.addUse(EntityNameUse.LEGAL);
orgName2.addNamePart(new EntityNamePart("aName", OrganizationNamePartType.PREFIX, EntityNamePartQualifier.LEGALSTATUS));
Assert.assertEquals(orgName1, orgName2);
}
@Test
public void TestPersonNameEquals()
{
PersonName personName1 = new PersonName();
personName1.addUse(EntityNameUse.LEGAL);
personName1.addNamePart(new EntityNamePart("aName", PersonNamePartType.FAMILY, EntityNamePartQualifier.INITIAL));
PersonName personName2 = new PersonName();
personName2.addUse(EntityNameUse.LEGAL);
personName2.addNamePart(new EntityNamePart("aName", PersonNamePartType.FAMILY, EntityNamePartQualifier.INITIAL));
Assert.assertEquals(personName1, personName2);
}
@Test
public void TestPostalAddressEquals()
{
PostalAddress address1 = new PostalAddress();
address1.addPostalAddressPart(new PostalAddressPart(PostalAddressPartType.CARE_OF, "careOfPlace"));
address1.addPostalAddressPart(new PostalAddressPart(PostalAddressPartType.CITY, "aCity"));
address1.addUse(X_BasicPostalAddressUse.HOME);
address1.addUse(X_BasicPostalAddressUse.TEMPORARY);
PostalAddress address2 = new PostalAddress();
address2.addPostalAddressPart(new PostalAddressPart(PostalAddressPartType.CARE_OF, "careOfPlace"));
address2.addPostalAddressPart(new PostalAddressPart(PostalAddressPartType.CITY, "aCity"));
address2.addUse(X_BasicPostalAddressUse.HOME);
address2.addUse(X_BasicPostalAddressUse.TEMPORARY);
Assert.assertEquals(address1, address2);
}
@Test
public void TestIdentiferEquals()
{
Identifier id1 = new Identifier("aRoot", "anExtension", "aVersion");
Identifier id2 = new Identifier("aRoot", "anExtension", "aVersion");
Assert.assertEquals(id1, id2);
}
@Test
public void TestDateEquals()
{
Date date1 = new Date(12345);
Date date2 = new Date(12345);
Assert.assertEquals(date1, date2);
}
@Test
public void TestMoneyEquals()
{
Money money1 = new Money(new BigDecimal(3.21), Currency.CANADIAN_DOLLAR);
Money money2 = new Money(new BigDecimal(3.21), Currency.CANADIAN_DOLLAR);
Assert.assertEquals(money1, money2);
}
@Test
public void TestRatioEquals()
{
PhysicalQuantity pq1a = new PhysicalQuantity(new BigDecimal(1.5), UnitsOfMeasureCaseSensitive.CENTIMETRE);
PhysicalQuantity pq1b = new PhysicalQuantity(new BigDecimal(1.46), UnitsOfMeasureCaseSensitive.CUBIC_MILIMETER);
Ratio<PhysicalQuantity, PhysicalQuantity> ratio1 = new Ratio<PhysicalQuantity, PhysicalQuantity>(pq1a, pq1b);
PhysicalQuantity pq2a = new PhysicalQuantity(new BigDecimal(1.5), UnitsOfMeasureCaseSensitive.CENTIMETRE);
PhysicalQuantity pq2b = new PhysicalQuantity(new BigDecimal(1.46), UnitsOfMeasureCaseSensitive.CUBIC_MILIMETER);
Ratio<PhysicalQuantity, PhysicalQuantity> ratio2 = new Ratio<PhysicalQuantity, PhysicalQuantity>(pq2a, pq2b);
Assert.assertEquals(ratio1, ratio2);
}
@Test
public void TestIntervalEquals()
{
Interval<Date> interval1 = IntervalFactory.createLowHigh(new Date(1234), new Date(5678));
Interval<Date> interval2 = IntervalFactory.createLowHigh(new Date(1234), new Date(5678));
Assert.assertEquals(interval1, interval2);
}
@Test
public void TestPivlEquals()
{
PeriodicIntervalTime pivl1 = PeriodicIntervalTime.createPeriodPhase(
new DateDiff(new PhysicalQuantity(new BigDecimal(4), UnitsOfMeasureCaseSensitive.DAY)),
IntervalFactory.createLowHigh(new Date(1234), new Date(5678))
);
PeriodicIntervalTime pivl2 = PeriodicIntervalTime.createPeriodPhase(
new DateDiff(new PhysicalQuantity(new BigDecimal(4), UnitsOfMeasureCaseSensitive.DAY)),
IntervalFactory.createLowHigh(new Date(1234), new Date(5678))
);
Assert.assertEquals(pivl1, pivl2);
pivl1 = PeriodicIntervalTime.createFrequency(5, new PhysicalQuantity(new BigDecimal(4), UnitsOfMeasureCaseSensitive.DAY));
pivl2 = PeriodicIntervalTime.createFrequency(5, new PhysicalQuantity(new BigDecimal(4), UnitsOfMeasureCaseSensitive.DAY));
Assert.assertEquals(pivl1, pivl2);
}
@Test
public void TestGtsEquals()
{
PeriodicIntervalTime pivl1 = PeriodicIntervalTime.createPeriodPhase(
new DateDiff(new PhysicalQuantity(new BigDecimal(4), UnitsOfMeasureCaseSensitive.DAY)),
IntervalFactory.createLowHigh(new Date(1234), new Date(5678))
);
GeneralTimingSpecification gts1 = new GeneralTimingSpecification(IntervalFactory.createLowHigh(new Date(2222), new Date(3333)), pivl1);
PeriodicIntervalTime pivl2 = PeriodicIntervalTime.createPeriodPhase(
new DateDiff(new PhysicalQuantity(new BigDecimal(4), UnitsOfMeasureCaseSensitive.DAY)),
IntervalFactory.createLowHigh(new Date(1234), new Date(5678))
);
GeneralTimingSpecification gts2 = new GeneralTimingSpecification(IntervalFactory.createLowHigh(new Date(2222), new Date(3333)), pivl2);
Assert.assertEquals(gts1, gts2);
}
@Test
public void TestCodedStringEquals()
{
CodedString<ca.infoway.messagebuilder.domainvalue.ActStatus> cs1 = new CodedString<ca.infoway.messagebuilder.domainvalue.ActStatus>("111", ActStatus.CANCELLED, "222", "333", "444");
CodedString<ca.infoway.messagebuilder.domainvalue.ActStatus> cs2 = new CodedString<ca.infoway.messagebuilder.domainvalue.ActStatus>("111", ActStatus.CANCELLED, "222", "333", "444");
Assert.assertEquals(cs1, cs2);
}
}
| 42.941704 | 190 | 0.712615 |
036a40e62e4cc1db62b208f80a078710c21c4735 | 7,524 | package com.gaohui.main;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.gaohui.badgeview.BadgeView;
import com.gaohui.xtablayout.R;
import com.gaohui.xtablayout.XTabLayout;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private TabLayout tabLayoutOne;
private TabLayout tabLayoutTwo;
private TabLayout tabLayoutThree;
private XTabLayout tabLayoutFour;
private XTabLayout tabLayoutFive;
private ViewPager viewPager;
private BadgeView redDotBadgeView;
private BadgeView redNumberBadgeView;
private String[] strArray = new String[]{"关注", "推荐", "视频", "直播", "图片", "段子", "精华", "热门"};
private List<String> stringList = new ArrayList<>();
private List<Fragment> fragmentList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void initViews() {
tabLayoutOne = findViewById(R.id.tabsOne);
tabLayoutTwo = findViewById(R.id.tabsTwo);
tabLayoutThree = findViewById(R.id.tabsThree);
tabLayoutFour = findViewById(R.id.tabsFour);
tabLayoutFive = findViewById(R.id.tabsFive);
viewPager = findViewById(R.id.viewPager);
initData();
IndexPagerAdapter indexPagerAdapter = new IndexPagerAdapter(getSupportFragmentManager(),stringList,fragmentList);
viewPager.setAdapter(indexPagerAdapter);
tabLayoutOne.setupWithViewPager(viewPager);
tabLayoutTwo.setupWithViewPager(viewPager);
tabLayoutThree.setupWithViewPager(viewPager);
tabLayoutFour.setupWithViewPager(viewPager);
tabLayoutFive.setupWithViewPager(viewPager);
tabLayoutTwo.post(new Runnable() {
@Override
public void run() {
try {
//了解源码得知 线的宽度是根据 tabView的宽度来设置的
LinearLayout mTabStrip = (LinearLayout) tabLayoutTwo.getChildAt(0);
int dp10 = dip2px(tabLayoutTwo.getContext(), 10);
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
View tabView = mTabStrip.getChildAt(i);
//拿到tabView的mTextView属性 tab的字数不固定一定用反射取mTextView
Field mTextViewField =
tabView.getClass().getDeclaredField("mTextView");
mTextViewField.setAccessible(true);
TextView mTextView = (TextView) mTextViewField.get(tabView);
tabView.setPadding(0, 0, 0, 0);
//因为我想要的效果是 字多宽线就多宽,所以测量mTextView的宽度
int width = 0;
width = mTextView.getWidth();
if (width == 0) {
mTextView.measure(0, 0);
width = mTextView.getMeasuredWidth();
}
//设置tab左右间距为10dp 注意这里不能使用Padding
// 因为源码中线的宽度是根据 tabView的宽度来设置的
LinearLayout.LayoutParams params =
(LinearLayout.LayoutParams) tabView.getLayoutParams();
params.width = width ;
params.leftMargin = dp10;
params.rightMargin = dp10;
tabView.setLayoutParams(params);
tabView.invalidate();
}
} catch (Exception e) {
}
}
});
tabLayoutThree.post(new Runnable() {
@Override
public void run() {
try {
Class<?> tablayout = tabLayoutThree.getClass();
Field tabStrip = tablayout.getDeclaredField("mTabStrip");
tabStrip.setAccessible(true);
LinearLayout ll_tab= (LinearLayout) tabStrip.get(tabLayoutThree);
for (int i = 0; i < ll_tab.getChildCount(); i++) {
View child = ll_tab.getChildAt(i);
child.setPadding(0,0,0,0);
LinearLayout.LayoutParams params = new
LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT,1);
params.setMarginStart(dip2px(MainActivity.this,1f));
params.setMarginEnd(dip2px(MainActivity.this,15f));
child.setLayoutParams(params);
child.invalidate();
}
} catch (Exception e) {
}
}
});
//add normal badgeView
if(redDotBadgeView == null) {
XTabLayout.Tab tab = tabLayoutFive.getTabAt(0);
if(tab != null && tab.getView() != null) {
redDotBadgeView = new BadgeView(this,tab.getView());
redDotBadgeView.setBadgeMargin(BadgeView.POSITION_TOP_RIGHT);
redDotBadgeView.setBadgeMargin(0, 0);
redDotBadgeView.setOvalShape(3);
redDotBadgeView.show();
}
}
//add number badgeView
if(redNumberBadgeView == null) {
XTabLayout.Tab tab = tabLayoutFive.getTabAt(1);
if(tab != null && tab.getTabView() != null) {
redNumberBadgeView = new BadgeView(this,tab.getTabView());
redNumberBadgeView.setBadgeMargin( BadgeView.POSITION_TOP_RIGHT);
redNumberBadgeView.setBadgeMargin(dip2px(this,8f), 0);
redNumberBadgeView.setGravity(Gravity.CENTER);
redNumberBadgeView.setText("9");
redNumberBadgeView.show();
}
}
}
private void initData() {
stringList.addAll(Arrays.asList(strArray));
for (int i=0;i<stringList.size();i++) {
Fragment fragment = EmptyFragment.newInstance(i);
fragmentList.add(fragment);
}
}
class IndexPagerAdapter extends FragmentPagerAdapter {
private List<String> titleList;
public IndexPagerAdapter(FragmentManager fm,List<String> titleList,List<Fragment> fragmentList) {
super(fm);
this.titleList = titleList;
}
@Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
@Override
public int getCount() {
return titleList.size();
}
@Override
public CharSequence getPageTitle(int position) {
return titleList.get(position);
}
}
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
}
| 35.658768 | 121 | 0.584264 |
a7531699fd4c43d843c829feafd3133196d48251 | 2,833 | package me.RonanCraft.Pueblos.player.command.types;
import me.RonanCraft.Pueblos.Pueblos;
import me.RonanCraft.Pueblos.inventory.PueblosInventory;
import me.RonanCraft.Pueblos.player.command.PueblosCommand;
import me.RonanCraft.Pueblos.player.command.PueblosCommandHelpable;
import me.RonanCraft.Pueblos.resources.PermissionNodes;
import me.RonanCraft.Pueblos.resources.claims.*;
import me.RonanCraft.Pueblos.resources.claims.ClaimMain;
import me.RonanCraft.Pueblos.resources.files.msgs.MessagesCore;
import me.RonanCraft.Pueblos.resources.files.msgs.MessagesHelp;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.*;
public class CmdInfo implements PueblosCommand, PueblosCommandHelpable {
//Opens a GUI to view claim information
public String getName() {
return "info";
}
public void execute(CommandSender sendi, String label, String[] args) {
ClaimHandler handler = Pueblos.getInstance().getClaimHandler();
Player p = (Player) sendi;
ClaimMain claim = handler.getClaimMain(p.getLocation());
if (claim != null) {
if (claim.isMember(p)) {
//---- JUNK CLAIM MEMBER
/*if (claim.getMembers().size() == 0) {
ClaimMember member = new ClaimMember(p.getUniqueId(), p.getName(), Calendar.getInstance().getTime(), false, claim);
member.setFlag(CLAIM_FLAG_MEMBER.ALLOW_BED, true, true);
claim.addMember(member, true);
Pueblos.getInstance().getSystems().getClaimDatabase().updateMembers(claim);
}*/
//----
PueblosInventory.CLAIM.open(p, claim, true);
} else {
if (claim.isAdminClaim())
if (PermissionNodes.ADMIN_CLAIM.check(sendi))
PueblosInventory.CLAIM.open(p, claim, true);
else
MessagesCore.CLAIM_PERMISSION_ADMINCLAIM.send(sendi, claim);
else
MessagesCore.CLAIM_PERMISSION_CLAIM.send(sendi, claim);
}
} else {
List<Claim> claims = handler.getClaims(p.getUniqueId());
if (!claims.isEmpty()) {
if (claims.size() == 1)
PueblosInventory.CLAIM.open(p, claims.get(0), true);
else
PueblosInventory.CLAIM_SELECT.open(p, claims, true);
} else
MessagesCore.CLAIM_NONE.send(sendi);
}
}
public boolean permission(CommandSender sendi) {
return PermissionNodes.USE.check(sendi);
}
@Override
public String getHelp() {
return MessagesHelp.INFO.get();
}
@Override
public boolean isPlayerOnly() {
return true;
}
}
| 37.773333 | 135 | 0.617014 |
31ca33fe7ce2a1b9a122084f3ddee723b50a7f98 | 473 | package com.sondertara.joya.core.model;
import lombok.Data;
import java.io.Serializable;
import java.util.Map;
/**
* the data of one table
*
* @author huangxiaohu
* @date 2021/11/15 16:34
* @since 1.0.0
*/
@Data
public final class TableStruct implements Serializable {
private String tableName;
/** entity className */
private String className;
/** the columns map key : the fieldName value: the table columnName */
private Map<String, String> fields;
}
| 20.565217 | 72 | 0.716702 |
c1e4af307a03417e1a40d8f956d0616ffb8b428d | 1,904 | /*
* Copyright 2018-2019 Wave Software
*
* 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 pl.wavesoftware.utils.stringify.impl.jpa;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import pl.wavesoftware.utils.stringify.impl.lang.LangModule;
import pl.wavesoftware.utils.stringify.spi.JpaLazyChecker;
import java.util.Collections;
import java.util.HashSet;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.function.Supplier;
/**
* @author <a href="mailto:[email protected]">Krzysztof Suszynski</a>
* @since 2.0.0
*/
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
final class JpaLazyCheckersSupplier implements Supplier<JpaLazyCheckers> {
private static final Supplier<Set<JpaLazyChecker>> IMPLS = LangModule.INSTANCE.lazy(
JpaLazyCheckersSupplier::computeImplementations
);
private final JpaLazyChecker fallback;
@Override
public JpaLazyCheckers get() {
return new JpaLazyCheckersImpl(IMPLS, fallback);
}
private static Set<JpaLazyChecker> computeImplementations() {
Set<JpaLazyChecker> impls = new HashSet<>();
impls.add(new HibernateLazyChecker());
ServiceLoader<JpaLazyChecker> serviceLoader = ServiceLoader.load(JpaLazyChecker.class);
for (JpaLazyChecker checker : serviceLoader) {
impls.add(checker);
}
return Collections.unmodifiableSet(impls);
}
}
| 33.403509 | 91 | 0.766282 |
dc0b6f490d5d5832836fdcfa670dd152c9a42054 | 2,282 | package com.example.anan.AAChartCore.AAChartCoreLib.AAOptionsModel;
public class AADataLabels {
public Boolean enabled;
public Boolean inside;
public AAStyle style;
public String format;
public Float rotation;
public Boolean allowOverlap;
public Boolean useHTML;
public Float distance;
public String verticalAlign;
public Float x;
public Float y;
public String color;
public String backgroundColor;
public String borderColor;
public Float borderRadius;
public Float borderWidth;
public String shape;
public AADataLabels inside(Boolean prop) {
inside = prop;
return this;
}
public AADataLabels enabled(Boolean prop) {
enabled = prop;
return this;
}
public AADataLabels style(AAStyle prop) {
style = prop;
return this;
}
public AADataLabels format(String prop) {
format = prop;
return this;
}
public AADataLabels rotation(Float prop) {
rotation = prop;
return this;
}
public AADataLabels allowOverlap(Boolean prop) {
allowOverlap = prop;
return this;
}
public AADataLabels useHTML(Boolean prop) {
useHTML = prop;
return this;
}
public AADataLabels distance(Float prop) {
distance = prop;
return this;
}
public AADataLabels verticalAlign(String prop) {
verticalAlign = prop;
return this;
}
public AADataLabels x(Float prop) {
x = prop;
return this;
}
public AADataLabels y(Float prop) {
y = prop;
return this;
}
public AADataLabels color(String prop) {
color = prop;
return this;
}
public AADataLabels backgroundColor(String prop) {
backgroundColor = prop;
return this;
}
public AADataLabels borderColor(String prop) {
borderColor = prop;
return this;
}
public AADataLabels borderRadius(Float prop) {
borderRadius = prop;
return this;
}
public AADataLabels borderWidth(Float prop) {
borderWidth = prop;
return this;
}
public AADataLabels shape(String prop) {
shape = prop;
return this;
}
}
| 21.12963 | 67 | 0.612621 |
0b25598625ea4d4790131efcd1f19f7bca64240a | 347 | // Locator2.java - extended Locator
// http://www.saxproject.org
// Public Domain: no warranty.
// $Id: Locator2.java,v 1.5 2004/03/17 14:30:10 dmegginson Exp $
package org.xml.sax.ext;
public interface Locator2
extends org.xml.sax.Locator
{
public abstract java.lang.String getXMLVersion();
public abstract java.lang.String getEncoding();
}
| 26.692308 | 64 | 0.743516 |
b98b68f537aedaa6bf1307314614e1dc1707bb15 | 5,121 | package org.gratitude.ui.adapter;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import org.gratitude.R;
import org.gratitude.data.model.projects.Project;
import org.gratitude.databinding.ProjectItemBinding;
import org.gratitude.utils.ImageHandler;
import java.util.ArrayList;
import java.util.List;
public class ProjectsAdapter extends RecyclerView.Adapter<ProjectsAdapter.ProjectHolder>{
private Context mContext;
private ArrayList<Project> mProject;
// Allows to remember the last item shown on screen
private int lastPosition = -1;
public ProjectsAdapter(Context context, List<Project> projectList) {
mContext = context;
mProject = new ArrayList<>(projectList);
}
@NonNull
@Override
public ProjectHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
ProjectItemBinding mBinding = DataBindingUtil.inflate(inflater,
R.layout.project_item, parent, false);
return new ProjectHolder(mBinding);
}
@Override
public void onBindViewHolder(@NonNull ProjectHolder holder, int position) {
holder.bind(position);
setAnimation(holder.itemView, position);
}
public void setProjectList(List<Project> projectList){
mProject.addAll(projectList);
}
public void setNewProjectList(List<Project> projectList){
mProject.clear();
mProject.addAll(projectList);
this.notifyDataSetChanged();
}
/**
* Here is the key method to apply the animation
*/
private void setAnimation(View viewToAnimate, int position)
{
// If the bound view wasn't previously displayed on screen, it's animated
if (position > lastPosition)
{
Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.item_animation_from_bottom);
viewToAnimate.startAnimation(animation);
lastPosition = position;
}
}
@Override
public int getItemCount() {
return mProject != null ? mProject.size() : 0;
}
public Project getItem(int position) {
return mProject.get(position);
}
public class ProjectHolder extends RecyclerView.ViewHolder{
private final ProjectItemBinding mBinding;
private ProjectHolder(ProjectItemBinding binding) {
super(binding.getRoot());
this.mBinding = binding;
}
public void bind(int position){
final Project project = mProject.get(position);
double result = ((project.getFunding() / project.getGoal()) * 100);
int progress;
if(result > 0 && result < 1) {
progress = 1;
} else {
progress = (int) result;
}
mBinding.includeHeader.projectTitle.setText(project.getTitle());
if (progress < 100) {
String text = String.format(mContext.getString(R.string.money_raised_text),
String.valueOf(project.getFunding()),
String.valueOf(project.getGoal()));
mBinding.includeRaised.moneyRaised.setText(Html.fromHtml(text));
} else {
String text = String.format(mContext.getString(R.string.money_raised_text),
String.valueOf(project.getFunding()),
String.valueOf(project.getGoal()));
mBinding.includeRaised.moneyRaised.setText(Html.fromHtml(text));
//goalReached();
}
ImageHandler.projectImageHandler(mContext, mBinding.includeHeader.projectImageview, project);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mBinding.includeRaised.moneyProgressBar.setProgress(progress, true);
} else {
mBinding.includeRaised.moneyProgressBar.setProgress(progress);
}
mBinding.includeRaised.share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, project.getProjectLink());
sendIntent.setType("text/plain");
mContext.startActivity(
Intent.createChooser(
sendIntent, mContext.getString(R.string.share_to)));
}
});
}
@Override
public String toString() {
return super.toString();
}
}
}
| 34.14 | 108 | 0.633079 |
ef0f5da1c5134d5e5b5cce8e57fe7ca52d74329f | 1,372 | package org.apdoer.condition.quot.source.deserializer.impl;
import lombok.extern.slf4j.Slf4j;
import org.apdoer.common.service.util.JacksonUtil;
import org.apdoer.condition.common.model.dto.LatestPriceDto;
import org.apdoer.condition.quot.payload.QuotPriceMessageSourcePayload;
import org.apdoer.condition.quot.source.deserializer.ZmqDeserializer;
@Slf4j
public class TickPriceDeserializer implements ZmqDeserializer {
private static final long WARN_REALTIME_INTER = 60000L;
@Override
public QuotPriceMessageSourcePayload deserialize(String source) {
if (null != source) {
return this.buildMessageSourcePayload(source);
} else {
return null;
}
}
private QuotPriceMessageSourcePayload buildMessageSourcePayload(String source) {
//log.info("latestPrice origin data[{}]", source);
LatestPriceDto latestPriceDto = JacksonUtil.jsonToObj(source, LatestPriceDto.class);
// if (System.currentTimeMillis() - NumberUtils.microToMil(latestPriceDto.getTimestamp()) > WARN_REALTIME_INTER) {
// log.error("index price later, data={}", source);
// }
QuotPriceMessageSourcePayload payload = new QuotPriceMessageSourcePayload();
payload.setMessageType(latestPriceDto.getMessageType());
payload.setData(latestPriceDto);
return payload;
}
}
| 39.2 | 121 | 0.73105 |
9b16b8d72bb242e01fab3aba25bcbc6474884c91 | 318 | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Write your main program here. Implementing your own classes will be very useful.
Scanner scanner = new Scanner(System.in);
UserInterface ui = new UserInterface(scanner);
ui.start();
}
}
| 26.5 | 91 | 0.657233 |
77de0b64d2582ffb13f11909a79428780190c4c2 | 6,645 | //
// ========================================================================
// Copyright (c) 1995-2018 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.client.util;
import org.eclipse.jetty.client.AuthenticationProtocolHandler;
import org.eclipse.jetty.client.api.Authentication;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.util.Attributes;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.ietf.jgss.GSSContext;
import org.ietf.jgss.GSSCredential;
import org.ietf.jgss.GSSException;
import org.ietf.jgss.GSSManager;
import org.ietf.jgss.GSSName;
import org.ietf.jgss.Oid;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.Base64;
public class SpnegoAuthentication implements Authentication
{
public static final Logger LOG = Log.getLogger(AuthenticationProtocolHandler.class);
private static final String SPNEGO_OID = "1.3.6.1.5.5.2";
private GSSCredential gssCredential;
private boolean useCanonicalHostName;
private boolean stripPort;
public SpnegoAuthentication(GSSCredential gssCredential, boolean useCanonicalHostName, boolean stripPort)
{
this.gssCredential = gssCredential;
this.useCanonicalHostName = useCanonicalHostName;
this.stripPort = stripPort;
}
@Override
public boolean matches(String type, URI uri, String realm)
{
return "Negotiate".equals(type);
}
@Override
public Result authenticate(Request request, ContentResponse response, HeaderInfo headerInfo, Attributes context)
{
String challenge = headerInfo.getBase64();
if (challenge == null)
challenge = "";
byte[] input = Base64.getDecoder().decode(challenge);
byte[] token;
String authServer = request.getHost();
if (useCanonicalHostName)
{
try
{
authServer = resolveCanonicalHostname(authServer);
}
catch (final UnknownHostException ignore)
{
}
}
if (!stripPort)
{
authServer = authServer + ":" + request.getPort();
}
GSSContext gssContext = (GSSContext)context.getAttribute(GSSContext.class.getName());
if (gssContext != null)
{
try
{
token = gssContext.initSecContext(input, 0, input.length);
}
catch (GSSException gsse)
{
throw new IllegalStateException(gsse.getMessage(), gsse);
}
}
else
{
final GSSManager manager = GSSManager.getInstance();
try
{
gssContext = createGSSContext(manager, new Oid(SPNEGO_OID), authServer);
token = gssContext.initSecContext(input, 0, input.length);
context.setAttribute(GSSContext.class.getName(), gssContext);
}
catch (GSSException gsse)
{
throw new IllegalStateException(gsse.getMessage(), gsse);
}
}
return new Result()
{
@Override
public URI getURI()
{
// Since Kerberos is connection based authentication, sub-sequence requests won't need to resend the token in header
// by return null, the ProtocolHandler won't try to apply this result on sequence requests
return null;
}
@Override
public void apply(Request request)
{
final String tokenstr = Base64.getEncoder().encodeToString(token);
if (LOG.isDebugEnabled())
{
LOG.info("Sending response '" + tokenstr + "' back to the auth server");
}
request.header(headerInfo.getHeader().asString(), "Negotiate " + tokenstr);
}
};
}
@Override
public boolean isMultipleRounds()
{
return true;
}
protected GSSContext createGSSContext(GSSManager manager, Oid oid, String authServer) throws GSSException
{
GSSName serverName = manager.createName("HTTP@" + authServer, GSSName.NT_HOSTBASED_SERVICE);
final GSSContext gssContext = manager.createContext(serverName.canonicalize(oid), oid, gssCredential,
GSSContext.DEFAULT_LIFETIME);
gssContext.requestMutualAuth(true);
return gssContext;
}
private String resolveCanonicalHostname(final String host) throws UnknownHostException
{
final InetAddress in = InetAddress.getByName(host);
final String canonicalServer = in.getCanonicalHostName();
if (in.getHostAddress().contentEquals(canonicalServer))
{
return host;
}
return canonicalServer;
}
}
| 40.518293 | 148 | 0.51392 |
ad3f59554401aaf4d4d30ac35de93a37221b355d | 967 | package com.liuscoding.springcloud.service.impl;
import com.liuscoding.springcloud.service.IMessageProvider;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.MessageBuilder;
import java.util.UUID;
/**
* @className: MessageProviderImpl
* @description:
* @author: liusCoding
* @create: 2020-06-10 12:33
*/
@EnableBinding(Source.class)
public class MessageProviderImpl implements IMessageProvider {
private final MessageChannel output;
public MessageProviderImpl(MessageChannel output) {
this.output = output;
}
@Override
public String send() {
String serial = UUID.randomUUID().toString();
output.send(MessageBuilder.withPayload(serial).build());
System.out.println("****************serial:"+serial);
return serial;
}
}
| 27.628571 | 65 | 0.736298 |
400df83562e7e428bde815416d0c987ce83b76a3 | 3,599 | package controllers;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import views.html.scoreScreen;
import views.html.loginScreen;
import views.html.createUserScreen;
import views.html.gameScreen;
import jpa.Score;
import models.GameForm;
import models.ScoreForm;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Result;
import services.ScorePersistenceService;
@Named
public class Application extends Controller {
private static final Logger log = LoggerFactory.getLogger(LoginApplication.class);
/**
*
* Application class that controls score and game based actions such as
* moving pages, persisting data, grabbing data from the database, or
* resetting game variables.
*
*/
@Inject
private ScorePersistenceService scorePersist;
/**
* Checks if user is logged in, yes take to highscore page, no take to login
* page.
*/
public Result scoreScreen() {
String currentUser = session("username");
if (currentUser == null) {
log.info("Attempted Access to scoreScreen without authorization");
return redirect(routes.LoginApplication.loginScreen());
}
String score = session("score");
log.info("{} at Score Screen", currentUser);
return ok(scoreScreen.render("Snake Scoreboard", Form.form(ScoreForm.class), currentUser, score));
}
/**
* takes score from the game screen and sends info and user to highscore
* page when called in routes. Checks for
*
* @return
* returns a redirect to the scoreScreen if form has no errors
*/
public Result moveToScore() {
Form<GameForm> form = Form.form(GameForm.class).bindFromRequest();
if (form.hasErrors()) {
log.info("There are errors in game screen");
return badRequest(gameScreen.render("Snake Game", form));
}
String score = form.get().getScore();
session("score", score);
return redirect(routes.Application.scoreScreen());
}
/**
* Sets variables to start game every time it is called. Game used with
* credit to Copyright © Patrick Gillespie, http://patorjk.com
*/
public Result startGame() {
if (session("score") == null || session("score").equals("")) {
session("score", "0");
log.info("Score is set to 0");
}
return ok(gameScreen.render("Snake Game", Form.form(GameForm.class)));
}
/**
* Adds the score from the textbox in html to the database This checks for
* errors in the form and will persist the score if no errors are found
*/
public Result addScore() {
log.info("Attempting to add score to database");
Form<ScoreForm> form = Form.form(ScoreForm.class).bindFromRequest();
if (form.hasErrors()) {
log.info("Score Form has errors");
return badRequest(scoreScreen.render("Snake Scoreboard", form, session("username"), session("score")));
}
log.info("Score succesfully persisted");
Score score = new Score();
score.setUser(session("username"));
score.setScore(Double.parseDouble(session("score")));
scorePersist.saveScore(score);
return redirect(routes.Application.scoreScreen());
}
/**
* Returns all scores in database with usernames attatched
*
*/
public Result getScores() {
List<Score> scores = scorePersist.fetchAllScores();
return ok(play.libs.Json.toJson(scores));
}
/**
* Fetches all scores associated with a specific username.
*
*/
public Result getUserScores() {
String user = session("username");
log.debug("SESSION USERNAME {} FOUND", user);
List<Score> userScores = scorePersist.fetchUserScores(user);
return ok(play.libs.Json.toJson(userScores));
}
}
| 28.338583 | 106 | 0.716866 |
a505c96b5193eb9abfe752a13e4582c81fd13db0 | 220 | package game.item;
import org.joml.Vector3i;
public interface ItemModifier {
default public void onPlace(Vector3i pos, Vector3i pointedThingAbove) {
System.out.println("placing interface worked");
}
}
| 20 | 75 | 0.731818 |
3b41b9a2dc67e670e5d9945bba4e138be49686df | 2,409 | /**********************************************************************
Copyright (c) 2009 Andy Jefferson and others. 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.
Contributors:
...
**********************************************************************/
package org.datanucleus.store.rdbms.sql.expression;
import org.datanucleus.ClassNameConstants;
import org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping;
import org.datanucleus.store.rdbms.sql.SQLStatement;
import org.datanucleus.store.rdbms.sql.SQLTable;
/**
* Expression representing an enum field/property.
* An enum can be represented as a String or as a numeric hence requires its own expression.
* Implemented as an internal delegate of the correct root expression type.
*/
public class EnumExpression extends DelegatedExpression
{
/**
* Constructor for an expression for an enum field/property.
* @param stmt The SQL statement
* @param table Table containing the enum
* @param mapping Mapping for the enum
*/
public EnumExpression(SQLStatement stmt, SQLTable table, JavaTypeMapping mapping)
{
super(stmt, table, mapping);
if (mapping.getJavaTypeForDatastoreMapping(0).equals(ClassNameConstants.JAVA_LANG_STRING))
{
delegate = new StringExpression(stmt, table, mapping);
}
else
{
delegate = new NumericExpression(stmt, table, mapping);
}
}
@Override
public void setJavaTypeMapping(JavaTypeMapping mapping)
{
super.setJavaTypeMapping(mapping);
// Reset the delegate in case it has changed
if (mapping.getJavaTypeForDatastoreMapping(0).equals(ClassNameConstants.JAVA_LANG_STRING))
{
delegate = new StringExpression(stmt, table, mapping);
}
else
{
delegate = new NumericExpression(stmt, table, mapping);
}
}
} | 36.5 | 98 | 0.672063 |
9c3830a90e334853cd4566082e76f3dd7932426d | 5,677 | /*
* 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.scavi.de.gw2imp.presenter;
import com.scavi.de.gw2imp.R;
import com.scavi.de.gw2imp.model.OverviewModel;
import com.scavi.de.gw2imp.ui.view.IOverviewView;
import javax.annotation.ParametersAreNonnullByDefault;
import javax.inject.Inject;
@ParametersAreNonnullByDefault
public class OverviewPresenter {
private final IOverviewView mView;
private final OverviewModel mModel;
/**
* Constructor
*
* @param view the view for the application overview
* @param model the model for the application overview
*/
@Inject
public OverviewPresenter(final IOverviewView view,
final OverviewModel model) {
mView = view;
mModel = model;
}
/**
* Loads and updates the status data
*/
public void loadStatusData() {
Runnable statusLoadAndProcessor = createLoadProcessor();
mModel.getExecutorAccess().getBackgroundThreadExecutor().execute(statusLoadAndProcessor);
}
/**
* Creates a runnable that loads all status information in the background (not UI process).
* Based on the loaded information in the background a runnable will be created to update the
* view. This runnable will be added to a UI thread updater.
*
* @return the status runnable
*/
private Runnable createLoadProcessor() {
return () -> {
int itemCount = mModel.selectItemCount();
int itemPriceCount = mModel.selectItemPriceCount();
int itemHistoryCount = mModel.selectItemPriceHistoryCount();
boolean isSearchIndexComplete = mModel.selectIsSearchIndexComplete();
boolean isWordIndexComplete = mModel.determineWordIndex();
Runnable informationUiUpdater = createInformationUiUpdater(itemCount, itemPriceCount,
itemHistoryCount);
Runnable statusUiUpdater = createSearchStatusUiUpdater(isSearchIndexComplete);
Runnable wordUiUpdater = createWordStatusUiUpdater(isWordIndexComplete);
mModel.getExecutorAccess().getUiThreadExecutor().execute(informationUiUpdater);
mModel.getExecutorAccess().getUiThreadExecutor().execute(statusUiUpdater);
mModel.getExecutorAccess().getUiThreadExecutor().execute(wordUiUpdater);
};
}
/**
* Creates a runnable to update the UI with the information
*
* @param itemCount the amount of distinct items in the database
* @param itemPriceCount the count of items in the item price table
* @param itemHistoryCount the count of items in the history item price table
* @return the runnable to update the UI with the information
*/
private Runnable createInformationUiUpdater(final int itemCount,
final int itemPriceCount,
final int itemHistoryCount) {
return () -> {
mView.updateItemCount(itemCount);
mView.updateItemPriceCount(itemPriceCount);
mView.updateHistoryCount(itemHistoryCount);
};
}
/**
* Creates a runnable to update the UI with the status
*
* @param isSearchIndexComplete <code>true</code> if the search index is complete <br>
* <code>false</code> if the update of the search index is still
* not complete
* @return the runnable to update the status
*/
private Runnable createSearchStatusUiUpdater(final boolean isSearchIndexComplete) {
return () -> {
int resourceId;
int color;
// determine text & color depending on the search index flag
if (isSearchIndexComplete) {
resourceId = R.string.overview_index_sync_complete;
color = R.color.core_highlight_3;
} else {
resourceId = R.string.overview_index_sync_incomplete;
color = R.color.core_highlight_1;
}
mView.updateSearchIndexStatus(resourceId, color);
};
}
/**
* Creates a runnable to update the UI with the status
*
* @param isWordIndexComplete <code>true</code> if the word index is complete <br>
* <code>false</code> if the update of the word index is still
* not complete
* @return the runnable to update the status
*/
private Runnable createWordStatusUiUpdater(final boolean isWordIndexComplete) {
return () -> {
int resourceId;
int color;
// determine text & color depending on the search index flag
if (isWordIndexComplete) {
resourceId = R.string.overview_index_sync_complete;
color = R.color.core_highlight_3;
} else {
resourceId = R.string.overview_index_sync_incomplete;
color = R.color.core_highlight_1;
}
mView.updateWordIndexStatus(resourceId, color);
};
}
}
| 39.423611 | 97 | 0.638365 |
bd6dd36738662191d4b0672fb6c0e93cd1141427 | 3,243 | package org.ethereum.beacon.test.runner.ssz;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
import org.ethereum.beacon.consensus.BeaconChainSpec;
import org.ethereum.beacon.ssz.SSZBuilder;
import org.ethereum.beacon.ssz.SSZSerializer;
import org.ethereum.beacon.ssz.access.SSZField;
import org.ethereum.beacon.ssz.access.container.SSZSchemeBuilder;
import org.ethereum.beacon.ssz.annotation.SSZSerializable;
import org.ethereum.beacon.test.runner.Runner;
import org.ethereum.beacon.test.type.TestCase;
import org.ethereum.beacon.test.type.ssz.SszGenericCase;
import java.io.IOException;
import java.util.Optional;
import static org.ethereum.beacon.test.SilentAsserts.assertEquals;
/**
* TestRunner for Boolean {@link SszGenericCase}
*
* <p>Test format description: <a
* href="https://github.com/ethereum/eth2.0-specs/tree/dev/specs/test_formats/ssz_generic">https://github.com/ethereum/eth2.0-specs/tree/dev/specs/test_formats/ssz_generic</a>
*/
public class SszBooleanRunner implements Runner {
private SszGenericCase testCase;
private BeaconChainSpec spec;
private ObjectMapper yamlMapper = new YAMLMapper();
private SSZSchemeBuilder.SSZScheme currentScheme;
private SSZSerializer sszSerializer;
public SszBooleanRunner(TestCase testCase, BeaconChainSpec spec) {
if (!(testCase instanceof SszGenericCase)) {
throw new RuntimeException("TestCase runner accepts only SszGenericCase.class as input!");
}
if (!((SszGenericCase) testCase).getTypeName().startsWith("bool")) {
throw new RuntimeException(
"Type " + ((SszGenericCase) testCase).getTypeName() + " is not supported");
}
this.testCase = (SszGenericCase) testCase;
this.spec = spec;
SSZBuilder builder = new SSZBuilder();
builder.withSSZSchemeBuilder(clazz -> currentScheme);
this.sszSerializer = builder.buildSerializer();
}
private void activateSchemeMock() {
this.currentScheme = new SSZSchemeBuilder.SSZScheme();
SSZField field = new SSZField(Boolean.class, null, null, null, "value", "getValue");
currentScheme.getFields().add(field);
}
public Optional<String> run() {
activateSchemeMock();
if (testCase.isValid()) {
Boolean expected = null;
try {
expected = yamlMapper.readValue(testCase.getValue(), Boolean.class);
} catch (IOException e) {
throw new RuntimeException("Unable to read expected value from file", e);
}
BooleanTester actual = sszSerializer.decode(testCase.getSerialized(), BooleanTester.class);
return assertEquals(expected, actual.getValue());
} else {
try {
BooleanTester actual = sszSerializer.decode(testCase.getSerialized(), BooleanTester.class);
} catch (Exception ex) {
return Optional.empty();
}
return Optional.of(
"SSZ encoded data ["
+ testCase.getSerialized()
+ "] is not valid but was successfully decoded.");
}
}
@SSZSerializable
public static class BooleanTester {
private Boolean value;
public Boolean getValue() {
return value;
}
public void setValue(Boolean value) {
this.value = value;
}
}
}
| 34.870968 | 175 | 0.720012 |
c34b1743a643285b5e5bbabbd1f055f1ee718948 | 1,811 | /**
* 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.tajo.master.event;
import org.apache.hadoop.yarn.api.records.Priority;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.tajo.ExecutionBlockId;
import java.util.Map;
public class GrouppedContainerAllocatorEvent
extends ContainerAllocationEvent {
private final Map<String, Integer> requestMap;
public GrouppedContainerAllocatorEvent(ContainerAllocatorEventType eventType,
ExecutionBlockId executionBlockId,
Priority priority,
Resource resource,
Map<String, Integer> requestMap,
boolean isLeafQuery, float progress) {
super(eventType, executionBlockId, priority,
resource, requestMap.size(), isLeafQuery, progress);
this.requestMap = requestMap;
}
public Map<String, Integer> getRequestMap() {
return this.requestMap;
}
}
| 39.369565 | 79 | 0.684152 |
793b513f50efbc6521b8940ce311615fac36fa9f | 2,521 | package info.unterrainer.commons.datastructures;
public class Interval<T extends Comparable<T>> {
private T maximalValue;
private T minimalValue;
/**
* Initializes a new instance of the {@link Interval} structure.
*
* @param min the minimal value
* @param max the maximal value
* @throws IllegalArgumentException if the given maximal-value is smaller than
* the given minimal-value
*/
public Interval(final T min, final T max) {
if (min.compareTo(max) > 0 || max.compareTo(min) < 0)
throw new IllegalArgumentException("Min has to be smaller than or equal to max.");
minimalValue = min;
maximalValue = max;
}
/**
* Gets or sets the minimal value. Adjusts the maximal-value as well if it
* should currently be smaller than the given value.
*
* @return the minimal value of this interval
*/
public T getMin() {
return minimalValue;
}
public void setMin(final T value) {
minimalValue = value;
if (value.compareTo(maximalValue) > 0)
maximalValue = value;
}
/**
* Gets or sets the maximal value. Adjusts the minimal-value as well if it
* should currently be smaller than the given value.
*
* @return the maximal value of this interval
*/
public T getMax() {
return maximalValue;
}
public void setMax(final T value) {
maximalValue = value;
if (value.compareTo(minimalValue) < 0)
minimalValue = value;
}
/**
* Clamps the given value to the {@link Interval}. If the value is greater than
* the interval's maximal-value, the interval's maximal-value is returned. If
* the value is smaller than the interval's minimal-value, the interval's
* minimal-value is returned.<br>
* If the value is null, null is returned.
*
* @param value the value
* @return the clamped value
*/
public T clamp(final T value) {
if (value == null)
return null;
if (value.compareTo(maximalValue) > 0)
return maximalValue;
if (value.compareTo(minimalValue) < 0)
return minimalValue;
return value;
}
/**
* Determines whether a specified value is in between the intervals
* boundaries.<br>
* If the specified value is null, false is returned.
*
* @param value the value
* @return true if the given value is in between the specified boundaries
*/
public boolean isInBetween(final T value) {
return value != null && value.compareTo(getMin()) >= 0 && value.compareTo(getMax()) <= 0;
}
@Override
public String toString() {
return "[" + minimalValue + ":" + maximalValue + "]";
}
}
| 26.819149 | 91 | 0.682666 |
546377aedb585eafead8327a445d795b7a6c574f | 10,545 | /*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.siddhi.extension.input.mapper.json;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.wso2.siddhi.core.ExecutionPlanRuntime;
import org.wso2.siddhi.core.SiddhiManager;
import org.wso2.siddhi.core.event.Event;
import org.wso2.siddhi.core.stream.output.StreamCallback;
import org.wso2.siddhi.core.util.EventPrinter;
import org.wso2.siddhi.core.util.transport.InMemoryBroker;
import org.wso2.siddhi.core.stream.input.source.InMemoryInputTransport;
import org.wso2.siddhi.query.api.ExecutionPlan;
import org.wso2.siddhi.query.api.definition.Attribute;
import org.wso2.siddhi.query.api.definition.StreamDefinition;
import org.wso2.siddhi.query.api.exception.ExecutionPlanValidationException;
import org.wso2.siddhi.query.api.execution.Subscription;
import org.wso2.siddhi.query.api.execution.io.Transport;
import org.wso2.siddhi.query.api.execution.io.map.Mapping;
import org.wso2.siddhi.query.compiler.SiddhiCompiler;
public class JsonInputMapperTestCase {
static final Logger log = Logger.getLogger(JsonInputMapperTestCase.class);
/**
* Expected input format:
* {'symbol': 'WSO2', 'price': 56.75, 'volume': 5, 'country': 'Sri Lanka'}
*/
@Test
public void subscriptionTest1() throws InterruptedException {
log.info("Subscription Test 1: Test an in memory transport with default json mapping");
Subscription subscription = SiddhiCompiler.parseSubscription(
"subscribe inMemory options (topic 'stock') " +
"map json " +
"insert into FooStream;");
ExecutionPlan executionPlan = ExecutionPlan.executionPlan();
executionPlan.defineStream(StreamDefinition.id("FooStream")
.attribute("symbol", Attribute.Type.STRING)
.attribute("price", Attribute.Type.FLOAT)
.attribute("volume", Attribute.Type.INT));
executionPlan.addSubscription(subscription);
SiddhiManager siddhiManager = new SiddhiManager();
siddhiManager.setExtension("inputtransport:inMemory", InMemoryInputTransport.class);
ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(executionPlan);
executionPlanRuntime.addCallback("FooStream", new StreamCallback() {
@Override
public void receive(Event[] events) {
EventPrinter.print(events);
}
});
executionPlanRuntime.start();
InMemoryBroker.publish("stock","{'symbol': 'WSO2', 'price': 56.75, 'volume': 5, 'country': 'Sri Lanka'}");
executionPlanRuntime.shutdown();
}
@Test(expected = ExecutionPlanValidationException.class)
public void subscriptionTest2() throws InterruptedException {
log.info("Subscription Test 2: Test an in memory transport with named and positional json mapping - expect " +
"exception");
Subscription subscription = SiddhiCompiler.parseSubscription(
"subscribe inMemory options (topic 'stock') " +
"map json '$.country', '$.price', '$.volume' as 'volume' " +
"insert into FooStream;");
// First two parameters are based on position and the last one is named parameter
ExecutionPlan executionPlan = ExecutionPlan.executionPlan();
executionPlan.defineStream(StreamDefinition.id("FooStream")
.attribute("symbol", Attribute.Type.STRING)
.attribute("price", Attribute.Type.FLOAT)
.attribute("volume", Attribute.Type.INT));
executionPlan.addSubscription(subscription);
SiddhiManager siddhiManager = new SiddhiManager();
siddhiManager.setExtension("inputtransport:inMemory", InMemoryInputTransport.class);
ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(executionPlan);
executionPlanRuntime.start();
InMemoryBroker.publish("stock","{'symbol': 'WSO2', 'price': 56.75, 'volume': 5, 'country': 'Sri Lanka'}");
executionPlanRuntime.shutdown();
}
/**
* Expected input format:
* {'symbol': 'WSO2', 'price': 56.75, 'volume': 5, 'country': 'Sri Lanka'}
*/
@Test
public void subscriptionTest3() throws InterruptedException {
log.info("Subscription Test 3: Test an in memory transport with custom positional json mapping");
Subscription subscription = SiddhiCompiler.parseSubscription(
"subscribe inMemory options(topic 'stock') " +
"map json '$.symbol', '$.price', '$.volume' " +
"insert into FooStream;");
ExecutionPlan executionPlan = ExecutionPlan.executionPlan();
executionPlan.defineStream(StreamDefinition.id("FooStream")
.attribute("output_symbol", Attribute.Type.STRING)
.attribute("price", Attribute.Type.FLOAT)
.attribute("volume", Attribute.Type.INT));
executionPlan.addSubscription(subscription);
SiddhiManager siddhiManager = new SiddhiManager();
siddhiManager.setExtension("inputtransport:inMemory", InMemoryInputTransport.class);
ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(executionPlan);
executionPlanRuntime.addCallback("FooStream", new StreamCallback() {
@Override
public void receive(Event[] events) {
EventPrinter.print(events);
}
});
executionPlanRuntime.start();
InMemoryBroker.publish("stock","{'symbol': 'WSO2', 'price': 56.75, 'volume': 5, 'country': 'Sri Lanka'}");
executionPlanRuntime.shutdown();
}
/**
* Expected input format:
* {'symbol': 'WSO2', 'price': 56.75, 'volume': 5, 'country': 'Sri Lanka'}
*/
@Test
public void subscriptionTest4() throws InterruptedException {
log.info("Subscription Test 4: Test an in memory transport with custom named json mapping");
Subscription subscription = SiddhiCompiler.parseSubscription(
"subscribe inMemory options(topic 'stock') " +
"map json '$.volume' as 'volume', '$.symbol' as 'symbol', '$.price' as 'price' " +
"insert into FooStream;");
ExecutionPlan executionPlan = ExecutionPlan.executionPlan();
executionPlan.defineStream(StreamDefinition.id("FooStream")
.attribute("symbol", Attribute.Type.STRING)
.attribute("price", Attribute.Type.FLOAT)
.attribute("volume", Attribute.Type.INT));
executionPlan.addSubscription(subscription);
SiddhiManager siddhiManager = new SiddhiManager();
siddhiManager.setExtension("inputtransport:inMemory", InMemoryInputTransport.class);
ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(executionPlan);
executionPlanRuntime.addCallback("FooStream", new StreamCallback() {
@Override
public void receive(Event[] events) {
EventPrinter.print(events);
}
});
executionPlanRuntime.start();
InMemoryBroker.publish("stock","{'country': 'Sri Lanka', 'symbol': 'WSO2', 'price': 56.75, 'volume': 5}");
executionPlanRuntime.shutdown();
}
@Test(expected = ExecutionPlanValidationException.class)
public void subscriptionTest5() throws InterruptedException {
log.info("Subscription Test 5: Test infer output stream using json mapping - expect exception");
Subscription subscription = Subscription.Subscribe(Transport.transport("inMemory").option("topic","stock"));
subscription.map(Mapping.format("json").map("volume", "$.volume").map("symbol", "$.symbol").map("price", "$" +
".price"));
subscription.insertInto("FooStream");
ExecutionPlan executionPlan = ExecutionPlan.executionPlan();
executionPlan.addSubscription(subscription);
SiddhiManager siddhiManager = new SiddhiManager();
siddhiManager.setExtension("inputtransport:inMemory", InMemoryInputTransport.class);
ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(executionPlan);
executionPlanRuntime.start();
InMemoryBroker.publish("stock","{'symbol': 'WSO2', 'price': 56.75, 'volume': 5, 'country': 'Sri Lanka'}");
executionPlanRuntime.shutdown();
}
@Test(expected = ExecutionPlanValidationException.class)
public void subscriptionTest6() throws InterruptedException {
log.info("Subscription Test 6: Test error in infer output stream using json mapping without mapping name" +
" - expect exception");
Subscription subscription = Subscription.Subscribe(Transport.transport("inMemory").option("topic","stock"));
subscription.map(Mapping.format("json").map("$.volume").map("$.symbol").map("$.price"));
subscription.insertInto("FooStream");
ExecutionPlan executionPlan = ExecutionPlan.executionPlan();
executionPlan.addSubscription(subscription);
SiddhiManager siddhiManager = new SiddhiManager();
siddhiManager.setExtension("inputtransport:inMemory", InMemoryInputTransport.class);
ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(executionPlan);
executionPlanRuntime.addCallback("FooStream", new StreamCallback() {
@Override
public void receive(Event[] events) {
EventPrinter.print(events);
}
});
executionPlanRuntime.start();
InMemoryBroker.publish("stock","{'symbol': 'WSO2', 'price': 56.75, 'volume': 5, 'country': 'Sri Lanka'}");
executionPlanRuntime.shutdown();
}
}
| 45.064103 | 118 | 0.672736 |
4ea12849dfe4eaaaadfadc9f9b2b9ff333295a50 | 509 | package io.penguinstats.model;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
@ApiModel(description = "The model for existence.")
public class Existence implements Serializable {
private static final long serialVersionUID = 1L;
private Boolean exist;
private Long openTime;
private Long closeTime;
}
| 21.208333 | 52 | 0.81336 |
10c885bee169b284b14211e75c1e1215c04c3ab7 | 851 | package com.stylefeng.guns.modular.foundation.service.impl;
import com.stylefeng.guns.modular.system.model.Material;
import com.stylefeng.guns.modular.system.dao.MaterialMapper;
import com.stylefeng.guns.modular.foundation.service.IMaterialService;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
/**
* <p>
* 材料表 服务实现类
* </p>
*
* @author stylefeng
* @since 2018-10-28
*/
@Service
public class MaterialServiceImpl extends ServiceImpl<MaterialMapper, Material> implements IMaterialService {
public List<Map<String, Object>> getMaterialList(Page<Material> page, String name, String orderByField,
boolean asc) {
return this.baseMapper.getMaterialList(page, name, orderByField, asc);
}
}
| 27.451613 | 108 | 0.788484 |
8de62f0d15589542664d18d2285048c9c23cd354 | 2,985 | /*
* Copyright 2015-2018 52°North Initiative for Geospatial Open Source
* Software GmbH
*
* 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.n52.svalbard.encode;
import com.google.common.collect.Sets;
import java.util.Set;
import net.opengis.sos.x10.DescribeSensorDocument;
import org.apache.xmlbeans.XmlObject;
import org.n52.shetland.ogc.sos.Sos1Constants;
import org.n52.shetland.ogc.sos.SosConstants;
import org.n52.shetland.ogc.sos.request.DescribeSensorRequest;
import org.n52.shetland.w3c.SchemaLocation;
import org.n52.svalbard.encode.exception.EncodingException;
/**
* @author <a href="mailto:[email protected]">Jan Schulte</a>
*/
public class DescribeSensorV1RequestEncoder extends AbstractSosV1RequestEncoder<DescribeSensorRequest> {
public DescribeSensorV1RequestEncoder() {
super(SosConstants.Operations.DescribeSensor.name(), DescribeSensorRequest.class);
}
@Override
protected Set<SchemaLocation> getConcreteSchemaLocations() {
return Sets.newHashSet();
}
@Override
protected XmlObject create(DescribeSensorRequest request) throws EncodingException {
DescribeSensorDocument doc = DescribeSensorDocument.Factory.newInstance(getXmlOptions());
DescribeSensorDocument.DescribeSensor descSens = doc.addNewDescribeSensor();
addVersion(descSens, request);
addService(descSens, request);
addProcedure(descSens, request);
addOutputFormat(descSens, request);
return doc;
}
private void addVersion(DescribeSensorDocument.DescribeSensor descSens, DescribeSensorRequest request) {
if (request.getVersion() != null) {
descSens.setVersion(request.getVersion());
} else {
descSens.setVersion(Sos1Constants.SERVICEVERSION);
}
}
private void addService(DescribeSensorDocument.DescribeSensor descSens, DescribeSensorRequest request) {
if (request.getService() != null) {
descSens.setService(request.getService());
} else {
descSens.setService(SosConstants.SOS);
}
}
private void addProcedure(DescribeSensorDocument.DescribeSensor descSens, DescribeSensorRequest request) {
descSens.setProcedure(request.getProcedure());
}
private void addOutputFormat(DescribeSensorDocument.DescribeSensor descSens, DescribeSensorRequest request) {
descSens.setOutputFormat(request.getProcedureDescriptionFormat());
}
}
| 37.78481 | 113 | 0.740034 |
114a66a555a7310b009728ff0952217d992c78c1 | 62,936 | // Copyright 2012 Citrix Systems, Inc. Licensed under the
// Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. Citrix Systems, Inc.
// reserves all rights not expressly granted by 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.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.xensource.xenapi;
import com.xensource.xenapi.Types.BadServerResponse;
import com.xensource.xenapi.Types.VersionException;
import com.xensource.xenapi.Types.XenAPIException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.apache.xmlrpc.XmlRpcException;
/**
* A storage repository
*
* @author Citrix Systems, Inc.
*/
public class SR extends XenAPIObject {
/**
* The XenAPI reference to this object.
*/
protected final String ref;
/**
* For internal use only.
*/
SR(String ref) {
this.ref = ref;
}
public String toWireString() {
return this.ref;
}
/**
* If obj is a SR, compares XenAPI references for equality.
*/
@Override
public boolean equals(Object obj)
{
if (obj != null && obj instanceof SR)
{
SR other = (SR) obj;
return other.ref.equals(this.ref);
} else
{
return false;
}
}
@Override
public int hashCode()
{
return ref.hashCode();
}
/**
* Represents all the fields in a SR
*/
public static class Record implements Types.Record {
public String toString() {
StringWriter writer = new StringWriter();
PrintWriter print = new PrintWriter(writer);
print.printf("%1$20s: %2$s\n", "uuid", this.uuid);
print.printf("%1$20s: %2$s\n", "nameLabel", this.nameLabel);
print.printf("%1$20s: %2$s\n", "nameDescription", this.nameDescription);
print.printf("%1$20s: %2$s\n", "allowedOperations", this.allowedOperations);
print.printf("%1$20s: %2$s\n", "currentOperations", this.currentOperations);
print.printf("%1$20s: %2$s\n", "VDIs", this.VDIs);
print.printf("%1$20s: %2$s\n", "PBDs", this.PBDs);
print.printf("%1$20s: %2$s\n", "virtualAllocation", this.virtualAllocation);
print.printf("%1$20s: %2$s\n", "physicalUtilisation", this.physicalUtilisation);
print.printf("%1$20s: %2$s\n", "physicalSize", this.physicalSize);
print.printf("%1$20s: %2$s\n", "type", this.type);
print.printf("%1$20s: %2$s\n", "contentType", this.contentType);
print.printf("%1$20s: %2$s\n", "shared", this.shared);
print.printf("%1$20s: %2$s\n", "otherConfig", this.otherConfig);
print.printf("%1$20s: %2$s\n", "tags", this.tags);
print.printf("%1$20s: %2$s\n", "smConfig", this.smConfig);
print.printf("%1$20s: %2$s\n", "blobs", this.blobs);
print.printf("%1$20s: %2$s\n", "localCacheEnabled", this.localCacheEnabled);
return writer.toString();
}
/**
* Convert a SR.Record to a Map
*/
public Map<String,Object> toMap() {
Map<String,Object> map = new HashMap<String,Object>();
map.put("uuid", this.uuid == null ? "" : this.uuid);
map.put("name_label", this.nameLabel == null ? "" : this.nameLabel);
map.put("name_description", this.nameDescription == null ? "" : this.nameDescription);
map.put("allowed_operations", this.allowedOperations == null ? new LinkedHashSet<Types.StorageOperations>() : this.allowedOperations);
map.put("current_operations", this.currentOperations == null ? new HashMap<String, Types.StorageOperations>() : this.currentOperations);
map.put("VDIs", this.VDIs == null ? new LinkedHashSet<VDI>() : this.VDIs);
map.put("PBDs", this.PBDs == null ? new LinkedHashSet<PBD>() : this.PBDs);
map.put("virtual_allocation", this.virtualAllocation == null ? 0 : this.virtualAllocation);
map.put("physical_utilisation", this.physicalUtilisation == null ? 0 : this.physicalUtilisation);
map.put("physical_size", this.physicalSize == null ? 0 : this.physicalSize);
map.put("type", this.type == null ? "" : this.type);
map.put("content_type", this.contentType == null ? "" : this.contentType);
map.put("shared", this.shared == null ? false : this.shared);
map.put("other_config", this.otherConfig == null ? new HashMap<String, String>() : this.otherConfig);
map.put("tags", this.tags == null ? new LinkedHashSet<String>() : this.tags);
map.put("sm_config", this.smConfig == null ? new HashMap<String, String>() : this.smConfig);
map.put("blobs", this.blobs == null ? new HashMap<String, Blob>() : this.blobs);
map.put("local_cache_enabled", this.localCacheEnabled == null ? false : this.localCacheEnabled);
return map;
}
/**
* Unique identifier/object reference
*/
public String uuid;
/**
* a human-readable name
*/
public String nameLabel;
/**
* a notes field containg human-readable description
*/
public String nameDescription;
/**
* list of the operations allowed in this state. This list is advisory only and the server state may have changed by the time this field is read by a client.
*/
public Set<Types.StorageOperations> allowedOperations;
/**
* links each of the running tasks using this object (by reference) to a current_operation enum which describes the nature of the task.
*/
public Map<String, Types.StorageOperations> currentOperations;
/**
* all virtual disks known to this storage repository
*/
public Set<VDI> VDIs;
/**
* describes how particular hosts can see this storage repository
*/
public Set<PBD> PBDs;
/**
* sum of virtual_sizes of all VDIs in this storage repository (in bytes)
*/
public Long virtualAllocation;
/**
* physical space currently utilised on this storage repository (in bytes). Note that for sparse disk formats, physical_utilisation may be less than virtual_allocation
*/
public Long physicalUtilisation;
/**
* total physical size of the repository (in bytes)
*/
public Long physicalSize;
/**
* type of the storage repository
*/
public String type;
/**
* the type of the SR's content, if required (e.g. ISOs)
*/
public String contentType;
/**
* true if this SR is (capable of being) shared between multiple hosts
*/
public Boolean shared;
/**
* additional configuration
*/
public Map<String, String> otherConfig;
/**
* user-specified tags for categorization purposes
*/
public Set<String> tags;
/**
* SM dependent data
*/
public Map<String, String> smConfig;
/**
* Binary blobs associated with this SR
*/
public Map<String, Blob> blobs;
/**
* True if this SR is assigned to be the local cache for its host
*/
public Boolean localCacheEnabled;
}
/**
* Get a record containing the current state of the given SR.
*
* @return all fields from the object
*/
public SR.Record getRecord(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.get_record";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toSRRecord(result);
}
/**
* Get a reference to the SR instance with the specified UUID.
*
* @param uuid UUID of object to return
* @return reference to the object
*/
public static SR getByUuid(Connection c, String uuid) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.get_by_uuid";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toSR(result);
}
/**
* Get all the SR instances with the given label.
*
* @param label label of object to return
* @return references to objects with matching names
*/
public static Set<SR> getByNameLabel(Connection c, String label) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.get_by_name_label";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(label)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toSetOfSR(result);
}
/**
* Get the uuid field of the given SR.
*
* @return value of the field
*/
public String getUuid(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.get_uuid";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toString(result);
}
/**
* Get the name/label field of the given SR.
*
* @return value of the field
*/
public String getNameLabel(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.get_name_label";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toString(result);
}
/**
* Get the name/description field of the given SR.
*
* @return value of the field
*/
public String getNameDescription(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.get_name_description";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toString(result);
}
/**
* Get the allowed_operations field of the given SR.
*
* @return value of the field
*/
public Set<Types.StorageOperations> getAllowedOperations(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.get_allowed_operations";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toSetOfStorageOperations(result);
}
/**
* Get the current_operations field of the given SR.
*
* @return value of the field
*/
public Map<String, Types.StorageOperations> getCurrentOperations(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.get_current_operations";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toMapOfStringStorageOperations(result);
}
/**
* Get the VDIs field of the given SR.
*
* @return value of the field
*/
public Set<VDI> getVDIs(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.get_VDIs";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toSetOfVDI(result);
}
/**
* Get the PBDs field of the given SR.
*
* @return value of the field
*/
public Set<PBD> getPBDs(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.get_PBDs";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toSetOfPBD(result);
}
/**
* Get the virtual_allocation field of the given SR.
*
* @return value of the field
*/
public Long getVirtualAllocation(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.get_virtual_allocation";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toLong(result);
}
/**
* Get the physical_utilisation field of the given SR.
*
* @return value of the field
*/
public Long getPhysicalUtilisation(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.get_physical_utilisation";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toLong(result);
}
/**
* Get the physical_size field of the given SR.
*
* @return value of the field
*/
public Long getPhysicalSize(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.get_physical_size";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toLong(result);
}
/**
* Get the type field of the given SR.
*
* @return value of the field
*/
public String getType(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.get_type";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toString(result);
}
/**
* Get the content_type field of the given SR.
*
* @return value of the field
*/
public String getContentType(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.get_content_type";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toString(result);
}
/**
* Get the shared field of the given SR.
*
* @return value of the field
*/
public Boolean getShared(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.get_shared";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toBoolean(result);
}
/**
* Get the other_config field of the given SR.
*
* @return value of the field
*/
public Map<String, String> getOtherConfig(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.get_other_config";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toMapOfStringString(result);
}
/**
* Get the tags field of the given SR.
*
* @return value of the field
*/
public Set<String> getTags(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.get_tags";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toSetOfString(result);
}
/**
* Get the sm_config field of the given SR.
*
* @return value of the field
*/
public Map<String, String> getSmConfig(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.get_sm_config";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toMapOfStringString(result);
}
/**
* Get the blobs field of the given SR.
*
* @return value of the field
*/
public Map<String, Blob> getBlobs(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.get_blobs";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toMapOfStringBlob(result);
}
/**
* Get the local_cache_enabled field of the given SR.
*
* @return value of the field
*/
public Boolean getLocalCacheEnabled(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.get_local_cache_enabled";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toBoolean(result);
}
/**
* Set the name/label field of the given SR.
*
* @param label New value to set
*/
public void setNameLabel(Connection c, String label) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.set_name_label";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(label)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Set the name/description field of the given SR.
*
* @param description New value to set
*/
public void setNameDescription(Connection c, String description) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.set_name_description";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(description)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Set the other_config field of the given SR.
*
* @param otherConfig New value to set
*/
public void setOtherConfig(Connection c, Map<String, String> otherConfig) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.set_other_config";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Add the given key-value pair to the other_config field of the given SR.
*
* @param key Key to add
* @param value Value to add
*/
public void addToOtherConfig(Connection c, String key, String value) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.add_to_other_config";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Remove the given key and its corresponding value from the other_config field of the given SR. If the key is not in that Map, then do nothing.
*
* @param key Key to remove
*/
public void removeFromOtherConfig(Connection c, String key) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.remove_from_other_config";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Set the tags field of the given SR.
*
* @param tags New value to set
*/
public void setTags(Connection c, Set<String> tags) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.set_tags";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(tags)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Add the given value to the tags field of the given SR. If the value is already in that Set, then do nothing.
*
* @param value New value to add
*/
public void addTags(Connection c, String value) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.add_tags";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Remove the given value from the tags field of the given SR. If the value is not in that Set, then do nothing.
*
* @param value Value to remove
*/
public void removeTags(Connection c, String value) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.remove_tags";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Set the sm_config field of the given SR.
*
* @param smConfig New value to set
*/
public void setSmConfig(Connection c, Map<String, String> smConfig) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.set_sm_config";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(smConfig)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Add the given key-value pair to the sm_config field of the given SR.
*
* @param key Key to add
* @param value Value to add
*/
public void addToSmConfig(Connection c, String key, String value) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.add_to_sm_config";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Remove the given key and its corresponding value from the sm_config field of the given SR. If the key is not in that Map, then do nothing.
*
* @param key Key to remove
*/
public void removeFromSmConfig(Connection c, String key) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.remove_from_sm_config";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Create a new Storage Repository and introduce it into the managed system, creating both SR record and PBD record to attach it to current host (with specified device_config parameters)
*
* @param host The host to create/make the SR on
* @param deviceConfig The device config string that will be passed to backend SR driver
* @param physicalSize The physical size of the new storage repository
* @param nameLabel The name of the new storage repository
* @param nameDescription The description of the new storage repository
* @param type The type of the SR; used to specify the SR backend driver to use
* @param contentType The type of the new SRs content, if required (e.g. ISOs)
* @param shared True if the SR (is capable of) being shared by multiple hosts
* @param smConfig Storage backend specific configuration options
* @return Task
*/
public static Task createAsync(Connection c, Host host, Map<String, String> deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, String contentType, Boolean shared, Map<String, String> smConfig) throws
BadServerResponse,
VersionException,
XenAPIException,
XmlRpcException,
Types.SrUnknownDriver {
if(c.rioConnection){
if (smConfig.isEmpty()){
return rioCreateAsync(c, host, deviceConfig, physicalSize, nameLabel, nameDescription, type, contentType, shared);
} else {
throw new Types.VersionException("smConfig parameter must be empty map for Rio (legacy XenServer) host");
}
} else {
return miamiCreateAsync(c, host, deviceConfig, physicalSize, nameLabel, nameDescription, type, contentType, shared, smConfig);
}
}
private static Task rioCreateAsync(Connection c, Host host, Map<String, String> deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, String contentType, Boolean shared) throws
BadServerResponse,
XmlRpcException,
XenAPIException,
Types.SrUnknownDriver {
String method_call = "Async.SR.create";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(physicalSize), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), Marshalling.toXMLRPC(shared)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toTask(result);
}
private static Task miamiCreateAsync(Connection c, Host host, Map<String, String> deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, String contentType, Boolean shared, Map<String, String> smConfig) throws
BadServerResponse,
XmlRpcException,
XenAPIException,
Types.SrUnknownDriver {
String method_call = "Async.SR.create";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(physicalSize), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), Marshalling.toXMLRPC(shared), Marshalling.toXMLRPC(smConfig)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toTask(result);
}
/**
* Create a new Storage Repository and introduce it into the managed system, creating both SR record and PBD record to attach it to current host (with specified device_config parameters)
*
* @param host The host to create/make the SR on
* @param deviceConfig The device config string that will be passed to backend SR driver
* @param physicalSize The physical size of the new storage repository
* @param nameLabel The name of the new storage repository
* @param nameDescription The description of the new storage repository
* @param type The type of the SR; used to specify the SR backend driver to use
* @param contentType The type of the new SRs content, if required (e.g. ISOs)
* @param shared True if the SR (is capable of) being shared by multiple hosts
* @param smConfig Storage backend specific configuration options
* @return The reference of the newly created Storage Repository.
*/
public static SR create(Connection c, Host host, Map<String, String> deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, String contentType, Boolean shared, Map<String, String> smConfig) throws
BadServerResponse,
VersionException,
XenAPIException,
XmlRpcException,
Types.SrUnknownDriver {
if(c.rioConnection){
if (smConfig.isEmpty()){
return rioCreate(c, host, deviceConfig, physicalSize, nameLabel, nameDescription, type, contentType, shared);
} else {
throw new Types.VersionException("smConfig parameter must be empty map for Rio (legacy XenServer) host");
}
} else {
return miamiCreate(c, host, deviceConfig, physicalSize, nameLabel, nameDescription, type, contentType, shared, smConfig);
}
}
private static SR rioCreate(Connection c, Host host, Map<String, String> deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, String contentType, Boolean shared) throws
BadServerResponse,
XmlRpcException,
XenAPIException,
Types.SrUnknownDriver {
String method_call = "SR.create";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(physicalSize), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), Marshalling.toXMLRPC(shared)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toSR(result);
}
private static SR miamiCreate(Connection c, Host host, Map<String, String> deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, String contentType, Boolean shared, Map<String, String> smConfig) throws
BadServerResponse,
XmlRpcException,
XenAPIException,
Types.SrUnknownDriver {
String method_call = "SR.create";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(physicalSize), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), Marshalling.toXMLRPC(shared), Marshalling.toXMLRPC(smConfig)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toSR(result);
}
/**
* Introduce a new Storage Repository into the managed system
*
* @param uuid The uuid assigned to the introduced SR
* @param nameLabel The name of the new storage repository
* @param nameDescription The description of the new storage repository
* @param type The type of the SR; used to specify the SR backend driver to use
* @param contentType The type of the new SRs content, if required (e.g. ISOs)
* @param shared True if the SR (is capable of) being shared by multiple hosts
* @param smConfig Storage backend specific configuration options
* @return Task
*/
public static Task introduceAsync(Connection c, String uuid, String nameLabel, String nameDescription, String type, String contentType, Boolean shared, Map<String, String> smConfig) throws
BadServerResponse,
VersionException,
XenAPIException,
XmlRpcException {
if(c.rioConnection){
if (smConfig.isEmpty()){
return rioIntroduceAsync(c, uuid, nameLabel, nameDescription, type, contentType, shared);
} else {
throw new Types.VersionException("smConfig parameter must be empty map for Rio (legacy XenServer) host");
}
} else {
return miamiIntroduceAsync(c, uuid, nameLabel, nameDescription, type, contentType, shared, smConfig);
}
}
private static Task rioIntroduceAsync(Connection c, String uuid, String nameLabel, String nameDescription, String type, String contentType, Boolean shared) throws
BadServerResponse,
XmlRpcException,
XenAPIException {
String method_call = "Async.SR.introduce";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), Marshalling.toXMLRPC(shared)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toTask(result);
}
private static Task miamiIntroduceAsync(Connection c, String uuid, String nameLabel, String nameDescription, String type, String contentType, Boolean shared, Map<String, String> smConfig) throws
BadServerResponse,
XmlRpcException,
XenAPIException {
String method_call = "Async.SR.introduce";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), Marshalling.toXMLRPC(shared), Marshalling.toXMLRPC(smConfig)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toTask(result);
}
/**
* Introduce a new Storage Repository into the managed system
*
* @param uuid The uuid assigned to the introduced SR
* @param nameLabel The name of the new storage repository
* @param nameDescription The description of the new storage repository
* @param type The type of the SR; used to specify the SR backend driver to use
* @param contentType The type of the new SRs content, if required (e.g. ISOs)
* @param shared True if the SR (is capable of) being shared by multiple hosts
* @param smConfig Storage backend specific configuration options
* @return The reference of the newly introduced Storage Repository.
*/
public static SR introduce(Connection c, String uuid, String nameLabel, String nameDescription, String type, String contentType, Boolean shared, Map<String, String> smConfig) throws
BadServerResponse,
VersionException,
XenAPIException,
XmlRpcException {
if(c.rioConnection){
if (smConfig.isEmpty()){
return rioIntroduce(c, uuid, nameLabel, nameDescription, type, contentType, shared);
} else {
throw new Types.VersionException("smConfig parameter must be empty map for Rio (legacy XenServer) host");
}
} else {
return miamiIntroduce(c, uuid, nameLabel, nameDescription, type, contentType, shared, smConfig);
}
}
private static SR rioIntroduce(Connection c, String uuid, String nameLabel, String nameDescription, String type, String contentType, Boolean shared) throws
BadServerResponse,
XmlRpcException,
XenAPIException {
String method_call = "SR.introduce";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), Marshalling.toXMLRPC(shared)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toSR(result);
}
private static SR miamiIntroduce(Connection c, String uuid, String nameLabel, String nameDescription, String type, String contentType, Boolean shared, Map<String, String> smConfig) throws
BadServerResponse,
XmlRpcException,
XenAPIException {
String method_call = "SR.introduce";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), Marshalling.toXMLRPC(shared), Marshalling.toXMLRPC(smConfig)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toSR(result);
}
/**
* Create a new Storage Repository on disk. This call is deprecated: use SR.create instead.
* @deprecated
*
* @param host The host to create/make the SR on
* @param deviceConfig The device config string that will be passed to backend SR driver
* @param physicalSize The physical size of the new storage repository
* @param nameLabel The name of the new storage repository
* @param nameDescription The description of the new storage repository
* @param type The type of the SR; used to specify the SR backend driver to use
* @param contentType The type of the new SRs content, if required (e.g. ISOs)
* @param smConfig Storage backend specific configuration options
* @return Task
*/
@Deprecated public static Task makeAsync(Connection c, Host host, Map<String, String> deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, String contentType, Map<String, String> smConfig) throws
BadServerResponse,
VersionException,
XenAPIException,
XmlRpcException {
if(c.rioConnection){
if (smConfig.isEmpty()){
return rioMakeAsync(c, host, deviceConfig, physicalSize, nameLabel, nameDescription, type, contentType);
} else {
throw new Types.VersionException("smConfig parameter must be empty map for Rio (legacy XenServer) host");
}
} else {
return miamiMakeAsync(c, host, deviceConfig, physicalSize, nameLabel, nameDescription, type, contentType, smConfig);
}
}
@Deprecated private static Task rioMakeAsync(Connection c, Host host, Map<String, String> deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, String contentType) throws
BadServerResponse,
XmlRpcException,
XenAPIException {
String method_call = "Async.SR.make";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(physicalSize), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toTask(result);
}
@Deprecated private static Task miamiMakeAsync(Connection c, Host host, Map<String, String> deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, String contentType, Map<String, String> smConfig) throws
BadServerResponse,
XmlRpcException,
XenAPIException {
String method_call = "Async.SR.make";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(physicalSize), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), Marshalling.toXMLRPC(smConfig)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toTask(result);
}
/**
* Create a new Storage Repository on disk. This call is deprecated: use SR.create instead.
* @deprecated
*
* @param host The host to create/make the SR on
* @param deviceConfig The device config string that will be passed to backend SR driver
* @param physicalSize The physical size of the new storage repository
* @param nameLabel The name of the new storage repository
* @param nameDescription The description of the new storage repository
* @param type The type of the SR; used to specify the SR backend driver to use
* @param contentType The type of the new SRs content, if required (e.g. ISOs)
* @param smConfig Storage backend specific configuration options
* @return The uuid of the newly created Storage Repository.
*/
@Deprecated public static String make(Connection c, Host host, Map<String, String> deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, String contentType, Map<String, String> smConfig) throws
BadServerResponse,
VersionException,
XenAPIException,
XmlRpcException {
if(c.rioConnection){
if (smConfig.isEmpty()){
return rioMake(c, host, deviceConfig, physicalSize, nameLabel, nameDescription, type, contentType);
} else {
throw new Types.VersionException("smConfig parameter must be empty map for Rio (legacy XenServer) host");
}
} else {
return miamiMake(c, host, deviceConfig, physicalSize, nameLabel, nameDescription, type, contentType, smConfig);
}
}
@Deprecated private static String rioMake(Connection c, Host host, Map<String, String> deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, String contentType) throws
BadServerResponse,
XmlRpcException,
XenAPIException {
String method_call = "SR.make";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(physicalSize), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toString(result);
}
@Deprecated private static String miamiMake(Connection c, Host host, Map<String, String> deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, String contentType, Map<String, String> smConfig) throws
BadServerResponse,
XmlRpcException,
XenAPIException {
String method_call = "SR.make";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(physicalSize), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), Marshalling.toXMLRPC(smConfig)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toString(result);
}
/**
* Destroy specified SR, removing SR-record from database and remove SR from disk. (In order to affect this operation the appropriate device_config is read from the specified SR's PBD on current host)
*
* @return Task
*/
public Task destroyAsync(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException,
Types.SrHasPbd {
String method_call = "Async.SR.destroy";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toTask(result);
}
/**
* Destroy specified SR, removing SR-record from database and remove SR from disk. (In order to affect this operation the appropriate device_config is read from the specified SR's PBD on current host)
*
*/
public void destroy(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException,
Types.SrHasPbd {
String method_call = "SR.destroy";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Removing specified SR-record from database, without attempting to remove SR from disk
*
* @return Task
*/
public Task forgetAsync(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException,
Types.SrHasPbd {
String method_call = "Async.SR.forget";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toTask(result);
}
/**
* Removing specified SR-record from database, without attempting to remove SR from disk
*
*/
public void forget(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException,
Types.SrHasPbd {
String method_call = "SR.forget";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Refresh the fields on the SR object
*
* @return Task
*/
public Task updateAsync(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "Async.SR.update";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toTask(result);
}
/**
* Refresh the fields on the SR object
*
*/
public void update(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.update";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Return a set of all the SR types supported by the system
*
* @return the supported SR types
*/
public static Set<String> getSupportedTypes(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.get_supported_types";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toSetOfString(result);
}
/**
* Refreshes the list of VDIs associated with an SR
*
* @return Task
*/
public Task scanAsync(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "Async.SR.scan";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toTask(result);
}
/**
* Refreshes the list of VDIs associated with an SR
*
*/
public void scan(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.scan";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Perform a backend-specific scan, using the given device_config. If the device_config is complete, then this will return a list of the SRs present of this type on the device, if any. If the device_config is partial, then a backend-specific scan will be performed, returning results that will guide the user in improving the device_config.
*
* @param host The host to create/make the SR on
* @param deviceConfig The device config string that will be passed to backend SR driver
* @param type The type of the SR; used to specify the SR backend driver to use
* @param smConfig Storage backend specific configuration options
* @return Task
*/
public static Task probeAsync(Connection c, Host host, Map<String, String> deviceConfig, String type, Map<String, String> smConfig) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "Async.SR.probe";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(smConfig)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toTask(result);
}
/**
* Perform a backend-specific scan, using the given device_config. If the device_config is complete, then this will return a list of the SRs present of this type on the device, if any. If the device_config is partial, then a backend-specific scan will be performed, returning results that will guide the user in improving the device_config.
*
* @param host The host to create/make the SR on
* @param deviceConfig The device config string that will be passed to backend SR driver
* @param type The type of the SR; used to specify the SR backend driver to use
* @param smConfig Storage backend specific configuration options
* @return An XML fragment containing the scan results. These are specific to the scan being performed, and the backend.
*/
public static String probe(Connection c, Host host, Map<String, String> deviceConfig, String type, Map<String, String> smConfig) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.probe";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(smConfig)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toString(result);
}
/**
* Sets the shared flag on the SR
*
* @param value True if the SR is shared
* @return Task
*/
public Task setSharedAsync(Connection c, Boolean value) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "Async.SR.set_shared";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toTask(result);
}
/**
* Sets the shared flag on the SR
*
* @param value True if the SR is shared
*/
public void setShared(Connection c, Boolean value) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.set_shared";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Create a placeholder for a named binary blob of data that is associated with this SR
*
* @param name The name associated with the blob
* @param mimeType The mime type for the data. Empty string translates to application/octet-stream
* @return Task
*/
public Task createNewBlobAsync(Connection c, String name, String mimeType) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "Async.SR.create_new_blob";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toTask(result);
}
/**
* Create a placeholder for a named binary blob of data that is associated with this SR
*
* @param name The name associated with the blob
* @param mimeType The mime type for the data. Empty string translates to application/octet-stream
* @return The reference of the blob, needed for populating its data
*/
public Blob createNewBlob(Connection c, String name, String mimeType) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.create_new_blob";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toBlob(result);
}
/**
* Sets the SR's physical_size field
*
* @param value The new value of the SR's physical_size
*/
public void setPhysicalSize(Connection c, Long value) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.set_physical_size";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Sets the SR's virtual_allocation field
*
* @param value The new value of the SR's virtual_allocation
*/
public void setVirtualAllocation(Connection c, Long value) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.set_virtual_allocation";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Sets the SR's physical_utilisation field
*
* @param value The new value of the SR's physical utilisation
*/
public void setPhysicalUtilisation(Connection c, Long value) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.set_physical_utilisation";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Returns successfully if the given SR can host an HA statefile. Otherwise returns an error to explain why not
*
* @return Task
*/
public Task assertCanHostHaStatefileAsync(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "Async.SR.assert_can_host_ha_statefile";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toTask(result);
}
/**
* Returns successfully if the given SR can host an HA statefile. Otherwise returns an error to explain why not
*
*/
public void assertCanHostHaStatefile(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.assert_can_host_ha_statefile";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Return a list of all the SRs known to the system.
*
* @return references to all objects
*/
public static Set<SR> getAll(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.get_all";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toSetOfSR(result);
}
/**
* Return a map of SR references to SR records for all SRs known to the system.
*
* @return records of all objects
*/
public static Map<SR, SR.Record> getAllRecords(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "SR.get_all_records";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toMapOfSRSRRecord(result);
}
} | 43.106849 | 362 | 0.667297 |
f9898f4d33984cfef0050783341dce19e08e675b | 525 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.test.annotations;
import javax.persistence.Entity;
/**
* @author Emmanuel Bernard
*/
@Entity()
public class Ferry extends Boat {
private String sea;
public String getSea() {
return sea;
}
public void setSea(String string) {
sea = string;
}
}
| 18.103448 | 94 | 0.700952 |
e3b6b5e7c979f494e2f712305b0542df2d22cff1 | 252 | package com.boluozhai.snowflake.xgit.http.client.smart;
import java.io.IOException;
import com.boluozhai.snowflake.xgit.http.client.smart.io.SmartPktWriter;
public interface SmartTx extends SmartPktWriter {
SmartRx openRx() throws IOException;
}
| 21 | 72 | 0.813492 |
72cc60966e2ac99366419d687b4bf0956b94e45a | 2,515 | /*
[The "BSD licence"]
Copyright (c) 2005-2008 Terence Parr
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.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 org.eclipse.persistence.internal.libraries.antlr.runtime;
/** A source of characters for an ANTLR lexer */
public interface CharStream extends IntStream {
public static final int EOF = -1;
/** For infinite streams, you don't need this; primarily I'm providing
* a useful interface for action code. Just make sure actions don't
* use this on streams that don't support it.
*/
public String substring(int start, int stop);
/** Get the ith character of lookahead. This is the same usually as
* LA(i). This will be used for labels in the generated
* lexer code. I'd prefer to return a char here type-wise, but it's
* probably better to be 32-bit clean and be consistent with LA.
*/
public int LT(int i);
/** ANTLR tracks the line information automatically */
int getLine();
/** Because this stream can rewind, we need to be able to reset the line */
void setLine(int line);
void setCharPositionInLine(int pos);
/** The index of the character relative to the beginning of the line 0..n-1 */
int getCharPositionInLine();
}
| 43.362069 | 79 | 0.758648 |
c60486700fd36dddb722f457044a642c61157fd8 | 19,725 | package de.esymetric.jerusalem.main.tests;
import java.io.File;
import java.io.FileInputStream;
import java.io.RandomAccessFile;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import junit.framework.TestCase;
import org.apache.tools.bzip2.CBZip2InputStream;
import de.esymetric.jerusalem.osmDataRepresentation.OSMDataReader;
import de.esymetric.jerusalem.osmDataRepresentation.osm2ownMaps.OsmNodeID2CellIDMapMemory;
import de.esymetric.jerusalem.osmDataRepresentation.osm2ownMaps.PartitionedOsmNodeID2OwnIDMap;
import de.esymetric.jerusalem.osmDataRepresentation.unused.LongOsmNodeID2OwnIDMapFileBased;
import de.esymetric.jerusalem.ownDataRepresentation.Node;
import de.esymetric.jerusalem.ownDataRepresentation.fileSystem.LatLonDir;
import de.esymetric.jerusalem.ownDataRepresentation.fileSystem.PartitionedNodeListFile;
import de.esymetric.jerusalem.ownDataRepresentation.fileSystem.PartitionedQuadtreeNodeIndexFile;
import de.esymetric.jerusalem.ownDataRepresentation.fileSystem.NodeIndexFile.NodeIndexNodeDescriptor;
import de.esymetric.jerusalem.ownDataRepresentation.geoData.Position;
import de.esymetric.jerusalem.ownDataRepresentation.geoData.importExport.KML;
import de.esymetric.jerusalem.rebuilding.Rebuilder;
import de.esymetric.jerusalem.rebuilding.optimizer.TransitionsOptimizer;
import de.esymetric.jerusalem.routing.Router;
import de.esymetric.jerusalem.routing.RoutingType;
import de.esymetric.jerusalem.routing.algorithms.TomsAStarStarRouting;
import de.esymetric.jerusalem.routing.heuristics.TomsRoutingHeuristics;
import de.esymetric.jerusalem.utils.BufferedRandomAccessFile;
import de.esymetric.jerusalem.utils.BufferedRandomAccessFileCache;
import de.esymetric.jerusalem.utils.FileBasedHashMap;
import de.esymetric.jerusalem.utils.FileBasedHashMapForLongKeys;
import de.esymetric.jerusalem.utils.MemoryEfficientLongToIntMap;
import de.esymetric.jerusalem.utils.RandomAccessFileCache;
public class JerusalemTests extends TestCase {
public JerusalemTests() {
super("Jerusalem Test");
}
public void testLanLonDir() throws Exception {
for (double lat = -89; lat < 89; lat += 0.5)
for (double lng = -89; lng < 89; lng += 0.3) {
boolean ok = new LatLonDir(lat, lng).equals(new LatLonDir(
new LatLonDir(lat, lng).getShortKey()));
assertTrue(ok);
// System.out.println("" + lat + " " + lng + " " + ok);
}
checkOffsetBits(48, 11, 48, 11);
checkOffsetBits(48, 11, 49, 11);
checkOffsetBits(48, 11, 49, 12);
checkOffsetBits(48, 11, 48, 12);
checkOffsetBits(48, 11, 48, 10);
checkOffsetBits(48, 11, 47, 10);
checkOffsetBits(48, 11, 47, 12);
checkOffsetBits(48, 11, 47, 11);
checkOffsetBits(48, 11, 49, 10);
}
void checkOffsetBits(int lat1, int lng1, int lat2, int lng2) {
LatLonDir lld1 = new LatLonDir(lat1, lng1);
int offsetBits = lld1.getOffsetBits(lat2, lng2);
LatLonDir lld3 = new LatLonDir(lat1, lng1, offsetBits);
assertTrue(new LatLonDir(lat2, lng2).equals(lld3));
}
public void testOsmNodeID2CellIDMap() throws Exception {
String filePath = "testData/osmNodeID2CellIDMap.data";
OsmNodeID2CellIDMapMemory map = new OsmNodeID2CellIDMapMemory();
LatLonDir lld = new LatLonDir(48.12345, 11.92737);
map.put(1234, lld);
assertTrue(lld.equals(map.get(1234)));
map.save(filePath);
map = new OsmNodeID2CellIDMapMemory();
map.load(filePath);
assertTrue(lld.equals(map.get(1234)));
}
public void testFileBasedHashMap() throws Exception {
new File("testData/fileBasedHashMapTest.data").delete();
FileBasedHashMap fbhm = new FileBasedHashMap();
fbhm.open("testData/fileBasedHashMapTest.data", false);
for (int id = 1000000; id > 0; id -= 111) {
int value = (int) (Math.random() * 788823548);
fbhm.put(id, value);
assertTrue(fbhm.get(id) == value);
}
for (int id = 1000001; id < 1286746; id += 263) {
int value = (int) (Math.random() * 788823548);
fbhm.put(id, value);
if (fbhm.get(id) != value) {
fbhm.put(id, value);
assertTrue(fbhm.get(id) == value);
}
assertTrue(fbhm.get(id) == value);
}
for (int id = 2000001; id < 3000000; id += 555) {
int key = id;
int value = (int) (Math.random() * 788823548);
fbhm.put(key, value);
assertTrue(fbhm.get(key) == value);
}
fbhm.close();
new File("testData/fileBasedHashMapTest.data").delete();
}
public void testFileBasedHashMapForLongKeys() throws Exception {
new File("testData/fileBasedHashMapTestForLongKeys.data").delete();
FileBasedHashMapForLongKeys fbhm = new FileBasedHashMapForLongKeys();
fbhm.open("testData/fileBasedHashMapTestForLongKeys.data", false);
for (int id = 1000000; id > 0; id -= 111) {
int value = (int) (Math.random() * 788823548);
fbhm.put(id, value);
assertTrue(fbhm.get(id) == value);
}
for (int id = 1000001; id < 1286746; id += 263) {
int value = (int) (Math.random() * 788823548);
fbhm.put(id, value);
if (fbhm.get(id) != value) {
fbhm.put(id, value);
assertTrue(fbhm.get(id) == value);
}
assertTrue(fbhm.get(id) == value);
}
for (long id = 3000000000L; id < 3300000000L; id += 23555L) {
long key = id;
int value = (int) (Math.random() * 788823548);
fbhm.put(key, value);
assertTrue(fbhm.get(key) == value);
}
fbhm.close();
new File("testData/fileBasedHashMapTestForLongKeys.data").delete();
}
public void testPartitionedOsmNodeID2OwnIDMap() {
LatLonDir.deleteAllLatLonDataFiles("testData");
PartitionedOsmNodeID2OwnIDMap map = new PartitionedOsmNodeID2OwnIDMap(
"testData", false);
for (int i = 0; i < 25; i++) {
double lat = Math.random() * 180 - 90;
double lng = Math.random() * 360 - 180;
int key = (int) (Math.random() * 788823);
int value = (int) (Math.random() * 788823548);
map.put(lat, lng, key, value);
assertTrue(map.get(key) == value);
}
LatLonDir.deleteAllLatLonDataFiles("testData");
}
public void testLongOsmNodeID2OwnIDMap() {
LatLonDir.deleteAllLatLonDataFiles("testData");
LongOsmNodeID2OwnIDMapFileBased map = new LongOsmNodeID2OwnIDMapFileBased(
"testData");
for (int i = 0; i < 6; i++) {
long key = (long) (Math.random() * 2100000000L);
int value = (int) (Math.random() * 788823548);
map.put(key, value);
assertTrue(map.get(key) == value);
}
//LatLonDir.deleteAllLatLonDataFiles("testData");
}
public void testMemoryEfficientLongToIntMap() {
MemoryEfficientLongToIntMap map = new MemoryEfficientLongToIntMap();
map.put( 23477289977L, 1234567);
for (int i = 0; i < 250; i++) {
long key = (long) (Math.random() * 2100000000L);
int value = (int) (Math.random() * 788823548);
map.put(key, value);
assertTrue(map.get(key) == value);
}
assertTrue(map.get(23477289977L) == 1234567);
// test the keys() method
map.clear();
map.put( 23477289977L, 1234567);
assertEquals(23477289977L, map.keys()[0]);
// test the keysIterator() method
map.put( 123456789123L, 12345);
Set<Long> s = new HashSet<Long>();
Iterator<Long> it = map.keysIterator();
while( it.hasNext() )
s.add(it.next());
assertEquals(2, s.size());
assertTrue(s.contains(23477289977L));
assertTrue(s.contains(123456789123L));
for (int i = 0; i < 250; i++) {
long key = (long) (i * 21000000L);
int value = (int) (Math.random() * 788823548);
map.put(key, value);
}
s.clear();
it = map.keysIterator();
while( it.hasNext() )
s.add(it.next());
assertEquals(252, s.size());
}
public void testBufferedRandomAccessFileCache() throws Exception {
BufferedRandomAccessFileCache rafCache = new BufferedRandomAccessFileCache();
for (int i = 0; i <= 30; i++) {
BufferedRandomAccessFile raf = rafCache.getRandomAccessFile(
"testData/rafCache" + i + ".data", false);
for (int j = 0; j < 200000; j++) {
int p = (int)(Math.random() * 20000);
raf.seek(p);
raf.writeInt(j);
}
raf.seek(999);
raf.writeInt(333);
}
for (int i = 10; i > 0; i--) {
BufferedRandomAccessFile raf = rafCache.getRandomAccessFile(
"testData/rafCache" + i + ".data", false);
raf.seek(999);
assertEquals(333, raf.readInt());
}
rafCache.close();
}
public void testRandomAccessFileCache() throws Exception {
RandomAccessFileCache rafCache = new RandomAccessFileCache();
for (int i = 0; i <= 30; i++) {
RandomAccessFile raf = rafCache.getRandomAccessFile(
"testData/rafCache" + i + ".data", false);
for (int j = 0; j < 200000; j++) {
int p = (int)(Math.random() * 20000);
raf.seek(p);
raf.writeInt(j);
}
raf.seek(999);
raf.writeInt(333);
}
for (int i = 10; i > 0; i--) {
RandomAccessFile raf = rafCache.getRandomAccessFile(
"testData/rafCache" + i + ".data", false);
raf.seek(999);
assertEquals(333, raf.readInt());
}
rafCache.close();
}
public void testRebuildAndRouting() throws Exception {
String dataDirectoryPath = "testData";
//String tempDirectoryPath = "/Users/tomhenne/tempData";
String tempDirectoryPath = "tempData";
Rebuilder rebuilder = new Rebuilder(dataDirectoryPath, tempDirectoryPath,
new TomsRoutingHeuristics(), false, false, false);
FileInputStream fis = new FileInputStream("osmData/hadern.osm.bz2");
CBZip2InputStream bzis = new CBZip2InputStream(fis);
OSMDataReader reader = new OSMDataReader(bzis, rebuilder, false);
reader.read(new Date());
bzis.close();
fis.close();
rebuilder.finishProcessingAndClose();
System.out.println("BRAF-INFO: " +
BufferedRandomAccessFile.getShortInfoAndResetCounters());
// create quadtree index
rebuilder = new Rebuilder(dataDirectoryPath, tempDirectoryPath,
new TomsRoutingHeuristics(), true, false, true);
rebuilder.makeQuadtreeIndex();
rebuilder.finishProcessingAndClose();
// test
Router router = new Router(dataDirectoryPath,
new TomsAStarStarRouting(), new TomsRoutingHeuristics(), 120);
Router.setDebugMode(true);
makeRoute(router, 48.107891, 11.461865, 48.099986, 11.511051,
"durch-waldfriedhof", dataDirectoryPath);
makeRoute(router, 48.107608, 11.461648, 48.108656, 11.477371,
"grosshadern-fussweg", dataDirectoryPath);
makeRoute(router, 48.116892, 11.487076, 48.117909, 11.472429,
"eichenstrasse", dataDirectoryPath);
/* nicht in hadern2 enthalten:
makeRoute(router, 48.125166, 11.451445, 48.103516, 11.501441,
"a96_Fuerstenrieder", dataDirectoryPath);
makeRoute(router, 48.125166, 11.451445, 48.12402, 11.515946, "a96",
dataDirectoryPath);
*/
}
public void testPartionedNodeListFile() throws Exception {
String dataDirectoryPath = "testData";
PartitionedNodeListFile nlf = new PartitionedNodeListFile(dataDirectoryPath, false);
int nodeID = nlf.insertNewNodeStreamAppend(48.11, 11.48);
int nodeID2 = nlf.insertNewNodeStreamAppend(48.111, 11.481);
int nodeID3 = nlf.insertNewNodeStreamAppend(-48.111, -11.481);
nlf.close();
// ---
nlf = new PartitionedNodeListFile(dataDirectoryPath, false);
nlf.setTransitionID(48.111, 11.481, nodeID2, 2222);
nlf.setTransitionID(48.11, 11.48, nodeID, 1111);
nlf.setTransitionID(-48.111, -11.481, nodeID3, 3333);
nlf.close();
// ---
nlf = new PartitionedNodeListFile(dataDirectoryPath, true);
Node n1 = nlf.getNode(new LatLonDir(48.11, 11.48), nodeID);
assertEquals(1111, n1.transitionID);
Node n2 = nlf.getNode(new LatLonDir(48.111, 11.481), nodeID2);
assertEquals(2222, n2.transitionID);
Node n3 = nlf.getNode(new LatLonDir(-48.111, -11.481), nodeID3);
assertEquals(3333, n3.transitionID);
nlf.close();
}
public void testRouting() throws Exception {
String dataDirectoryPath = "testData";
Router router = new Router(dataDirectoryPath,
new TomsAStarStarRouting(), new TomsRoutingHeuristics(), 120);
Router.setDebugMode(true);
makeRoute(router, 48.107891, 11.461865, 48.099986, 11.511051,
"durch-waldfriedhof", dataDirectoryPath);
makeRoute(router, 48.107608, 11.461648, 48.108656, 11.477371,
"grosshadern-fussweg", dataDirectoryPath);
makeRoute(router, 48.116892, 11.487076, 48.117909, 11.472429,
"eichenstrasse", dataDirectoryPath);
}
public void testRebuildOnlyWays() throws Exception {
String dataDirectoryPath = "testData";
String tempDirectoryPath = "tempData";
// rebuild full
Rebuilder rebuilder = new Rebuilder(dataDirectoryPath,tempDirectoryPath,
new TomsRoutingHeuristics(), false, false, false);
FileInputStream fis = new FileInputStream("osmData/hadern.osm.bz2");
CBZip2InputStream bzis = new CBZip2InputStream(fis);
OSMDataReader reader = new OSMDataReader(bzis, rebuilder, false);
reader.read(new Date());
bzis.close();
fis.close();
rebuilder.finishProcessingAndClose();
// create quadtree index
rebuilder = new Rebuilder(dataDirectoryPath, tempDirectoryPath,
new TomsRoutingHeuristics(), true, false, true);
rebuilder.makeQuadtreeIndex();
rebuilder.finishProcessingAndClose();
// rebuild only ways
rebuilder = new Rebuilder(dataDirectoryPath, tempDirectoryPath,
new TomsRoutingHeuristics(), true, true, false);
fis = new FileInputStream("osmData/hadern.osm.bz2");
bzis = new CBZip2InputStream(fis);
reader = new OSMDataReader(bzis, rebuilder, true);
reader.read(new Date());
bzis.close();
fis.close();
rebuilder.finishProcessingAndClose();
// test
Router router = new Router(dataDirectoryPath,
new TomsAStarStarRouting(), new TomsRoutingHeuristics(), 120);
Router.setDebugMode(true);
makeRoute(router, 48.107891, 11.461865, 48.099986, 11.511051,
"durch-waldfriedhof", dataDirectoryPath);
makeRoute(router, 48.107608, 11.461648, 48.108656, 11.477371,
"grosshadern-fussweg", dataDirectoryPath);
/*
makeRoute(router, 48.125166, 11.451445, 48.103516, 11.501441,
"a96_Fuerstenrieder", dataDirectoryPath);
makeRoute(router, 48.125166, 11.451445, 48.12402, 11.515946, "a96",
dataDirectoryPath);*/
}
public void testTransitionsOptimizer() throws Exception {
String dataDirectoryPath = "testData";
TransitionsOptimizer to = new TransitionsOptimizer(dataDirectoryPath);
to.optimize(new Date());
to.close();
// test
Router router = new Router(dataDirectoryPath,
new TomsAStarStarRouting(), new TomsRoutingHeuristics(), 120);
Router.setDebugMode(true);
makeRoute(router, 48.107891, 11.461865, 48.099986, 11.511051,
"durch-waldfriedhof", dataDirectoryPath);
makeRoute(router, 48.107608, 11.461648, 48.108656, 11.477371,
"grosshadern-fussweg", dataDirectoryPath);
makeRoute(router, 48.116892, 11.487076, 48.117909, 11.472429,
"eichenstrasse-opt", dataDirectoryPath);
}
void makeRoute(Router router, double lat1, double lng1, double lat2,
double lng2, String name, String dataDirectoryPath) {
for (RoutingType rt : RoutingType.values())
makeRoute(router, rt.name(), lat1, lng1, lat2, lng2, name,
dataDirectoryPath);
}
void makeRoute(Router router, String routingType, double lat1, double lng1,
double lat2, double lng2, String name, String dataDirectoryPath) {
System.out.println("---------------------------------------------");
System.out
.println("Computing Route " + name + " (" + routingType + ")");
System.out.println("---------------------------------------------");
List<Node> route = router
.findRoute(routingType, lat1, lng1, lat2, lng2);
assertNotNull(route);
if (route == null) {
System.out.println("ERROR: no route found for " + name + " ("
+ routingType + ")");
return;
}
System.out.println();
KML kml = new KML();
Vector<Position> trackPts = new Vector<Position>();
for (Node n : route) {
Position p = new Position();
p.latitude = n.lat;
p.longitude = n.lng;
trackPts.add(p);
}
kml.setTrackPositions(trackPts);
kml.Save(dataDirectoryPath + File.separatorChar + name + "-"
+ routingType + ".kml");
assertTrue(trackPts.size() > 10);
}
static String D02(int d) {
return d < 10 ? "0" + String.valueOf(d) : String.valueOf(d);
}
public static String FormatTimeStopWatch(long ticks) {
int sec = (int) (ticks / 1000L);
int days = sec / 86400;
sec -= days * 86400;
int hours = sec / 3600;
sec -= hours * 3600;
int min = sec / 60;
sec -= min * 60;
return "" + (days > 0 ? (days + ".") : "") + hours + ":"
+ D02(Math.abs(min)) + ":" + D02(Math.abs(sec));
}
public void testPartionedQuadtreeNodeIndex() throws Exception {
PartitionedQuadtreeNodeIndexFile pf = new PartitionedQuadtreeNodeIndexFile("testData", false, true);
pf.setID(48.11, 11.48, 77);
assertEquals(77, pf.getID(48.11, 11.48));
pf.setID(48.11, 11.48, 55);
pf.setID(33.11, 22.48, 44);
assertEquals(55, pf.getID(48.11, 11.48));
assertEquals(44, pf.getID(33.11, 22.48));
/* just testing ... this is wrong
pf.setID(48.11001, 11.48, 55);
pf.setID(48.11002, 11.48, 56);
List<NodeIndexNodeDescriptor> l = pf.getIDPlusSourroundingIDs(48.11001, 11.48, 0);
System.out.println(l);
*/
for( double lat = 50.0; lat < 50.4; lat += 0.00001)
for( double lng = 11.0; lng < 12; lng += 0.009)
pf.setID(lat, lng, (int)lat * (int)(lng * 100.0));
for( double lat = 50.0; lat < 50.4; lat += 0.00001)
for( double lng = 11.0; lng < 12; lng += 0.009) {
//System.out.println(" " + lat + " " + lng);
assertEquals((int)lat * (int)(lng * 100.0), pf.getID(lat, lng ));
}
for( double lat = 50.0; lat < 60; lat += 0.3)
for( double lng = -120.0; lng < 60; lng += 0.8)
pf.setID(lat, lng, (int)(lat * lng));
for( double lat = 50.0; lat < 60; lat += 0.3)
for( double lng = -120.0; lng < 60; lng += 0.8)
assertEquals((int)(lat * lng), pf.getID(lat, lng ));
for( double lat = 50.0; lat < 60; lat += 0.3)
for( double lng = -120.0; lng < 60; lng += 0.8)
pf.setID(lat, lng, (int)(lat * lng));
for( double lat = 50.0; lat < 60; lat += 0.3)
for( double lng = -120.0; lng < 60; lng += 0.8)
assertEquals((int)(lat * lng), pf.getID(lat, lng ));
}
public void testBufferedRandomAccessFile() throws Exception {
new File("testData/braf.data").delete();
BufferedRandomAccessFile braf = new BufferedRandomAccessFile();
braf.open("testData/braf.data", "rw");
for (int i = 0; i < 10000; i++)
braf.writeInt(-1);
braf.close();
braf.open("testData/braf.data", "rw");
braf.seek(20000);
for (int i = 0; i < 10000; i++)
braf.writeInt(-1);
braf.close();
assertEquals(60000, new File("testData/braf.data").length());
braf.open("testData/braf.data", "rw");
for (int i = 11; i < 2000; i += 10) {
braf.seek(i);
braf.writeInt(i);
}
for (int i = 11; i < 2000; i += 10) {
braf.seek(i);
assertTrue(braf.readInt() == i);
}
for (int i = 55; i < 2009; i += 9) {
braf.seek(i);
braf.writeInt(i);
}
braf.close();
braf.open("testData/braf.data", "rw");
for (int i = 55; i < 2009; i += 9) {
braf.seek(i);
assertTrue(braf.readInt() == i);
}
braf.close();
}
}
| 31.56 | 103 | 0.658809 |
f5280f37ca6e1ecce408ad2532f28430398599d4 | 501 | import java.util.Scanner;
public class fibonacci {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a value: ");
int value = scan.nextInt();
System.out.println("The result is " + recurseFib(value));
scan.close();
}
static int recurseFib(int num) {
if (num <= 1) {
return num;
} else {
return recurseFib(num - 1) + recurseFib(num - 2);
}
}
} | 26.368421 | 65 | 0.54491 |
d7c72200ece2db995fcc7a0063c2ba654d0f4fb8 | 252 | package vfdt.stat.splitter;
import vfdt.tree.Decision;
/**
* %Description%
*
* @author Mehran Mirkhan
* @version 1.0
* @since 2018 Mar 07
*/
public interface Splitter {
Double getSplitGain() throws Exception;
Decision getDecision();
}
| 14.823529 | 43 | 0.686508 |
e48aed28f7dbf10915d27df406254c67555148c7 | 3,022 | package com.chenyee.stephenlau.floatingball.quickSetting;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.service.quicksettings.Tile;
import android.service.quicksettings.TileService;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import com.chenyee.stephenlau.floatingball.floatingBall.service.FloatingBallService;
import com.chenyee.stephenlau.floatingball.repository.BallSettingRepo;
import static com.chenyee.stephenlau.floatingball.util.StaticStringUtil.EXTRAS_COMMAND;
/**
* Description: <p> Created by Liu Qitian on 18-5-3.
*/
@TargetApi(Build.VERSION_CODES.N)
public class QuickSettingService extends TileService {
public static final String QUICK_SETTING_REFRESH_MAIN_ACTIVITY_ACTION = "quickSettingRefreshMainActivity";
private static final String TAG = QuickSettingService.class.getSimpleName();
private boolean isAddedBall = false;
private Tile tile;
//当用户从Edit栏添加到快速设定中调用
@Override
public void onTileAdded() {
Log.d(TAG, "onTileAdded");
}
//当用户从快速设定栏中移除的时候调用
@Override
public void onTileRemoved() {
Log.d(TAG, "onTileRemoved");
}
/**
* 打开下拉菜单的时候调用,当快速设置按钮并没有在编辑栏拖到设置栏中不会调用
* 在TileAdded之后会调用一次
*/
@Override
public void onStartListening() {
Log.d(TAG, "onStartListening");
tile = getQsTile();
isAddedBall = BallSettingRepo.isAddedBallInSetting();
Log.d(TAG, "onStartListening isAddedBall:" + isAddedBall);
refreshTile();
}
@Override
public void onClick() {
if (isAddedBall) {
removeFloatBall();
} else {
addFloatBall();
}
isAddedBall = !isAddedBall;
BallSettingRepo.setIsAddedBallInSetting(isAddedBall);
LocalBroadcastManager.getInstance(QuickSettingService.this).sendBroadcast(new Intent(QUICK_SETTING_REFRESH_MAIN_ACTIVITY_ACTION));
refreshTile();
}
// 关闭下拉菜单的时候调用,当快速设置按钮并没有在编辑栏拖到设置栏中不会调用
// 在onTileRemoved移除之前也会调用移除
@Override
public void onStopListening() {
Log.d(TAG, "onStopListening");
}
private void addFloatBall() {
Intent intent = new Intent(QuickSettingService.this, FloatingBallService.class);
Bundle data = new Bundle();
data.putInt(EXTRAS_COMMAND, FloatingBallService.TYPE_SWITCH_ON);
intent.putExtras(data);
startService(intent);
}
private void removeFloatBall() {
Intent intent = new Intent(QuickSettingService.this, FloatingBallService.class);
Bundle data = new Bundle();
data.putInt(EXTRAS_COMMAND, FloatingBallService.TYPE_REMOVE_ALL);
intent.putExtras(data);
startService(intent);
}
private void refreshTile() {
if (isAddedBall) {
tile.setState(Tile.STATE_ACTIVE);
} else {
tile.setState(Tile.STATE_INACTIVE);
}
tile.updateTile();
}
}
| 29.339806 | 138 | 0.694904 |
8b658a689f9d864593f4fafad94fc6f984db71e1 | 2,481 | /**
* Copyright 2020 Alibaba Group Holding Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.maxgraph.v2.common;
import com.alibaba.maxgraph.v2.common.config.CommonConfig;
import com.alibaba.maxgraph.v2.common.config.Configs;
import com.alibaba.maxgraph.v2.common.discovery.RoleType;
import java.io.Closeable;
public abstract class NodeBase implements Closeable {
protected RoleType roleType;
protected int idx;
public NodeBase() {
this.roleType = RoleType.UNKNOWN;
this.idx = 0;
}
public NodeBase(Configs configs) {
this.roleType = RoleType.fromName(CommonConfig.ROLE_NAME.get(configs));
this.idx = CommonConfig.NODE_IDX.get(configs);
}
public NodeBase(Configs configs, RoleType roleType) {
this.roleType = roleType;
this.idx = CommonConfig.NODE_IDX.get(configs);
}
protected Configs reConfig(Configs configs) {
int storeCount = CommonConfig.STORE_NODE_COUNT.get(configs);
int ingestorCount = CommonConfig.INGESTOR_NODE_COUNT.get(configs);
return Configs.newBuilder(configs)
.put(String.format(CommonConfig.NODE_COUNT_FORMAT, RoleType.EXECUTOR_ENGINE.getName()), String.valueOf(storeCount))
.put(String.format(CommonConfig.NODE_COUNT_FORMAT, RoleType.EXECUTOR_GRAPH.getName()), String.valueOf(storeCount))
.put(String.format(CommonConfig.NODE_COUNT_FORMAT, RoleType.EXECUTOR_MANAGE.getName()), String.valueOf(storeCount))
.put(String.format(CommonConfig.NODE_COUNT_FORMAT, RoleType.EXECUTOR_QUERY.getName()), String.valueOf(storeCount))
.put(CommonConfig.INGESTOR_QUEUE_COUNT.getKey(), String.valueOf(ingestorCount))
.put(CommonConfig.ROLE_NAME.getKey(), this.roleType.getName())
.build();
}
public abstract void start();
public String getName() {
return roleType + "#" + idx;
}
}
| 39.380952 | 131 | 0.707376 |
755dbe43bbda67f7ffccfd0a6e0420a8c8ea5b67 | 1,987 | package examples.MetadataOperations.SetMetadata;
import java.util.ArrayList;
import com.groupdocs.cloud.metadata.api.MetadataApi;
import com.groupdocs.cloud.metadata.client.ApiException;
import com.groupdocs.cloud.metadata.model.FileInfo;
import com.groupdocs.cloud.metadata.model.SearchCriteria;
import com.groupdocs.cloud.metadata.model.SetOptions;
import com.groupdocs.cloud.metadata.model.SetProperty;
import com.groupdocs.cloud.metadata.model.SetResult;
import com.groupdocs.cloud.metadata.model.Tag;
import com.groupdocs.cloud.metadata.model.TagOptions;
import com.groupdocs.cloud.metadata.model.requests.SetRequest;
import examples.Common;
/**
* This example demonstrates how to set metadata by exact tag name and tag category.
*/
public class SetMetadataByTag {
public static void main(String[] args) {
MetadataApi apiInstance = new MetadataApi(Common.GetConfiguration());
try {
SetOptions options = new SetOptions();
ArrayList<SetProperty> properties = new ArrayList<SetProperty>();
SetProperty property = new SetProperty();
SearchCriteria searchCriteria = new SearchCriteria();
TagOptions tagOptions = new TagOptions();
Tag tag = new Tag();
tag.setName("Creator");
tag.setCategory("Person");
tagOptions.setExactTag(tag);
searchCriteria.setTagOptions(tagOptions);
property.setSearchCriteria(searchCriteria);
property.setNewValue("NewAuthor");
property.setType("string");
properties.add(property);
options.setProperties(properties);
FileInfo fileInfo = new FileInfo();
fileInfo.setFilePath("documents/input.docx");
options.setFileInfo(fileInfo);
SetRequest request = new SetRequest(options);
SetResult response = apiInstance.set(request);
System.out.println("Count of changes: " + response.getSetCount());
System.out.println("Resultant file path: " + response.getPath());
} catch (ApiException e) {
System.err.println("Exception while calling MetadataApi:");
e.printStackTrace();
}
}
} | 34.258621 | 84 | 0.766985 |
b986ac61713de74e820e9166ad64f34ae4232258 | 391 | package test.me.chan.spark2pidgin;
import static org.junit.Assert.*;
import me.chan.spark2pidgin.AppConstants;
import org.junit.Test;
/**
* Makes sure {@link AppConstants} is initialized properly with
* <code>app.properties<code>.
*
* @author chan
*
*/
public class AppConstantsTest {
@Test
public void test() {
assertNotNull(AppConstants.OWNER);
}
}
| 17 | 64 | 0.677749 |
f628fbc2757e755324962150e61841f249c05898 | 2,635 | package mit.edu.scansite.examples.databasesearch;
import mit.edu.scansite.examples.ExampleUtils;
import java.util.List;
import static mit.edu.scansite.examples.ExampleUtils.baseURL;
/**
* @author Thomas Bernwinkler
* Last edited 4/4/2017
* Provided by Yaffe Lab, Koch Institute, MIT
*/
//../databasesearch/motifshortname=Shc_SH2/dsshortname=swissprot/organismclass=Mammals/speciesrestriction=rattus/numberofphosphorylations=1/molweightfrom=5000/molweightto=20000/isoelectricpointfrom=4/keywordrestriction=cell/sequencerestriction=PPP
public class DatabaseSearchExample1 {
private static final String param1 = "/motifshortname=";
private static final String param2 = "/dsshortname=";
private static final String param3 = "/organismclass=";
private static final String param4 = "/speciesrestriction=";
private static final String param5 = "/numberofphosphorylations=";
private static final String param6 = "/molweightfrom=";
private static final String param7 = "/molweightto=";
private static final String param8 = "/isoelectricpointfrom=";
private static final String param9 = "/keywordrestriction=";
private static final String param10 = "/sequencerestriction=";
private static final String service = "databasesearch";
private static final String outputFileName = "DatabaseSearchExample1Output.txt";
public static void main(String[] args) {
String motifshortname = "Shc_SH2";
String dsshortname = "swissprot";
String organismclass = "Mammals";
String speciesrestriction = "rattus";
String numberofphosphorylations = "1";
String molweightfrom = "5000";
String molweightto = "20000";
String isoelectricpointfrom = "4";
String keywordrestriction = "cell";
String sequencerestriction = "PPP";
String urlString = baseURL + service
+ param1 + motifshortname
+ param2 + dsshortname
+ param3 + organismclass
+ param4 + speciesrestriction
+ param5 + numberofphosphorylations
+ param6 + molweightfrom
+ param7 + molweightto
+ param8 + isoelectricpointfrom
+ param9 + keywordrestriction
+ param10+ sequencerestriction;
List<String> results = ExampleUtils.runRequest(urlString);
String resultContent = "";
for (String result : results) {
resultContent += result + "\n";
}
ExampleUtils.writeToFile(resultContent, outputFileName);
System.out.println(resultContent);
}
}
| 40.538462 | 247 | 0.681214 |
385c17ebccee9499fdedd6254ab37381633ab312 | 860 | package org.lndroid.framework.usecases;
import org.lndroid.framework.WalletData;
import org.lndroid.framework.client.IPluginClient;
import org.lndroid.framework.common.IPluginData;
import org.lndroid.framework.defaults.DefaultPlugins;
import java.io.IOException;
import java.lang.reflect.Type;
public class GetPaymentPeerContact extends GetData<WalletData.Contact, Long> {
public GetPaymentPeerContact(IPluginClient client){
super(client, DefaultPlugins.GET_PAYMENT_PEER_CONTACT);
}
@Override
protected WalletData.Contact getData(IPluginData in) {
in.assignDataType(WalletData.Contact.class);
try {
return in.getData();
} catch (IOException e) {
return null;
}
}
@Override
protected Type getRequestType() {
return WalletData.GetRequestLong.class;
}
}
| 27.741935 | 78 | 0.719767 |
5c2fb33f3a4a7966c05074cf02a5ba4998daca8b | 142 | package org.jetbrains.research.kex.intrinsics.internal;
@FunctionalInterface
public interface FloatGenerator {
float apply(int index);
}
| 20.285714 | 55 | 0.802817 |
34fd29190a06d5c86d1c9949bc32efe1cd4b66a2 | 4,012 | /**
* Copyright (C) 2018-2019 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.mutantswarm.exec;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import com.hotels.mutantswarm.exec.MutatedSourceFactory.MutatedSource;
import com.hotels.mutantswarm.model.MutantSwarmScript;
import com.hotels.mutantswarm.model.MutantSwarmSource;
import com.hotels.mutantswarm.model.MutantSwarmStatement;
import com.hotels.mutantswarm.mutate.Mutation;
import com.hotels.mutantswarm.mutate.Mutator;
import com.hotels.mutantswarm.mutate.Splice;
import com.hotels.mutantswarm.plan.Mutant;
import com.hotels.mutantswarm.plan.gene.Gene;
@RunWith(MockitoJUnitRunner.class)
public class MutatedSourceFactoryTest {
@Mock
private MutantSwarmSource source;
@Mock
private MutantSwarmScript script;
@Mock
private MutantSwarmStatement statement;
@Mock
private Mutant mutant;
@Mock
private Mutator mutator;
@Mock
private Gene gene;
@Mock
private Mutation mutation;
@Mock
private Splice splice;
private MutatedSourceFactory mutatedSourceFactory = new MutatedSourceFactory();
@Before
public void setup(){
when(mutant.getMutator()).thenReturn(mutator);
when(mutant.getGene()).thenReturn(gene);
when(mutator.apply(gene)).thenReturn(mutation);
when(source.getScripts()).thenReturn(Arrays.asList(script));
when(script.getIndex()).thenReturn(0);
when(mutant.getScriptIndex()).thenReturn(0);
when(script.getStatements()).thenReturn(Arrays.asList(statement));
when(statement.getIndex()).thenReturn(0);
when(mutant.getStatementIndex()).thenReturn(0);
when(mutation.getSplice()).thenReturn(splice);
}
@Test
public void simpleSourceWithInnerJoin() {
String sql = "select a from foo inner join bar on foo.a = bar.a";
// 0 select a from foo inner join bar on foo.a = bar.a
// --012345678901234567890123456
String expectedMutatedSql = "select a from foo left outer join bar on foo.a = bar.a;\n";
when(statement.getSql()).thenReturn(sql);
when(mutation.getReplacementText()).thenReturn("left outer");
when(splice.getStartIndex()).thenReturn(18);
when(splice.getStopIndex()).thenReturn(22);
MutatedSource mutatedSource = mutatedSourceFactory.newMutatedSource(source, mutant);
String actualMutatedSql = mutatedSource.getScripts().get(0).getSql();
assertEquals(expectedMutatedSql, actualMutatedSql);
}
@Test
public void simpleSourceWithEqual() {
String sql = "select a from foo inner join bar on foo.a = bar.a";
// 0 select a from foo inner join bar on foo.a = bar.a
// --0123456789012345678901234567890123456789012345678
String expectedMutatedSql = "select a from foo inner join bar on foo.a <> bar.a;\n";
when(statement.getSql()).thenReturn(sql);
when(mutation.getReplacementText()).thenReturn("<>");
when(splice.getStartIndex()).thenReturn(42);
when(splice.getStopIndex()).thenReturn(42);
MutatedSourceFactory mutatedSourceFactory = new MutatedSourceFactory();
MutatedSource mutatedSource = mutatedSourceFactory.newMutatedSource(source, mutant);
String actualMutatedSql = mutatedSource.getScripts().get(0).getSql();
assertEquals(expectedMutatedSql, actualMutatedSql);
}
}
| 34.886957 | 92 | 0.747009 |
141effca85920562540b1987fc1a1d64e2762e2e | 4,357 | /**
* 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 demo.jaxrs.tracing.server;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.json.Json;
import javax.json.JsonObject;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.apache.cxf.tracing.Traceable;
import org.apache.cxf.tracing.TracerContext;
@Path("/catalog")
public class Catalog {
private final ExecutorService executor = Executors.newFixedThreadPool(2);
private final CatalogStore store;
public Catalog() {
store = new CatalogStore();
}
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response addBook(@Context final UriInfo uriInfo, @Context final TracerContext tracing,
@FormParam("title") final String title) {
try {
final String id = UUID.randomUUID().toString();
executor.submit(
tracing.wrap("Inserting New Book",
new Traceable<Void>() {
public Void call(final TracerContext context) throws Exception {
store.put(id, title);
return null;
}
}
)
).get(10, TimeUnit.SECONDS);
return Response
.created(uriInfo.getRequestUriBuilder().path(id).build())
.build();
} catch (final Exception ex) {
return Response
.serverError()
.entity(Json
.createObjectBuilder()
.add("error", ex.getMessage())
.build())
.build();
}
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public void getBooks(@Suspended final AsyncResponse response,
@Context final TracerContext tracing) throws Exception {
tracing.continueSpan(new Traceable<Void>() {
@Override
public Void call(final TracerContext context) throws Exception {
executor.submit(tracing.wrap("Looking for books", new Traceable<Void>() {
@Override
public Void call(final TracerContext context) throws Exception {
response.resume(store.scan());
return null;
}
}));
return null;
}
});
}
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject getBook(@PathParam("id") final String id) throws IOException {
final JsonObject book = store.get(id);
if (book == null) {
throw new NotFoundException("Book with does not exists: " + id);
}
return book;
}
@DELETE
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response delete(@PathParam("id") final String id) throws IOException {
if (!store.remove(id)) {
throw new NotFoundException("Book with does not exists: " + id);
}
return Response.ok().build();
}
}
| 32.036765 | 97 | 0.620611 |
6be3886b820ca811d49360dcaeb40d78e38c64e1 | 4,690 | package webhook.teamcity.payload.format;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.HashMap;
import java.util.TreeMap;
import org.junit.Before;
import org.junit.Test;
import jetbrains.buildServer.parameters.ParametersProvider;
import jetbrains.buildServer.responsibility.ResponsibilityEntry;
import jetbrains.buildServer.serverSide.SBuildServer;
import jetbrains.buildServer.users.User;
import webhook.teamcity.MockSBuildType;
import webhook.teamcity.MockSProject;
import webhook.teamcity.executor.WebHookResponsibilityHolder;
import webhook.teamcity.payload.PayloadTemplateEngineType;
import webhook.teamcity.payload.WebHookPayloadManager;
import webhook.teamcity.payload.WebHookTemplateContent;
import webhook.teamcity.payload.content.ExtraParameters;
import webhook.teamcity.payload.variableresolver.WebHookVariableResolverManager;
import webhook.teamcity.payload.variableresolver.WebHookVariableResolverManagerImpl;
import webhook.teamcity.payload.variableresolver.velocity.WebHooksBeanUtilsVelocityVariableResolverFactory;
public class WebHookPayloadJsonVelocityTemplateTest {
WebHookVariableResolverManager variableResolverManager = new WebHookVariableResolverManagerImpl();
WebHookPayloadJsonVelocityTemplate whp;
WebHookPayloadManager whpm;
ResponsibilityEntry responsibilityEntryOld;
ResponsibilityEntry responsibilityEntryNew;
@Before
public void setup() {
User user = mock(User.class);
when(user.getDescriptiveName()).thenReturn("Fred", "Bob");
responsibilityEntryOld = mock(ResponsibilityEntry.class);
responsibilityEntryNew = mock(ResponsibilityEntry.class);
when(responsibilityEntryOld.getResponsibleUser()).thenReturn(user);
when(responsibilityEntryNew.getResponsibleUser()).thenReturn(user);
when(responsibilityEntryOld.getComment()).thenReturn("Comment Old");
when(responsibilityEntryNew.getComment()).thenReturn("Comment New");
SBuildServer buildServer = mock(SBuildServer.class);
when(buildServer.getRootUrl()).thenReturn("http://test.url");
variableResolverManager.registerVariableResolverFactory(new WebHooksBeanUtilsVelocityVariableResolverFactory());
whp = new WebHookPayloadJsonVelocityTemplate(new WebHookPayloadManager(buildServer), variableResolverManager);
}
@Test
public void testRegister() {
SBuildServer mockServer = mock(SBuildServer.class);
when(mockServer.getRootUrl()).thenReturn("http://test.url");
WebHookPayloadManager wpm = new WebHookPayloadManager(mockServer);
WebHookPayloadJsonVelocityTemplate whp = new WebHookPayloadJsonVelocityTemplate(wpm, variableResolverManager);
whp.register();
assertEquals(whp, wpm.getFormat(whp.getFormatShortName()));
}
@Test
public void testGetContentType() {
assertEquals(whp.getContentType().toString(), "application/json");
}
@Test
public void testGetRank() {
assertEquals(Integer.valueOf(101),whp.getRank());
}
@Test
public void testSetRank() {
whp.setRank(10);
assertEquals(Integer.valueOf(10), whp.getRank());
}
@Test
public void testGetCharset() {
assertEquals("UTF-8", whp.getCharset());
}
@Test
public void testGetFormatDescription() {
assertEquals("JSON Velocity template", whp.getFormatDescription());
}
@Test
public void testGetFormatShortName() {
assertEquals("jsonVelocityTemplate", whp.getFormatShortName());
}
@Test
public void testGetTemplateEngineType() {
assertEquals(PayloadTemplateEngineType.VELOCITY, whp.getTemplateEngineType());
}
@Test
public void testGetFormatToolTipText() {
assertEquals("Send a JSON payload with content from a Velocity template", whp.getFormatToolTipText());
}
@Test
public void testResponsibleChanged() {
ParametersProvider pp = mock(ParametersProvider.class);
when(pp.getAll()).thenReturn(new HashMap<String,String>());
MockSBuildType buildType = new MockSBuildType("mockBuildType", "a description", "bt01");
buildType.setParametersProvider(pp);
MockSProject project = new MockSProject("name", "description", "projectId", "projectExternalId", buildType);
buildType.setProject(project);
WebHookTemplateContent templateContent = WebHookTemplateContent.create(
"responsibilityChanged",
"{ \"testing\": \"${buildTypeId}\" }",
true,
""
);
assertEquals("{ \"testing\": \"mockBuildType\" }", whp.responsibilityChanged(
WebHookResponsibilityHolder
.builder()
.responsibilityEntryOld(responsibilityEntryOld)
.responsibilityEntryNew(responsibilityEntryNew)
.sBuildType(buildType)
.sProject(project)
.build(),
new ExtraParameters(),
new TreeMap<String,String>(),
templateContent));
}
}
| 34.485294 | 114 | 0.793603 |
29b64884f284ff88a9b2d55c17ef7d29cee2d6a5 | 324 | package io.advantageous.qbit.service.discovery;
import io.advantageous.qbit.annotation.EventChannel;
/**
* ServiceChangedChannel
* created by rhightower on 3/23/15.
*/
@EventChannel
public interface ServiceChangedEventChannel {
void servicePoolChanged(String serviceName);
default void flushEvents() {
}
}
| 20.25 | 52 | 0.765432 |
992f3b1e30c9dd000b69abb7ea90a2d70aec1637 | 2,952 | /*
* Copyright (c) 2014, Cloudera, Inc. All Rights Reserved.
*
* Cloudera, Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* This software 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.cloudera.oryx.common.random;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.commons.math3.random.RandomGenerator;
import org.apache.commons.math3.random.Well19937c;
/**
* Manages random number generation. Allows resetting RNGs to a known state for testing.
*/
public final class RandomManager {
private static final long TEST_SEED = getTestSeed();
private static final Reference<? extends Collection<RandomGenerator>> INSTANCES =
new SoftReference<>(new ArrayList<>());
private static boolean useTestSeed;
private RandomManager() {
}
private static long getTestSeed() {
String seedString = System.getProperty("oryx.test.seed", "1234567890123456789");
try {
return Long.parseLong(seedString);
} catch (NumberFormatException nfe) {
return Long.parseLong(seedString, 16);
}
}
/**
* @return a new, seeded {@link RandomGenerator}
*/
public static RandomGenerator getRandom() {
if (useTestSeed) {
// No need to track instances anymore
return new Well19937c(TEST_SEED);
}
return getUnseededRandom();
}
static RandomGenerator getUnseededRandom() {
RandomGenerator random = new Well19937c();
Collection<RandomGenerator> instances = INSTANCES.get();
if (instances != null) {
synchronized (instances) {
instances.add(random);
}
} // else oh well, only matters in tests
return random;
}
/**
* @param seed explicit seed for random number generator
* @return a new, seeded {@link RandomGenerator}
*/
public static RandomGenerator getRandom(long seed) {
// Don't track these or use the test seed as the caller has manually specified
// the seeding behavior
return new Well19937c(seed);
}
/**
* <em>Only call in test code.</em> Causes all known instances of {@link RandomGenerator},
* and future ones, to be started from a fixed seed. This is useful for making
* tests deterministic.
*/
public static void useTestSeed() {
useTestSeed = true;
Collection<RandomGenerator> instances = INSTANCES.get();
if (instances != null) {
synchronized (instances) {
instances.forEach(random -> random.setSeed(TEST_SEED));
instances.clear();
}
INSTANCES.clear();
}
}
}
| 29.818182 | 92 | 0.695799 |
1b0f9e10381586c48addcc9c61af426be6df0638 | 1,962 | import java.util.*;
import org.junit.Test;
import static org.junit.Assert.*;
// LC1738: https://leetcode.com/problems/find-kth-largest-xor-coordinate-value/
//
// You are given a 2D matrix of size m x n, consisting of non-negative integers. You are also given
// an integer k. The value of coordinate (a, b) of the matrix is the XOR of all matrix[i][j] where
// 0 <= i <= a < m and 0 <= j <= b < n (0-indexed). Find the kth largest value (1-indexed) of all
// the coordinates of matrix.
//
// Constraints:
// m == matrix.length
// n == matrix[i].length
// 1 <= m, n <= 1000
// 0 <= matrix[i][j] <= 10^6
// 1 <= k <= m * n
public class KthLargestXORCoordinateValue {
// Heap + Dynamic Programming
// time complexity: O(M*N*log(K)), space complexity: O(M*N)
// 215 ms(82.98%), 198.7 MB(38.83%) for 49 tests
public int kthLargestValue(int[][] matrix, int k) {
int m = matrix.length;
int n = matrix[0].length;
int[][] dp = new int[m + 1][n + 1];
PriorityQueue<Integer> pq = new PriorityQueue<>(k + 1);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int a = dp[i + 1][j + 1] = dp[i][j + 1] ^ dp[i + 1][j] ^ dp[i][j] ^ matrix[i][j];
pq.offer(a);
if (pq.size() > k) {
pq.poll();
}
}
}
return pq.peek();
}
private void test(int[][] matrix, int k, int expected) {
assertEquals(expected, kthLargestValue(matrix, k));
}
@Test public void test() {
test(new int[][] {{5, 2}, {1, 6}}, 1, 7);
test(new int[][] {{5, 2}, {1, 6}}, 2, 5);
test(new int[][] {{5, 2}, {1, 6}}, 3, 4);
test(new int[][] {{5, 2}, {1, 6}}, 4, 0);
}
public static void main(String[] args) {
String clazz = new Object() {
}.getClass().getEnclosingClass().getSimpleName();
org.junit.runner.JUnitCore.main(clazz);
}
}
| 33.827586 | 99 | 0.523445 |
459062489b503b5e6d3dde8565127cc528ae0c7d | 12,874 | /*
New BSD License http://www.opensource.org/licenses/bsd-license.php
Copyright (c) 2017, Beck Yang
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 com.beck.tool;
import static com.beck.kml.source.KMLSource.unGzip;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;
import javax.swing.JLabel;
import javax.swing.*;
import com.beck.kml.model.Placemark;
import com.beck.kml.source.KMLSource;
import com.beck.kml.source.KMLSourceFactory;
import com.beck.kml.source.YoubikeKML;
public class YoubikeKMLUI extends JPanel {
private static final long serialVersionUID = 4773652794390020385L;
private final String[] URLS = new String[] {"ntpc", "taichung", "chcg", "tycg", "hccg", "sipa", "taipei"};
final private JTextArea txLog;
final private JComboBox<String> cmbUrl;
final private JComboBox<String> ckOutputEnglish;
final private JRadioButton rdOpenData;
final private JRadioButton rdUrl;
final private JRadioButton rdFile;
private File inputFile;
private File outputFile;
public YoubikeKMLUI() {
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[] {65, 0, 0};
gridBagLayout.rowHeights = new int[]{23, 0, 0, 0, 0, 0, 0};
gridBagLayout.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
setLayout(gridBagLayout);
ButtonGroup buttonGroup = new ButtonGroup();
rdFile = new JRadioButton("[Select input file]");
buttonGroup.add(rdFile);
GridBagConstraints gbc_rdFile = new GridBagConstraints();
gbc_rdFile.gridwidth = 2;
gbc_rdFile.anchor = GridBagConstraints.NORTHWEST;
gbc_rdFile.gridx = 0;
gbc_rdFile.gridy = 0;
add(rdFile, gbc_rdFile);
rdOpenData = new JRadioButton("Download data of Taipei city (opendata)");
rdOpenData.setSelected(true);
buttonGroup.add(rdOpenData);
add(rdOpenData, new GridBagConstraints(0, 1,
2, 1, 0, 0,
GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 0, 0), 0, 0));
rdUrl = new JRadioButton("Download from official site, location:");
buttonGroup.add(rdUrl);
GridBagConstraints gbc_rdUrl = new GridBagConstraints();
gbc_rdUrl.anchor = GridBagConstraints.WEST;
gbc_rdUrl.insets = new Insets(0, 0, 0, 3);
gbc_rdUrl.gridx = 0;
gbc_rdUrl.gridy = 2;
add(rdUrl, gbc_rdUrl);
cmbUrl = new JComboBox<String>();
cmbUrl.setEditable(true);
cmbUrl.setModel(new DefaultComboBoxModel<String>(URLS));
GridBagConstraints gbc_cmbUrl = new GridBagConstraints();
gbc_cmbUrl.fill = GridBagConstraints.HORIZONTAL;
gbc_cmbUrl.gridx = 1;
gbc_cmbUrl.gridy = 2;
add(cmbUrl, gbc_cmbUrl);
add(new JLabel("Data language:"), new GridBagConstraints(0, 3,
1, 1, 0, 0,
GridBagConstraints.EAST, GridBagConstraints.NONE,
new Insets(0, 0, 0, 7), 0, 0));
ckOutputEnglish = new JComboBox<String>();
ckOutputEnglish.setModel(new DefaultComboBoxModel<String>(new String[]{"tw","en"}));
GridBagConstraints gbc_chckbxNewCheckBox = new GridBagConstraints();
gbc_chckbxNewCheckBox.anchor = GridBagConstraints.WEST;
gbc_chckbxNewCheckBox.gridwidth = 1;
gbc_chckbxNewCheckBox.gridx = 1;
gbc_chckbxNewCheckBox.gridy = 3;
add(ckOutputEnglish, gbc_chckbxNewCheckBox);
JButton btnNewButton = new JButton("Convert to KML");
GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
//gbc_btnNewButton.fill = GridBagConstraints.HORIZONTAL;
gbc_btnNewButton.insets = new Insets(3, 10, 3, 10);
gbc_btnNewButton.gridwidth = 2;
gbc_btnNewButton.gridx = 0;
gbc_btnNewButton.gridy = 4;
add(btnNewButton, gbc_btnNewButton);
txLog = new JTextArea();
JScrollPane scrollPane = new JScrollPane(txLog);
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
gbc_scrollPane.gridwidth = 2;
gbc_scrollPane.fill = GridBagConstraints.BOTH;
gbc_scrollPane.gridx = 0;
gbc_scrollPane.gridy = 5;
add(scrollPane, gbc_scrollPane);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
convertKML();
}
});
rdFile.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
selectInputFile();
}
});
}
private void selectInputFile() {
openDialog(inputFile, "Select source data file").ifPresent(file -> {
inputFile = file;
rdFile.setText("Input file ["+inputFile.getAbsolutePath()+"]");
});
}
private Optional<File> openDialog(final File f, final String dialogTitle) {
final JFileChooser dialog = new JFileChooser();
dialog.setDialogTitle(dialogTitle);
if (f != null) {
dialog.setSelectedFile(f);
}
if (dialog.showDialog(getParent(), null) == JFileChooser.APPROVE_OPTION) {
return Optional.of(dialog.getSelectedFile());
}
return Optional.empty();
}
private void convertKML() {
final StringWriter sw = new StringWriter(256);
final PrintWriter pw = new PrintWriter(sw);
try {
final YoubikeKML youbikeKML = new YoubikeKML();
Map<String, String> options = new HashMap<>();
byte[] data = null;
if (rdFile.isSelected()) {
if (inputFile == null || !inputFile.exists()) {
pw.println("Input file does not exist");
} else {
pw.printf("Try to read data from [%s]\n", inputFile.getAbsolutePath());
data = Files.readAllBytes(inputFile.toPath());
}
} else if (rdOpenData.isSelected()){
data = download("http://data.taipei/youbike", null, null);
options.put("en", "true");
} else if (rdUrl.isSelected()){
final String loc = String.valueOf(cmbUrl.getSelectedItem());
final String lang = String.valueOf(ckOutputEnglish.getSelectedItem());
pw.printf("Try to download data location=%s, lang=%s\n", loc, lang);
data = download("https://apis.youbike.com.tw/useAPI", "https://"+loc+".youbike.com.tw/station/list", "action=ub_site_by_sno_class&datas[lang]="+lang+"&datas[loc]="+loc);
}
if (data != null) {
final String json = new String(unGzip(data), "UTF-8");
if (outputFile == null) {
outputFile = new File("youbike.kml");
}
Optional<File> fout = openDialog(outputFile, "Select output kml file");
if (!fout.isPresent()) {
pw.println("Action canceled - output file must be selected");
} else {
outputFile = fout.get();
final Collection<Placemark> list = youbikeKML.parse(json, options);
pw.println("parse complete - stations found");;
new KMLWriter(youbikeKML.getKMLName(), true).out(list).write(outputFile);
pw.printf("Complete - output file [%s]\n", outputFile.getAbsolutePath());
}
}
} catch (IllegalArgumentException ie) {
pw.println(ie.getMessage());
} catch (Throwable e) {
e.printStackTrace(pw);
}
txLog.setText(sw.toString());
}
public static byte[] download(final String url, final String refer, final String postData) throws Exception {
URLConnection urlc = new URL(url).openConnection();
if (urlc instanceof HttpURLConnection) {
final HttpURLConnection hconn = (HttpURLConnection)urlc;
hconn.setRequestProperty("Referer", refer);
hconn.setInstanceFollowRedirects(true);
if (postData != null) {
hconn.setDoOutput(true);
try (final OutputStream out = hconn.getOutputStream()){
out.write(postData.getBytes());
}
}
final int stat = hconn.getResponseCode();
if (stat == HttpURLConnection.HTTP_MOVED_PERM || stat == HttpURLConnection.HTTP_MOVED_TEMP) {
final String location = hconn.getHeaderField("Location");
if (location.indexOf("//") == -1) {
urlc = new URL(new URL(url), location).openConnection();
} else {
urlc = new URL(location).openConnection();
}
}
}
try (final InputStream in = urlc.getInputStream()) {
return KMLSource.readAllBytes(in);
} catch (Exception e) {
byte[] result = null;
if (urlc instanceof HttpURLConnection) {
try (final InputStream err = ((HttpURLConnection)urlc).getErrorStream()) {
if (err != null) {
result = KMLSource.readAllBytes(err);
}
}
}
if (result == null) {
throw e;
} else {
return result;
}
}
}
public static void main(final String[] args) throws Exception {
if (args.length == 0) {
//launch GUI
JFrame frame = new JFrame();
frame.setTitle("Convert Youbike open data to KML file");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new YoubikeKMLUI());
frame.setSize(420, 400);
frame.doLayout();
frame.setVisible(true);
return;
}
KMLSource kmlSource = null;
String inputFile = "youbike";
String outputFile = "youbike.kml";
Map<String, String> options = new HashMap<>();
boolean checkSamePoint = true;
for (int i = 0; i < args.length; i++) {
String arg = args[i].trim();
if (arg.startsWith("-h")) {
System.out.println("YoutubeKML - Convert Youbike open data to KML file");
System.out.println(" Command line options:");
System.out.println("-i [file] input file, or folder with input files");
System.out.println("-o [file] output file(kml)");
System.out.println("-t [type] source type or qualified java class");
System.out.println("-h print help");
System.out.println("-nocheck Do NOT add if duplicate point exist (default:true)");
System.out.println("-en output English description in KML(only work for youbike opendata)");
System.out.println(" GUI will start up if no command options.");
return;
} else {
String fn = (i+1)==args.length?null:args[i+1];
if ("-i".equals(arg)) {
inputFile = fn;
i++;
} else if ("-o".equals(arg)) {
outputFile = fn;
i++;
} else if ("-t".equals(arg)) {
final Optional<KMLSource> opt = KMLSourceFactory.newKMLSource(fn);
if (opt.isPresent()) {
kmlSource = opt.get();
} else {
System.out.printf("source type [%s] does not exist", fn);
return;
}
i++;
} else if ("-en".equals(arg)) {
options.put("en", "true");
} else if ("-nocheck".equals(arg)) {
checkSamePoint = false;
}
}
}
final Iterable<Placemark> list;
final File f = new File(inputFile);
if (f.isDirectory()) {
final ArrayList<Placemark> alist = new ArrayList<>();
final KMLSource ks = kmlSource;
Stream.of(f.listFiles()).sorted(Comparator.comparing(File::lastModified)).forEach(file -> {
try {
alist.addAll(ks.parse(ks.read(file)));
} catch (Exception e) {
throw new RuntimeException(e);
}
});
list = alist;
} else {
list = kmlSource.parse(kmlSource.read(f));
}
new KMLWriter(kmlSource.getKMLName(), checkSamePoint).out(list).write(new File(outputFile));
}
}
| 37.424419 | 174 | 0.681451 |
6ca35d1211a843d8f77788915c380606906d84d3 | 185 | package ru.gdg.kazan.gdgkazan.screens.splash;
/**
* @author Artur Vasilov
*/
public interface SplashView {
void showLoading();
void showError();
void showEvents();
}
| 12.333333 | 45 | 0.664865 |
c1f22740cd0100075970908a0aaadcbe86263976 | 1,333 | package com.twu.biblioteca;
import java.io.IOException;
import java.util.Optional;
public class ReturnBook implements Command {
private Output out;
private Input input;
private Catalog catalog;
private ListBooks listBooksCommand;
public ReturnBook(final Output out,
final Input input,
final Catalog catalog,
final ListBooks listBooksCommand) {
this.out = out;
this.input = input;
this.catalog = catalog;
this.listBooksCommand = listBooksCommand;
}
@Override
public void perform(final BibliotecaApp app) throws IOException {
listBooksCommand.printCheckedOutBookList();
out.write("Enter id of book to return: ");
Optional<Integer> selection = input.getSelection();
if (selection.isPresent()) {
Integer bookId = selection.get();
BookStatus status = catalog.checkBookStatus(bookId);
if (status == BookStatus.CHECKED_OUT) {
catalog.returnBook(bookId);
out.write("Thank you for returning the book.");
} else {
out.write("That is not a valid book to return.");
}
}
}
@Override
public String toString() {
return "Return a book";
}
}
| 29.622222 | 69 | 0.597149 |
9239cd9f889a7428e949f52efc85a53c31976424 | 1,559 | /*
* Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
* OF ANY KIND, either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
package com.zappos.json.benchmark.data;
import java.util.Random;
import com.zappos.json.util.Strings;
/**
*
* @author Hussachai Puripunpinyo
*
*/
public class SimpleBean {
private static final Random RANDOM = new Random();
private String string;
private Boolean flag;
private int number;
public static SimpleBean random(){
SimpleBean bean = new SimpleBean();
bean.string = Strings.randomAlphabetic(32);
bean.flag = RANDOM.nextBoolean();
bean.number = RANDOM.nextInt(100);
return bean;
}
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
public Boolean getFlag() {
return flag;
}
public void setFlag(Boolean flag) {
this.flag = flag;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}
| 22.271429 | 76 | 0.65619 |
942226a6450fa8afffa7f27c98d8b4f08d52c016 | 2,191 | package com.cherry.jeeves.domain.request;
import com.cherry.jeeves.domain.request.component.BaseRequest;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
public class UploadMediaRequest {
@JsonProperty
private BaseRequest BaseRequest;
@JsonProperty
private String FromUserName;
@JsonProperty
private String ToUserName;
@JsonProperty
private String FileMd5;
@JsonProperty
private long ClientMediaId;
@JsonProperty
private long DataLen;
@JsonProperty
private long TotalLen;
@JsonProperty
private int StartPos;
@JsonProperty
private int MediaType;
@JsonProperty
private int UploadType;
public BaseRequest getBaseRequest() {
return BaseRequest;
}
public void setBaseRequest(BaseRequest baseRequest) {
BaseRequest = baseRequest;
}
public long getClientMediaId() {
return ClientMediaId;
}
public void setClientMediaId(long clientMediaId) {
ClientMediaId = clientMediaId;
}
public long getDataLen() {
return DataLen;
}
public void setDataLen(long dataLen) {
DataLen = dataLen;
}
public long getTotalLen() {
return TotalLen;
}
public void setTotalLen(long totalLen) {
TotalLen = totalLen;
}
public int getStartPos() {
return StartPos;
}
public void setStartPos(int startPos) {
StartPos = startPos;
}
public int getMediaType() {
return MediaType;
}
public void setMediaType(int mediaType) {
MediaType = mediaType;
}
public String getFromUserName() {
return FromUserName;
}
public void setFromUserName(String fromUserName) {
FromUserName = fromUserName;
}
public String getToUserName() {
return ToUserName;
}
public void setToUserName(String toUserName) {
ToUserName = toUserName;
}
public String getFileMd5() {
return FileMd5;
}
public void setFileMd5(String fileMd5) {
FileMd5 = fileMd5;
}
public int getUploadType() {
return UploadType;
}
public void setUploadType(int uploadType) {
UploadType = uploadType;
}
} | 19.389381 | 62 | 0.76084 |
c84caebfd1be538994c20baa86af880cd1f6fa2e | 3,019 | /*
* 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.bookkeeper.clients.impl.internal;
import static org.apache.bookkeeper.clients.impl.internal.ProtocolInternalUtils.createActiveRanges;
import static org.apache.bookkeeper.stream.protocol.util.ProtoUtils.createGetActiveRangesRequest;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import lombok.extern.slf4j.Slf4j;
import org.apache.bookkeeper.clients.impl.container.StorageContainerChannel;
import org.apache.bookkeeper.clients.impl.container.StorageContainerChannelManager;
import org.apache.bookkeeper.clients.impl.internal.api.HashStreamRanges;
import org.apache.bookkeeper.clients.impl.internal.api.MetaRangeClient;
import org.apache.bookkeeper.clients.impl.internal.mr.MetaRangeRequestProcessor;
import org.apache.bookkeeper.common.util.OrderedScheduler;
import org.apache.bookkeeper.stream.proto.StreamProperties;
/**
* A default implementation for {@link MetaRangeClient}.
*/
@Slf4j
class MetaRangeClientImpl implements MetaRangeClient {
private final StreamProperties streamProps;
private final ScheduledExecutorService executor;
private final StorageContainerChannel scClient;
MetaRangeClientImpl(StreamProperties streamProps,
OrderedScheduler scheduler,
StorageContainerChannelManager channelManager) {
this.streamProps = streamProps;
this.executor = scheduler.chooseThread(streamProps.getStreamId());
this.scClient = channelManager.getOrCreate(streamProps.getStorageContainerId());
}
@Override
public StreamProperties getStreamProps() {
return streamProps;
}
StorageContainerChannel getStorageContainerClient() {
return scClient;
}
//
// Meta KeyRange Server Requests
//
@Override
public CompletableFuture<HashStreamRanges> getActiveDataRanges() {
return MetaRangeRequestProcessor.of(
createGetActiveRangesRequest(
scClient.getStorageContainerId(),
streamProps),
(response) -> createActiveRanges(response.getGetActiveRangesResp()),
scClient,
executor
).process();
}
}
| 38.21519 | 99 | 0.752236 |
9f2d903781ab8f9959008b17e09c489dca396c66 | 5,275 | /*
* Copyright 2014 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.gradle.api.internal.tasks.compile.incremental.cache;
import org.gradle.api.internal.cache.StringInterner;
import org.gradle.api.internal.tasks.compile.incremental.analyzer.ClassAnalysisCache;
import org.gradle.api.internal.tasks.compile.incremental.analyzer.ClassAnalysisSerializer;
import org.gradle.api.internal.tasks.compile.incremental.analyzer.DefaultClassAnalysisCache;
import org.gradle.api.internal.tasks.compile.incremental.classpath.ClasspathEntrySnapshotCache;
import org.gradle.api.internal.tasks.compile.incremental.classpath.ClasspathEntrySnapshotData;
import org.gradle.api.internal.tasks.compile.incremental.classpath.ClasspathEntrySnapshotDataSerializer;
import org.gradle.api.internal.tasks.compile.incremental.classpath.DefaultClasspathEntrySnapshotCache;
import org.gradle.api.internal.tasks.compile.incremental.classpath.SplitClasspathEntrySnapshotCache;
import org.gradle.api.internal.tasks.compile.incremental.deps.ClassAnalysis;
import org.gradle.api.internal.tasks.compile.incremental.recomp.PreviousCompilationData;
import org.gradle.api.internal.tasks.compile.incremental.recomp.PreviousCompilationStore;
import org.gradle.api.invocation.Gradle;
import org.gradle.cache.CacheRepository;
import org.gradle.cache.FileLockManager;
import org.gradle.cache.PersistentCache;
import org.gradle.cache.PersistentIndexedCache;
import org.gradle.cache.PersistentIndexedCacheParameters;
import org.gradle.cache.internal.InMemoryCacheDecoratorFactory;
import org.gradle.internal.hash.HashCode;
import org.gradle.internal.serialize.HashCodeSerializer;
import org.gradle.internal.vfs.AdditiveCacheLocations;
import org.gradle.internal.vfs.VirtualFileSystem;
import java.io.Closeable;
import static org.gradle.cache.internal.filelock.LockOptionsBuilder.mode;
public class DefaultGeneralCompileCaches implements GeneralCompileCaches, Closeable {
private final ClassAnalysisCache classAnalysisCache;
private final ClasspathEntrySnapshotCache classpathEntrySnapshotCache;
private final PersistentCache cache;
private final PersistentIndexedCache<String, PreviousCompilationData> previousCompilationCache;
public DefaultGeneralCompileCaches(
AdditiveCacheLocations additiveCacheLocations,
CacheRepository cacheRepository,
Gradle gradle,
InMemoryCacheDecoratorFactory inMemoryCacheDecoratorFactory,
StringInterner interner,
UserHomeScopedCompileCaches userHomeScopedCompileCaches,
VirtualFileSystem virtualFileSystem
) {
cache = cacheRepository
.cache(gradle, "javaCompile")
.withDisplayName("Java compile cache")
.withLockOptions(mode(FileLockManager.LockMode.None)) // Lock on demand
.open();
PersistentIndexedCacheParameters<HashCode, ClassAnalysis> classCacheParameters = PersistentIndexedCacheParameters.of("classAnalysis", new HashCodeSerializer(), new ClassAnalysisSerializer(interner))
.withCacheDecorator(inMemoryCacheDecoratorFactory.decorator(400000, true));
this.classAnalysisCache = new DefaultClassAnalysisCache(cache.createCache(classCacheParameters));
PersistentIndexedCacheParameters<HashCode, ClasspathEntrySnapshotData> jarCacheParameters = PersistentIndexedCacheParameters.of("jarAnalysis", new HashCodeSerializer(), new ClasspathEntrySnapshotDataSerializer(interner))
.withCacheDecorator(inMemoryCacheDecoratorFactory.decorator(20000, true));
this.classpathEntrySnapshotCache = new SplitClasspathEntrySnapshotCache(additiveCacheLocations, userHomeScopedCompileCaches.getClasspathEntrySnapshotCache(), new DefaultClasspathEntrySnapshotCache(virtualFileSystem, cache.createCache(jarCacheParameters)));
PersistentIndexedCacheParameters<String, PreviousCompilationData> previousCompilationCacheParameters = PersistentIndexedCacheParameters.of("taskHistory", String.class, new PreviousCompilationData.Serializer(interner))
.withCacheDecorator(inMemoryCacheDecoratorFactory.decorator(2000, false));
previousCompilationCache = cache.createCache(previousCompilationCacheParameters);
}
@Override
public void close() {
cache.close();
}
@Override
public ClassAnalysisCache getClassAnalysisCache() {
return classAnalysisCache;
}
@Override
public ClasspathEntrySnapshotCache getClasspathEntrySnapshotCache() {
return classpathEntrySnapshotCache;
}
@Override
public PreviousCompilationStore createPreviousCompilationStore(String taskPath) {
return new PreviousCompilationStore(taskPath, previousCompilationCache);
}
}
| 52.75 | 264 | 0.807583 |
f140dd602e638478dbb49e5494c594636e3deed6 | 2,267 | package com.my.edigits.servlet;
import com.my.edigits.utils.AStarUtils;
import com.my.edigits.utils.Matutils;
import com.my.edigits.utils.Node;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
@WebServlet("/every.do")
public class EveryServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String startarr = req.getParameter("startarr");
String endarr = req.getParameter("endarr");
System.out.println(startarr);
System.out.println(endarr);
Integer[] start = new Integer[9];
Integer[] end = new Integer[9];
//在这里判断一下是否有解!!没解或者非法输入说明用户修改了js文件
String[] s_strs = startarr.split(",");
String[] e_strs = endarr.split(",");
Integer[] test1 = {0,0,0,0,0,0,0,0,0};
Integer[] test2 = {0,0,0,0,0,0,0,0,0};
for(int i = 0; i < 9; ++ i){
start[i] = Integer.valueOf(s_strs[i]);
end[i] = Integer.valueOf(e_strs[i]);
++ test1[start[i]];
++ test2[end[i]];
}
boolean isVaild = true;
for(int i = 0; i < 9; ++ i){
if(test1[i] != 1 || test2[i] != 1){
isVaild = false;
break;
}
}
boolean hasSolution = Matutils.haveSolution(start,end);
if(!isVaild || !hasSolution){
req.getRequestDispatcher("/WEB-INF/view/error/404.jsp").forward(req,resp);
return;
}
AStarUtils aStarUtils = new AStarUtils(new Node(start),new Node(end));
aStarUtils.search();
ArrayList<String> solution = aStarUtils.getSolution();
req.setAttribute("solution",solution);
req.setAttribute("step",solution.size() - 1);
req.getRequestDispatcher("/WEB-INF/view/biz/solution.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
| 35.984127 | 114 | 0.626378 |
6d5226b55d39e169f9d54815b5194791f3de2b61 | 1,940 | package com.nano.candy.std;
import com.nano.candy.utils.Characters;
public class Names {
public static final String MOUDLE_FILE_NAME = "__module__.cd";
public static final String MAIN_FILE_NAME = "main.cd";
public static final String METHOD_INITALIZER = "init";
public static final String METHOD_ITERATOR = "_iterator";
public static final String METHOD_ITERATOR_HAS_NEXT = "_hasNext";
public static final String METHOD_ITERATOR_NEXT = "_next";
public static final String METHOD_HASH_CODE = "_hashCode";
public static final String METHOD_EQUALS = "_equals";
public static final String METHOD_STR_VALUE = "_str";
public static final String METHOD_SET_ATTR = "_setAttr";
public static final String METHOD_GET_ATTR = "_getAttr";
public static final String METHOD_GET_UNKNOWN_ATTR = "_getUnknownAttr";
public static final String METHOD_SET_ITEM = "_setItem";
public static final String METHOD_GET_ITEM = "_getItem";
public static final String METHOD_OP_POSITIVE = "_positive";
public static final String METHOD_OP_NEGATIVE = "_negative";
public static final String METHOD_OP_ADD = "_add";
public static final String METHOD_OP_SUB = "_sub";
public static final String METHOD_OP_MUL = "_mul";
public static final String METHOD_OP_DIV = "_div";
public static final String METHOD_OP_MOD = "_mod";
public static final String METHOD_OP_GT = "_gt";
public static final String METHOD_OP_GTEQ = "_gteq";
public static final String METHOD_OP_LT = "_lt";
public static final String METHOD_OP_LTEQ = "_lteq";
private Names(){}
public static boolean isCandyIdentifier(String name) {
if (name.length() == 0) {
return false;
}
if (!Characters.isCandyIdentifierStart(name.charAt(0))) {
return false;
}
final int len = name.length();
for (int i = 1; i < len; i ++) {
char ch = name.charAt(i);
if (!Characters.isCandyIdentifier(ch)) {
return false;
}
}
return true;
}
}
| 32.333333 | 72 | 0.741753 |
ac23e881340645b2270dfc09cceeb62656d64480 | 969 | /*
* (C) Copyright IBM Corp. 2021
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.alvearie.imaging.ingestion.model.result;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonInclude(Include.NON_NULL)
public class DicomAttribute {
@JsonProperty("vr")
private String vr;
@JsonProperty("Value")
private List<String> value;
public String getVr() {
return vr;
}
public void setVr(String vr) {
this.vr = vr;
}
public List<String> getValue() {
return value;
}
public void addValue(String value) {
if (this.value == null) {
this.value = new ArrayList<String>();
}
this.value.add(value);
}
}
| 21.065217 | 60 | 0.675955 |
6c85ae41a62f74c6296788289652cfdd88e26c5f | 2,164 | /**********************************************************************************
*
* $Id$
*
***********************************************************************************
*
* Copyright (c) 2005, 2006 The Sakai Foundation, The MIT Corporation
*
* 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/ECL-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.sakaiproject.tool.gradebook;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
/**
* A LetterGradeMapping defines the set of grades available to a gradebook as
* "A", "B", "C", "D", and "F", each of which can be mapped to a minimum
* percentage value.
*
*/
public class LetterGradeMapping extends GradeMapping {
private static final long serialVersionUID = 1L;
private List grades;
private List defaultValues;
@Override
public Collection getGrades() {
return grades;
}
@Override
public List getDefaultValues() {
return defaultValues;
}
public LetterGradeMapping() {
setGradeMap(new LinkedHashMap());
grades = new ArrayList();
grades.add("A");
grades.add("B");
grades.add("C");
grades.add("D");
grades.add("F");
defaultValues = new ArrayList();
defaultValues.add(Double.valueOf(90));
defaultValues.add(Double.valueOf(80));
defaultValues.add(Double.valueOf(70));
defaultValues.add(Double.valueOf(60));
defaultValues.add(Double.valueOf(00));
setDefaultValues();
}
@Override
public String getName() {
return "Letter Grades";
}
}
| 27.74359 | 83 | 0.608595 |
4d6af63365459ab20553f6ff2d17012915377106 | 266 | package com.sorm.core;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public interface CallBack {
public Object doExecute(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet);
}
| 22.166667 | 107 | 0.785714 |
11dc3e022218f40399549629a3858c0e4bd6cc9a | 1,504 | package net.quikkly.android.react;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.annotations.ReactProp;
import java.util.Map;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class QuikklyScanViewManager extends SimpleViewManager<QuikklyScanView> {
private static final String TAG = "QuikklyScanViewManager";
private static final String REACT_CLASS = "QuikklyScanView";
@Nonnull
@Override
public String getName() {
return REACT_CLASS;
}
@Nullable
@Override
@SuppressWarnings("unchecked")
public Map<String, Object> getExportedCustomBubblingEventTypeConstants() {
return (Map)MapBuilder.builder().put("scanCode",
MapBuilder.of("phasedRegistrationNames",
MapBuilder.of("bubbled", "onScanCode")))
.build();
}
@Nonnull
@Override
protected QuikklyScanView createViewInstance(@Nonnull ThemedReactContext context) {
return new QuikklyScanView(context);
}
@Override
public void onDropViewInstance(QuikklyScanView view) {
super.onDropViewInstance(view);
view.cleanupView();
}
@ReactProp(name = "cameraPreviewFit")
public void setCameraPreviewFit(QuikklyScanView view, Integer cameraPreviewFit) {
view.setCameraPreviewFit(cameraPreviewFit);
}
}
| 29.490196 | 87 | 0.716755 |
8eab3f919e2e2bd6f220dac0004dce8283e7bae4 | 3,128 | package net.sf.regadb.ui.datatable.query;
import java.util.List;
import net.sf.regadb.db.QueryDefinitionRun;
import net.sf.regadb.db.QueryDefinitionRunStatus;
import net.sf.regadb.db.Transaction;
import net.sf.regadb.ui.framework.RegaDBMain;
import net.sf.regadb.ui.framework.forms.SelectForm;
import net.sf.regadb.ui.framework.widgets.datatable.DefaultDataTable;
import net.sf.regadb.ui.framework.widgets.datatable.IFilter;
import net.sf.regadb.ui.framework.widgets.datatable.StringFilter;
import net.sf.regadb.ui.framework.widgets.datatable.hibernate.HibernateStringUtils;
import eu.webtoolkit.jwt.WString;
public class ISelectQueryDefinitionRunDataTable extends DefaultDataTable<QueryDefinitionRun>
{
public ISelectQueryDefinitionRunDataTable(
SelectForm<QueryDefinitionRun> form) {
super(form);
}
private static WString [] _colNames = {
WString.tr("dataTable.queryDefinitionRun.colName.name"),
WString.tr("dataTable.queryDefinitionRun.colName.query"),
WString.tr("dataTable.queryDefinitionRun.colName.description"),
WString.tr("dataTable.queryDefinitionRun.colName.status")};
private static String[] filterVarNames_ = {"queryDefinitionRun.name", "queryDefinitionRun.queryDefinition.name", "queryDefinitionRun.queryDefinition.description", "queryDefinitionRun.status"};
private static boolean [] sortable_ = {true, true, true, true};
private static int[] colWidths = {20,20,40,20};
private IFilter[] filters_ = new IFilter[4];
public CharSequence[] getColNames()
{
return _colNames;
}
public List<QueryDefinitionRun> getDataBlock(Transaction t, int startIndex, int amountOfRows, int sortIndex, boolean ascending)
{
return t.getQueryDefinitionRuns(startIndex, amountOfRows, filterVarNames_[sortIndex], HibernateStringUtils.filterConstraintsQuery(this), ascending, RegaDBMain.getApp().getLogin().getUid());
}
public long getDataSetSize(Transaction t)
{
return t.getQueryDefinitionRunCount(HibernateStringUtils.filterConstraintsQuery(this));
}
public String[] getFieldNames()
{
return filterVarNames_;
}
public IFilter[] getFilters()
{
return filters_;
}
public String[] getRowData(QueryDefinitionRun queryDefinitionRun)
{
String[] row = new String[4];
row[0] = queryDefinitionRun.getName();
row[1] = queryDefinitionRun.getQueryDefinition().getName();
row[2] = queryDefinitionRun.getQueryDefinition().getDescription();
row[3] = QueryDefinitionRunStatus.getQueryDefinitionRunStatus(queryDefinitionRun).toString();
return row;
}
public void init(Transaction t)
{
filters_[0] = new StringFilter();
filters_[1] = new StringFilter();
filters_[2] = new StringFilter();
filters_[3] = new StringFilter();
}
public boolean[] sortableFields()
{
return sortable_;
}
public int[] getColumnWidths() {
return colWidths;
}
public String[] getRowTooltips(QueryDefinitionRun type) {
return null;
}
}
| 33.634409 | 197 | 0.717711 |
ba600fb2bf08cfff810cfb09ec43351f44a6f15f | 420 | package com.stephenmac.incorporate.commands;
import com.stephenmac.incorporate.ArgParser;
import com.stephenmac.incorporate.Executor;
public class HelpCommand extends Command {
public HelpCommand(ArgParser p, Executor cmdExec) {
super(p, cmdExec);
needsCorp = false;
}
@Override
public String execute() {
return "Please see http://dev.bukkit.org/bukkit-plugins/incorporate/ for a list of commands.";
}
}
| 22.105263 | 96 | 0.764286 |
42a8db8b3d5864b73153c1028b0a2be8a415d109 | 3,905 |
package com.tw.go.task.sonarqualitygate;
import com.google.gson.GsonBuilder;
import com.thoughtworks.go.plugin.api.GoApplicationAccessor;
import com.thoughtworks.go.plugin.api.GoPluginIdentifier;
import com.thoughtworks.go.plugin.api.annotation.Extension;
import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest;
import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse;
import com.tw.go.plugin.common.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;;
@Extension
public class SonarScanTask extends BaseGoPlugin {
public static final String ISSUE_TYPE_FAIL = "IssueTypeFail";
public static final String SONAR_API_URL = "SonarApiUrl";
public static final String SONAR_PROJECT_KEY = "SonarProjectKey";
public static final String STAGE_NAME = "StageName";
public static final String JOB_NAME = "JobName";
public static final String JOB_COUNTER = "JobCounter";
@Override
public void initializeGoApplicationAccessor(GoApplicationAccessor goApplicationAccessor) {
// not required in most plugins
}
@Override
protected GoPluginApiResponse handleTaskView(GoPluginApiRequest request) {
return getViewResponse("SonarQube - Quality Gate",
getClass().getResourceAsStream("/views/task.template.html"));
}
@Override
protected GoPluginApiResponse handleGetConfigRequest(GoPluginApiRequest request) {
return success(getConfigDef());
}
@Override
protected GoPluginApiResponse handleValidation(GoPluginApiRequest request) {
HashMap result = new HashMap();
return success(result);
}
@Override
protected GoPluginApiResponse handleTaskExecution(GoPluginApiRequest request) {
Map executionRequest = (Map) new GsonBuilder().create().fromJson(request.requestBody(), Object.class);
Map<String, Map> config = (Map) executionRequest.get("config");
fixConfigAttrs(config,getConfigDef());
Context context = new Context((Map) executionRequest.get("context"));
Map<String, String> envVars = context.getEnvironmentVariables();
SonarTaskExecutor executor = new SonarTaskExecutor(
MaskingJobConsoleLogger.getConsoleLogger(), context, config);
// The RESPONSE_CODE MUST be 200 (SUCCESS) to be processed by Go.CD
// The outcome is defined by the property "success", and the cause can be stored in "message"
// See
// public <T> T submitRequest(String pluginId, String requestName, PluginInteractionCallback<T> pluginInteractionCallback) {
// in
// .../gocd/plugin-infra/go-plugin-access/src/com/thoughtworks/go/plugin/access/PluginRequestHelper.java
try {
Result result = executor.execute();
return success(result.toMap());
} catch (Exception e) {
Result result = new Result(false,e.getMessage());
return success(result.toMap());
}
}
private void fixConfigAttrs(Map<String, Map> configAct, Map<String, Map> configDef) {
for (Map.Entry<String,Map> e : configAct.entrySet()) {
Map def = configDef.get(e.getKey());
Map act = e.getValue();
act.put("required",def.get("required"));
act.put("secure",def.get("secure"));
}
}
private Map getConfigDef() {
return new ConfigDef()
.add(STAGE_NAME, "", Required.NO)
.add(JOB_NAME, "", Required.NO)
.add(JOB_COUNTER, "", Required.NO)
.add(SONAR_PROJECT_KEY, "", Required.YES)
.add(ISSUE_TYPE_FAIL, "error", Required.YES)
.add(SONAR_API_URL, "", Required.YES)
.toMap();
}
@Override
public GoPluginIdentifier pluginIdentifier() {
return new GoPluginIdentifier("task", Arrays.asList("1.0"));
}
} | 37.548077 | 133 | 0.673239 |
f8e46c9c7938cd128153ca8d23c66a7df83e2756 | 5,017 | /*
* UltraCart Rest API V2
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: [email protected]
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package com.ultracart.admin.v2.models;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.ultracart.admin.v2.models.PaymentsConfigurationRestrictions;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
/**
* PaymentsConfigurationMoneyOrder
*/
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2021-12-29T11:15:51.350-05:00")
public class PaymentsConfigurationMoneyOrder {
@SerializedName("accept_money_orders")
private Boolean acceptMoneyOrders = null;
@SerializedName("accounting_code")
private String accountingCode = null;
@SerializedName("deposit_to_account")
private String depositToAccount = null;
@SerializedName("restrictions")
private PaymentsConfigurationRestrictions restrictions = null;
public PaymentsConfigurationMoneyOrder acceptMoneyOrders(Boolean acceptMoneyOrders) {
this.acceptMoneyOrders = acceptMoneyOrders;
return this;
}
/**
* Master flag for this merchant accepting money orders
* @return acceptMoneyOrders
**/
@ApiModelProperty(value = "Master flag for this merchant accepting money orders")
public Boolean isAcceptMoneyOrders() {
return acceptMoneyOrders;
}
public void setAcceptMoneyOrders(Boolean acceptMoneyOrders) {
this.acceptMoneyOrders = acceptMoneyOrders;
}
public PaymentsConfigurationMoneyOrder accountingCode(String accountingCode) {
this.accountingCode = accountingCode;
return this;
}
/**
* Optional Quickbooks accounting code
* @return accountingCode
**/
@ApiModelProperty(value = "Optional Quickbooks accounting code")
public String getAccountingCode() {
return accountingCode;
}
public void setAccountingCode(String accountingCode) {
this.accountingCode = accountingCode;
}
public PaymentsConfigurationMoneyOrder depositToAccount(String depositToAccount) {
this.depositToAccount = depositToAccount;
return this;
}
/**
* Optional Quickbooks deposit to account
* @return depositToAccount
**/
@ApiModelProperty(value = "Optional Quickbooks deposit to account")
public String getDepositToAccount() {
return depositToAccount;
}
public void setDepositToAccount(String depositToAccount) {
this.depositToAccount = depositToAccount;
}
public PaymentsConfigurationMoneyOrder restrictions(PaymentsConfigurationRestrictions restrictions) {
this.restrictions = restrictions;
return this;
}
/**
* Get restrictions
* @return restrictions
**/
@ApiModelProperty(value = "")
public PaymentsConfigurationRestrictions getRestrictions() {
return restrictions;
}
public void setRestrictions(PaymentsConfigurationRestrictions restrictions) {
this.restrictions = restrictions;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PaymentsConfigurationMoneyOrder paymentsConfigurationMoneyOrder = (PaymentsConfigurationMoneyOrder) o;
return Objects.equals(this.acceptMoneyOrders, paymentsConfigurationMoneyOrder.acceptMoneyOrders) &&
Objects.equals(this.accountingCode, paymentsConfigurationMoneyOrder.accountingCode) &&
Objects.equals(this.depositToAccount, paymentsConfigurationMoneyOrder.depositToAccount) &&
Objects.equals(this.restrictions, paymentsConfigurationMoneyOrder.restrictions);
}
@Override
public int hashCode() {
return Objects.hash(acceptMoneyOrders, accountingCode, depositToAccount, restrictions);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PaymentsConfigurationMoneyOrder {\n");
sb.append(" acceptMoneyOrders: ").append(toIndentedString(acceptMoneyOrders)).append("\n");
sb.append(" accountingCode: ").append(toIndentedString(accountingCode)).append("\n");
sb.append(" depositToAccount: ").append(toIndentedString(depositToAccount)).append("\n");
sb.append(" restrictions: ").append(toIndentedString(restrictions)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 29.863095 | 125 | 0.741878 |
6f105dc844cc95338e4593830046b9c5b3660d67 | 2,748 | /*
* Weblounge: Web Content Management System
* Copyright (c) 2003 - 2011 The Weblounge Team
* http://entwinemedia.com/weblounge
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package ch.entwine.weblounge.common.content;
/**
* A <code>RendererException</code> is thrown if an exceptional state is reached
* when executing a <code>Renderer</code> to create the output for either a page
* or a single page name.
*/
public class RenderException extends RuntimeException {
/** The serial version id */
private static final long serialVersionUID = -857423335304601456L;
/** Renderer name, e. g. <code>XSLRenderer</code> */
protected Renderer renderer = null;
/**
* Creates a new <code>RendererException</code> that has been thrown by the
* specified renderer.
*
* @param renderer
* the renderer
*/
public RenderException(Renderer renderer) {
this.renderer = renderer;
}
/**
* Creates a new <code>RendererException</code> that has been thrown by the
* specified renderer.
*
* @param renderer
* the renderer
* @param t
* the exception caught when executing the renderer
*/
public RenderException(Renderer renderer, Throwable t) {
super(t);
this.renderer = renderer;
}
/**
* Creates a new <code>RendererException</code> that has been thrown by the
* specified renderer.
*
* @param renderer
* the renderer
* @param message
* the error message
*/
public RenderException(Renderer renderer, String message) {
super(message);
this.renderer = renderer;
}
/**
* Returns the renderer that raised this exception.
*
* @return the renderer
*/
public Renderer getRenderer() {
return renderer;
}
/**
* Returns the exception detail message.
*
* @see java.lang.Throwable#getMessage()
*/
public String getMessage() {
if (getCause() != null) {
return getCause().getMessage();
} else {
return super.getMessage();
}
}
} | 28.040816 | 80 | 0.673581 |
d789660a6171df90558f076cf8011ecb32fbf163 | 265 | package com.infosys.json;
import org.junit.Test;
import junit.framework.Assert;
public class InformaticaTest {
@Test
public void test() {
Informatica i = new Informatica();
i.setInfoObject(null);
Assert.assertEquals(null, i.getInfoObject());
}
}
| 14.722222 | 47 | 0.713208 |
b0544a89800607082c5d232bcb66803ebb6d932f | 1,130 | package com.samaranavi.egorpetruchcho.ui;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import com.samaranavi.egorpetruchcho.samaranavi.R;
import org.osmdroid.DefaultResourceProxyImpl;
public class CustomResourceProxy extends DefaultResourceProxyImpl {
private final Context context;
public CustomResourceProxy(Context context) {
super(context);
this.context = context;
}
@Override
public Bitmap getBitmap(bitmap resId) {
// switch (resId) {
// case person:
// return BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_person_pin_circle_black_48dp);
// }
return super.getBitmap(resId);
}
@Override
public Drawable getDrawable(bitmap resId) {
// switch (resId) {
// case person:
// return ContextCompat.getDrawable(context, R.drawable.ic_person_pin_circle_black_48dp);
// }
return super.getDrawable(resId);
}
} | 28.974359 | 122 | 0.7 |
b9b2074ac40a568b6c151d190f2e91f8446281f4 | 536 | package observer3;
import java.awt.*;
public class RedBall extends Ball {
public RedBall(MainPanel panel, int xSpeed, int ySpeed, int ballSize) {
super(panel, Color.RED, xSpeed, ySpeed, ballSize);
}
@Override
public void update(char keyChar) {
if (keyChar == 'a' || keyChar == 'd') {
int temp = getXSpeed();
setXSpeed(getYSpeed());
setYSpeed(temp);
}
}
public void update(GreenBall ball) {
escapeIsShamefulButUseful(ball, 100, 50);
}
}
| 23.304348 | 75 | 0.587687 |
9afb1b1476569e374ceb01613914656ff432d3cf | 9,302 | /*
* 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 io.tilt.minka.core.follower.impl;
import static java.util.Objects.requireNonNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.tilt.minka.api.Config;
import io.tilt.minka.core.follower.HeartbeatFactory;
import io.tilt.minka.core.leader.distributor.ChangeFeature;
import io.tilt.minka.core.task.LeaderAware;
import io.tilt.minka.domain.CommitTree.Log;
import io.tilt.minka.domain.DependencyPlaceholder;
import io.tilt.minka.domain.EntityEvent;
import io.tilt.minka.domain.EntityRecord;
import io.tilt.minka.domain.EntityState;
import io.tilt.minka.domain.Heartbeat;
import io.tilt.minka.domain.ShardEntity;
import io.tilt.minka.domain.ShardEntity.Builder;
import io.tilt.minka.domain.ShardedPartition;
import io.tilt.minka.shard.DomainInfo;
import io.tilt.minka.shard.NetworkShardIdentifier;
import io.tilt.minka.shard.ShardCapacity;
import io.tilt.minka.shard.ShardIdentifier;
import io.tilt.minka.utils.LogUtils;
/**
* It keeps sending heartbeats to the leader as long as is alive
*
* @author Cristian Gonzalez
* @since Nov 17, 2015
*/
class HeartbeatFactoryImpl implements HeartbeatFactory {
private final Logger log = LoggerFactory.getLogger(getClass());
private final String classname = getClass().getSimpleName();
private final DependencyPlaceholder dependencyPlaceholder;
private final ShardedPartition partition;
private final AtomicLong sequence;
private final LeaderAware leaderAware;
private final long includeFrequency;
private DomainInfo domain;
private long includeTimestamp;
private boolean logBeat;
private ShardIdentifier lastLeader;
HeartbeatFactoryImpl(
final Config config,
final DependencyPlaceholder holder,
final ShardedPartition partition,
final LeaderAware leaderAware) {
super();
this.dependencyPlaceholder = requireNonNull(holder);
this.partition = requireNonNull(partition);
this.sequence = new AtomicLong();
this.leaderAware = requireNonNull(leaderAware);
this.includeFrequency = config.beatToMs(50);
}
@Override
public Heartbeat create(final boolean forceFullReport, final ChangeFeature f) {
final long now = System.currentTimeMillis();
boolean newLeader = theresNewLeader(now);
logBeat |=newLeader;
// this's used only if there's nothing important to report (differences, absences, etc)
final Heartbeat.Builder builder = Heartbeat.builder(sequence.getAndIncrement(), partition.getId());
builder.feature(f);
// add reported: as confirmed if previously assigned, dangling otherwise.
final List<EntityRecord> tmp = new ArrayList<>(partition.getDuties().size());
boolean issues = detectChangesOnReport(builder, tmp::add, newLeader);
logBeat |=issues;
if (reportCapture(forceFullReport, now, newLeader, issues)) {
tmp.forEach(builder::addCaptured);
builder.reportsCapture();
includeTimestamp = now;
}
addReportedCapacities(builder);
final Heartbeat hb = builder.build();
logging(hb);
return hb;
}
private void logging(final Heartbeat hb) {
if (log.isDebugEnabled()) {
logDebugNicely(hb);
} else if (log.isInfoEnabled() && logBeat) {
logBeat = false;
log.info("{}: ({}) {} SeqID: {}, {}",
getClass().getSimpleName(), hb.getShardId(), LogUtils.HB_CHAR, hb.getSequenceId(),
hb.reportsDuties() ? new StringBuilder("Duties: (")
.append(EntityRecord.toStringIds(hb.getCaptured()))
.append(")").toString() : "");
}
}
private boolean reportCapture(final boolean force, final long now, boolean newLeader, boolean issues) {
final boolean exclusionExpired = includeTimestamp == 0
|| (now - includeTimestamp) > includeFrequency;
return force
|| issues
|| exclusionExpired
|| partition.wasRecentlyUpdated()
|| newLeader;
}
private boolean theresNewLeader(final long now) {
boolean newLeader = false;
final NetworkShardIdentifier leader = leaderAware.getLeaderShardId();
if (leader!=null && !leader.equals(lastLeader)) {
this.lastLeader = leader;
newLeader = true;
// put last inc. timestamp older so exclusion expires and full report beats follows
includeTimestamp = (now - includeFrequency) + 1;
}
return newLeader;
}
/* analyze reported duties and return if there're issues */
private boolean detectChangesOnReport(
final Heartbeat.Builder builder,
final Consumer<EntityRecord> c,
final boolean newLeader) {
boolean includeDuties = false;
Map<EntityEvent, StringBuilder> tmp = new HashMap<>(2);
for (ShardEntity shardedDuty: partition.getDuties()) {
includeDuties |= detectReception(shardedDuty, tmp);
c.accept(EntityRecord.fromEntity(shardedDuty, newLeader));
}
includeDuties |= treatReplicas(c, newLeader, tmp);
if (!tmp.isEmpty() && log.isInfoEnabled()) {
tmp.forEach((k,v)-> log.info(v.toString()));
}
return includeDuties;
}
private boolean treatReplicas(
final Consumer<EntityRecord> c,
final boolean newLeader,
final Map<EntityEvent, StringBuilder> tmp) {
Map<String, ShardEntity> palletsById = null;
if (newLeader && domain!=null) {
palletsById = toMap(domain.getDomainPallets());
}
boolean include = false;
for (ShardEntity duty: partition.getReplicas()) {
// new leader or not it must be comitted
include |= detectReception(duty, tmp);
// replicas must be reported when new leader or when simply comitting
if (newLeader || include) {
if (palletsById!=null && duty.getRelatedEntity()==null) {
// send with pallets for replication restore after leader reelection
final ShardEntity pallet = palletsById.get(duty.getDuty().getPalletId());
if (pallet!=null) {
final Builder bldr = ShardEntity.Builder.builderFrom(duty);
bldr.withRelatedEntity(pallet);
duty = bldr.build();
}
}
c.accept(EntityRecord.fromEntity(duty, true));
}
}
return include;
}
private Map<String, ShardEntity> toMap(Collection<ShardEntity> domainPallets) {
final Map<String, ShardEntity> ret = new HashMap<>();
for (ShardEntity pallet: domainPallets) {
ret.put(pallet.getPallet().getId(), pallet);
}
return ret;
}
/** this confirms action to the leader */
private boolean detectReception(final ShardEntity duty, final Map<EntityEvent, StringBuilder> tmp) {
// consider only the last action logged to this shard
for (final Log found : duty.getCommitTree().findAll(partition.getId())) {
final EntityState stamp = EntityState.COMMITED;
if (found.getLastState()!=stamp) {
if (log.isInfoEnabled()) {
StringBuilder sb = tmp.get(found.getEvent());
if (sb==null) {
sb= new StringBuilder(String.format("%s: (%s) Changing %s %s to %s duties: ",
classname, partition.getId(), found.getEvent(), found.getLastState(), stamp));
tmp.put(found.getEvent(), sb);
}
sb.append(duty.getDuty().getId()).append(',');
}
duty.getCommitTree().addEvent(
found.getEvent(),
stamp,
partition.getId(),
found.getPlanId());
return true;
}
}
return false;
}
private void addReportedCapacities(final Heartbeat.Builder builder) {
if (domain!=null && domain.getDomainPallets()!=null) {
for (ShardEntity pallet: domain.getDomainPallets()) {
double capacity = 0;
try {
capacity = dependencyPlaceholder.getDelegate().getTotalCapacity(pallet.getPallet());
} catch (Exception e) {
log.error("{}: ({}) Error ocurred while asking for total capacity on Pallet: {}", classname,
partition.getId(), pallet.getPallet(), e);
} finally {
builder.addCapacity(pallet.getPallet(), new ShardCapacity(pallet.getPallet(), capacity));
}
}
}
}
private void logDebugNicely(final Heartbeat hb) {
if (!log.isDebugEnabled()) {
return;
}
final StringBuilder sb = new StringBuilder();
List<EntityRecord> sorted = hb.getCaptured();
if (!sorted.isEmpty()) {
sorted.sort(sorted.get(0));
}
log.debug("{}: ({}) {} SeqID: {}, Duties: {} = [ {}] {}", classname,
hb.getShardId(),
LogUtils.HB_CHAR,
hb.getSequenceId(),
hb.getCaptured().size(),
EntityRecord.toStringIds(hb.getCaptured()),
hb.getCaptured().isEmpty() ? "" : "reportDuties"
);
}
@Override
public void setDomainInfo(final DomainInfo domain) {
this.domain = domain;
}
}
| 33.825455 | 104 | 0.716728 |
2d4e87d5a73a2d2c60326feb1117c54374729792 | 2,927 | package com.auto.applet.violation.model;
import java.util.Date;
import javax.validation.constraints.NotNull;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.CompoundIndexes;
import org.springframework.data.mongodb.core.mapping.Document;
/**
* 违章小程序-用户车辆关系表
* cSideUserId和carId将作为复合索引,数字参数指定索引的方向,1为正序,-1为倒序。方向对单键索引和随机存不要紧,但如果你要执行分组和排序操作的时候,它就非常重要了。
*
* @author li_xiaodong
* @date 2018年7月21日
*/
@Document(collection = "violation-applet-userCarMapping")
@CompoundIndexes({ @CompoundIndex(name = "userId_carId_idx", def = "{'cSideUserId': 1, 'carId': 1}") })
public class UserCar {
/**
* 注解属性id为ID--主键,不可重复,自带索引,可以在定义的列名上标注,需要自己生成并维护不重复的约束
*/
@Id
private String id;
/**
* C端用户标识
*/
private String cSideUserId;
/**
* 车辆主键Id
*/
private String carId;
/**
* 预约违章短信提醒(0默认不开通、1开通)
*/
@NotNull
private Integer openSmsRemind = 0;
/**
* 用户最近一次查询违章的时间(一键查询+列表)
*/
private Date gmtLatelyQuery;
@NotNull
private Date gmtModified = new Date();
@NotNull
private Date gmtCreate = new Date();
@NotNull
private Integer isDeleted = 0;
public UserCar() {
}
public UserCar(String cSideUserId, String carId) {
this.cSideUserId = cSideUserId;
this.carId = carId;
this.openSmsRemind = 0;
}
public UserCar(String cSideUserId, String carId, Integer openSmsRemind) {
this.cSideUserId = cSideUserId;
this.carId = carId;
this.openSmsRemind = openSmsRemind;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getcSideUserId() {
return cSideUserId;
}
public void setcSideUserId(String cSideUserId) {
this.cSideUserId = cSideUserId;
}
public String getCarId() {
return carId;
}
public void setCarId(String carId) {
this.carId = carId;
}
public Integer getOpenSmsRemind() {
return openSmsRemind;
}
public void setOpenSmsRemind(Integer openSmsRemind) {
this.openSmsRemind = openSmsRemind;
}
public Date getGmtLatelyQuery() {
return gmtLatelyQuery;
}
public void setGmtLatelyQuery(Date gmtLatelyQuery) {
this.gmtLatelyQuery = gmtLatelyQuery;
}
public Date getGmtModified() {
return gmtModified;
}
public void setGmtModified(Date gmtModified) {
this.gmtModified = gmtModified;
}
public Date getGmtCreate() {
return gmtCreate;
}
public void setGmtCreate(Date gmtCreate) {
this.gmtCreate = gmtCreate;
}
public Integer getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(Integer isDeleted) {
this.isDeleted = isDeleted;
}
@Override
public String toString() {
return "UserCar [id=" + id + ", cSideUserId=" + cSideUserId + ", carId=" + carId + ", openSmsRemind="
+ openSmsRemind + ", gmtLatelyQuery=" + gmtLatelyQuery + ", gmtModified=" + gmtModified + ", gmtCreate="
+ gmtCreate + ", isDeleted=" + isDeleted + "]";
}
}
| 19.911565 | 108 | 0.714725 |
3fe3f75d63e0dcfcb992496207b6cec34d3b5bf3 | 8,897 | /* */ package edu.drexel.cis.dragon.qa.system;
/* */
/* */ import edu.drexel.cis.dragon.matrix.DoubleFlatSparseMatrix;
/* */ import edu.drexel.cis.dragon.matrix.IntFlatSparseMatrix;
/* */ import edu.drexel.cis.dragon.nlp.Document;
/* */ import edu.drexel.cis.dragon.nlp.DocumentParser;
/* */ import edu.drexel.cis.dragon.nlp.Paragraph;
/* */ import edu.drexel.cis.dragon.nlp.Sentence;
/* */ import edu.drexel.cis.dragon.nlp.Word;
/* */ import edu.drexel.cis.dragon.onlinedb.Article;
/* */ import edu.drexel.cis.dragon.onlinedb.CollectionReader;
/* */ import edu.drexel.cis.dragon.qa.query.QuestionQuery;
/* */ import edu.drexel.cis.dragon.util.MathUtil;
/* */ import java.util.ArrayList;
/* */
/* */ public class CandidateBase
/* */ {
/* */ private DoubleFlatSparseMatrix cansentMatrix;
/* */ private IntFlatSparseMatrix querysentMatrix;
/* */ private ArrayList docList;
/* */ private ArrayList sentList;
/* */ private ArrayList docKeyList;
/* */ private int totalCount;
/* */ private int[] arrQueryCount;
/* */ private int sentFiltered;
/* */
/* */ public CandidateBase(QuestionQuery query, DocumentParser parser, CollectionReader reader)
/* */ {
/* 18 */ this(query, parser, reader, 2147483647);
/* */ }
/* */
/* */ public CandidateBase(QuestionQuery query, DocumentParser parser, CollectionReader reader, int top)
/* */ {
/* 30 */ this.sentFiltered = 0;
/* 31 */ this.totalCount = 0;
/* 32 */ this.docList = new ArrayList();
/* 33 */ this.docKeyList = new ArrayList();
/* 34 */ this.arrQueryCount = new int[query.size()];
/* */ Article article;
/* 36 */ while (((article = reader.getNextArticle()) != null) && (this.docList.size() < top))
/* */ {
/* 37 */ StringBuffer buf = new StringBuffer();
/* 38 */ if (article.getTitle() != null) {
/* 39 */ buf.append(article.getTitle());
/* 40 */ buf.append("\n\n");
/* */ }
/* 42 */ if (article.getAbstract() != null) {
/* 43 */ buf.append(article.getAbstract());
/* 44 */ buf.append("\n\n");
/* */ }
/* 46 */ if (article.getBody() != null) {
/* 47 */ buf.append(article.getBody());
/* */ }
/* 49 */ String content = buf.toString();
/* 50 */ content = content.replaceAll("\\.\\.\\.", "\n\n");
/* 51 */ content = content.replaceAll("�", " - ");
/* 52 */ Document doc = parser.parse(content);
/* 53 */ if (doc != null) {
/* 54 */ this.docList.add(doc);
/* 55 */ this.docKeyList.add(article.getKey());
/* */ }
/* */ }
/* */
/* 59 */ this.sentList = new ArrayList();
/* 60 */ int sentNum = 0;
/* 61 */ for (int i = 0; i < this.docList.size(); i++) {
/* 62 */ Document doc = getDocument(i);
/* 63 */ doc.setIndex(i);
/* 64 */ Paragraph para = doc.getFirstParagraph();
/* 65 */ while (para != null) {
/* 66 */ mergeShortSentence(para);
/* 67 */ Sentence sent = para.getFirstSentence();
/* 68 */ while (sent != null) {
/* 69 */ if (sent.getWordNum() > 2) {
/* 70 */ sent.setIndex(sentNum);
/* 71 */ sentNum++;
/* 72 */ this.sentList.add(sent);
/* */ }
/* 74 */ sent = sent.next;
/* */ }
/* 76 */ para = para.next;
/* */ }
/* */ }
/* */
/* 80 */ this.cansentMatrix = new DoubleFlatSparseMatrix();
/* 81 */ this.querysentMatrix = new IntFlatSparseMatrix();
/* */ }
/* */
/* */ public int getCollectionCount() {
/* 85 */ return this.totalCount;
/* */ }
/* */
/* */ public void addCollectionCount(int inc) {
/* 89 */ this.totalCount += inc;
/* */ }
/* */
/* */ public int getSentenceFiltered() {
/* 93 */ return this.sentFiltered;
/* */ }
/* */
/* */ public void addSentenceFiltered(int inc) {
/* 97 */ this.sentFiltered += inc;
/* */ }
/* */
/* */ public int getQueryWordCount(int queryWordIndex) {
/* 101 */ return this.arrQueryCount[queryWordIndex];
/* */ }
/* */
/* */ public void reset() {
/* 105 */ this.totalCount = 0;
/* 106 */ this.sentFiltered = 0;
/* 107 */ MathUtil.initArray(this.arrQueryCount, 0);
/* 108 */ if (this.cansentMatrix != null)
/* 109 */ this.cansentMatrix.close();
/* 110 */ this.cansentMatrix = new DoubleFlatSparseMatrix();
/* 111 */ if (this.querysentMatrix != null)
/* 112 */ this.querysentMatrix.close();
/* 113 */ this.querysentMatrix = new IntFlatSparseMatrix();
/* */ }
/* */
/* */ public void finalize() {
/* 117 */ if (this.cansentMatrix != null)
/* 118 */ this.cansentMatrix.finalizeData();
/* 119 */ if (this.querysentMatrix != null)
/* 120 */ this.querysentMatrix.finalizeData();
/* */ }
/* */
/* */ public void close() {
/* 124 */ if (this.sentList != null)
/* 125 */ this.sentList.clear();
/* 126 */ if (this.docList != null)
/* 127 */ this.docList.clear();
/* 128 */ if (this.docKeyList != null)
/* 129 */ this.docKeyList.clear();
/* 130 */ if (this.cansentMatrix != null)
/* 131 */ this.cansentMatrix.close();
/* 132 */ if (this.querysentMatrix != null)
/* 133 */ this.querysentMatrix.close();
/* */ }
/* */
/* */ public boolean addQueryWord(int wordIndex, int sentIndex, int freq) {
/* 137 */ this.arrQueryCount[wordIndex] += freq;
/* 138 */ return this.querysentMatrix.add(wordIndex, sentIndex, freq);
/* */ }
/* */
/* */ public int[] getQuerySentences(int queryIndex) {
/* 142 */ return this.querysentMatrix.getNonZeroColumnsInRow(queryIndex);
/* */ }
/* */
/* */ public int[] getQueryCounts(int queryIndex) {
/* 146 */ return this.querysentMatrix.getNonZeroIntScoresInRow(queryIndex);
/* */ }
/* */
/* */ public boolean add(int candIndex, int sentIndex, double weight) {
/* 150 */ return this.cansentMatrix.add(candIndex, sentIndex, weight);
/* */ }
/* */
/* */ public int[] getCandidateSentences(int candIndex) {
/* 154 */ return this.cansentMatrix.getNonZeroColumnsInRow(candIndex);
/* */ }
/* */
/* */ public double[] getCandidateScores(int candIndex) {
/* 158 */ return this.cansentMatrix.getNonZeroDoubleScoresInRow(candIndex);
/* */ }
/* */
/* */ public int getDocumentNum() {
/* 162 */ return this.docList.size();
/* */ }
/* */
/* */ public Document getDocument(int index) {
/* 166 */ return (Document)this.docList.get(index);
/* */ }
/* */
/* */ public String getDocumentURL(int index) {
/* 170 */ return (String)this.docKeyList.get(index);
/* */ }
/* */
/* */ public int getSentenceNum() {
/* 174 */ return this.sentList.size();
/* */ }
/* */
/* */ public Sentence getSentence(int index) {
/* 178 */ return (Sentence)this.sentList.get(index);
/* */ }
/* */
/* */ protected void mergeShortSentence(Paragraph para)
/* */ {
/* 186 */ boolean needMerge = false;
/* 187 */ Sentence prev = null;
/* 188 */ Sentence cur = para.getFirstSentence();
/* 189 */ while (cur != null)
/* 190 */ if (cur.getWordNum() == 0) {
/* 191 */ cur = cur.next;
/* */ }
/* */ else
/* */ {
/* 195 */ if (needMerge) {
/* 196 */ Word curWord = new Word(";");
/* 197 */ curWord.setType(4);
/* 198 */ prev.getLastWord().next = curWord;
/* 199 */ curWord.prev = prev.getLastWord();
/* 200 */ curWord.next = cur.getFirstWord();
/* 201 */ cur.getFirstWord().prev = curWord;
/* 202 */ prev.setPunctuation(cur.getPunctuation());
/* 203 */ prev.resetBoundary(prev.getFirstWord(), cur.getLastWord());
/* 204 */ prev.next = cur.next;
/* */ }
/* */ else {
/* 207 */ prev = cur;
/* */ }
/* */
/* 210 */ needMerge = false;
/* 211 */ if (((cur.getPunctuation() == '.') || (cur.getPunctuation() == ';')) && (cur.getWordNum() < 6))
/* 212 */ needMerge = true;
/* 213 */ cur = cur.next;
/* */ }
/* */ }
/* */ }
/* Location: C:\dragontoolikt\dragontool.jar
* Qualified Name: dragon.qa.system.CandidateBase
* JD-Core Version: 0.6.2
*/ | 39.896861 | 114 | 0.505564 |
677b3d4e22d3a83fb7a76df7c677c06218861ec7 | 36,675 | /*
* Copyright (c) Australian Institute of Marine Science, 2021.
* @author Gael Lafond <[email protected]>
*/
package au.gov.aims.ncanimate;
import au.gov.aims.aws.s3.entity.S3Client;
import au.gov.aims.ereefs.Utils;
import au.gov.aims.ereefs.bean.metadata.TimeIncrement;
import au.gov.aims.ereefs.bean.metadata.netcdf.NetCDFMetadataBean;
import au.gov.aims.ereefs.bean.ncanimate.NcAnimateConfigBean;
import au.gov.aims.ereefs.bean.ncanimate.NcAnimateRegionBean;
import au.gov.aims.ereefs.bean.ncanimate.render.AbstractNcAnimateRenderFileBean;
import au.gov.aims.ereefs.bean.ncanimate.render.NcAnimateRenderMapBean;
import au.gov.aims.ereefs.bean.ncanimate.render.NcAnimateRenderVideoBean;
import au.gov.aims.ereefs.bean.task.TaskBean;
import au.gov.aims.ereefs.database.CacheStrategy;
import au.gov.aims.ereefs.database.DatabaseClient;
import au.gov.aims.ereefs.helper.NcAnimateConfigHelper;
import au.gov.aims.ereefs.helper.TaskHelper;
import au.gov.aims.ncanimate.commons.NcAnimateGenerateFileBean;
import au.gov.aims.ncanimate.commons.NcAnimateUtils;
import au.gov.aims.ncanimate.commons.generator.context.GeneratorContext;
import au.gov.aims.ncanimate.commons.timetable.DateTimeRange;
import au.gov.aims.ncanimate.commons.timetable.FrameTimetable;
import au.gov.aims.ncanimate.commons.timetable.FrameTimetableMap;
import au.gov.aims.ncanimate.commons.timetable.NetCDFMetadataFrame;
import au.gov.aims.ncanimate.commons.timetable.NetCDFMetadataSet;
import au.gov.aims.ncanimate.commons.timetable.ProductTimetable;
import au.gov.aims.ncanimate.generator.AbstractMediaGenerator;
import au.gov.aims.ncanimate.generator.FrameGenerator;
import au.gov.aims.ncanimate.generator.MapGenerator;
import au.gov.aims.ncanimate.generator.VideoGenerator;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
public class NcAnimate {
private static final Logger LOGGER = Logger.getLogger(NcAnimate.class);
private static final String TASKID_ENV_VARIABLE = "TASK_ID";
private static final String NCANIMATE_TASK_TYPE = "ncanimate";
private static final int LOG_OUTDATED_LIMIT = 3;
private DatabaseClient dbClient;
private FrameGenerator frameGenerator;
private S3Client s3Client;
private String regionId;
public static void main(String ... args) throws Exception {
String taskId = NcAnimate.getTaskId(args);
if ("__FIX_NCANIMATE_PRODUCT_METADATA_ID__".equals(taskId)) {
NcAnimateMetadataIdFixer.fixMetadataIds(
new DatabaseClient(NcAnimateUtils.APP_NAME), CacheStrategy.NONE);
return;
}
/* WARNING! This task will trigger a re-generation of all nc-aggregate tasks. */
if ("__FIX_DOWNLOAD_METADATA_ID__".equals(taskId)) {
NcAnimateMetadataIdFixer.fixDownloadMetadataIds(
new DatabaseClient(NcAnimateUtils.APP_NAME), CacheStrategy.NONE);
return;
}
if ("__FIX_METADATA_DUPLICATE_ID__".equals(taskId)) {
NcAnimateMetadataIdFixer.fixDuplicatedMetadataIds(
new DatabaseClient(NcAnimateUtils.APP_NAME), CacheStrategy.NONE);
return;
}
NcAnimate ncAnimate = new NcAnimate();
ncAnimate.generateFromTaskId(taskId);
}
public NcAnimate() {
this(new DatabaseClient(NcAnimateUtils.APP_NAME), NcAnimate.createS3Client());
}
private static S3Client createS3Client() {
try {
return new S3Client();
} catch(Exception ex) {
LOGGER.warn("Exception occurred while initialising the S3Client. Please ignore if encountered in unit tests.", ex);
return null;
}
}
public NcAnimate(DatabaseClient dbClient, S3Client s3Client) {
this.dbClient = dbClient;
this.s3Client = s3Client;
this.regionId = null;
this.frameGenerator = new FrameGenerator();
}
/**
* Set a custom service end point, for MongoDB.
* Used with unit tests.
*/
public void setCustomDatabaseServerAddress(String customDatabaseServerAddress, int customDatabaseServerPort) {
this.frameGenerator.setCustomDatabaseServerAddress(customDatabaseServerAddress, customDatabaseServerPort);
}
/**
* Set custom database name, for MongoDB.
* Used with unit tests.
*/
public void setCustomDatabaseName(String customDatabaseName) {
this.frameGenerator.setCustomDatabaseName(customDatabaseName);
}
/**
* Set the region ID
* @param regionId ID of the region to generate. Set to null to generate all regions.
*/
public void setRegionId(String regionId) {
this.frameGenerator.setRegionId(regionId);
this.regionId = regionId;
}
private static String getTaskId(String ... args) {
// Look for a task ID from parameters.
if (args != null && args.length > 0) {
return args[0];
}
// Get "TASK_ID" from environmental variables (used when ran on AWS infrastructure)
return System.getenv(TASKID_ENV_VARIABLE);
}
public TaskBean getTask(String taskId) throws Exception {
if (taskId != null) {
TaskHelper taskHelper = new TaskHelper(this.dbClient, CacheStrategy.DISK);
return taskHelper.getTask(taskId);
}
return null;
}
public void generateFromTaskId(String taskId) throws Exception {
LOGGER.info(String.format("Generate for task ID: %s", taskId));
NcAnimateUtils.printMemoryUsage("NcAnimate init");
long maxMemory = Runtime.getRuntime().maxMemory();
if (maxMemory == Long.MAX_VALUE) {
LOGGER.info(String.format("%n Max memory: UNLIMITED"));
} else {
LOGGER.info(String.format("%n Max memory: LIMITED TO %.2f MB", (maxMemory / (1024 * 1024.0))));
}
TaskBean task = this.getTask(taskId);
if (task != null) {
LOGGER.info(String.format("Task: %s", task));
String taskType = task.getType();
String regionId = task.getRegionId();
if (regionId != null && !regionId.isEmpty()) {
this.setRegionId(regionId);
} else {
this.setRegionId(null);
}
if (NCANIMATE_TASK_TYPE.equals(taskType)) {
String productId = task.getProductId();
if (productId != null && !productId.isEmpty()) {
this.generateFromProductId(productId);
} else {
throw new IllegalArgumentException(String.format("The task has no productDefinitionId. Task ID: %s", taskId));
}
} else {
throw new IllegalArgumentException(
String.format("Wrong task type. Expected \"%s\" Found \"%s\". Task ID: %s", NCANIMATE_TASK_TYPE, taskType, taskId));
}
} else {
throw new IllegalArgumentException(String.format("Task not found. Task ID: %s", taskId));
}
}
/**
* Generate frames for a product.
* NOTE: This method does not generate all frames blindly!
* 1. Loop through all products, find the one which are outdated
* 2. Build a list of frames which needs to be generated (don't care about outdated or missing frames, NcAnimate frame take care of that)
* 3. Merge all frame date ranges into large continuous date ranges (defragmentation of available dates from input data files)
* 4. Split the large continuous date ranges into date range of frames sharing the same input files
* 5. Generate the frames (using the grouping above)
* 6. Generate outdated products (videos and maps)
*
* @param productId ID of the NcAnimate configuration to generate.
* @throws Exception
*/
public void generateFromProductId(String productId) throws Exception {
LOGGER.info(String.format("Generate for product ID: %s", productId));
NcAnimateConfigHelper configHelper = new NcAnimateConfigHelper(this.dbClient, CacheStrategy.DISK);
NcAnimateConfigBean ncAnimateConfig = configHelper.getNcAnimateConfig(productId);
ProductTimetable productTimetable = new ProductTimetable(ncAnimateConfig, this.dbClient);
NcAnimateUtils.printMemoryUsage("NcAnimate ProductTimetable");
MapGenerator mapGenerator = new MapGenerator(ncAnimateConfig, productTimetable, this.s3Client, this.dbClient);
VideoGenerator videoGenerator = new VideoGenerator(ncAnimateConfig, productTimetable, this.s3Client, this.dbClient);
// Validate regions
Map<String, NcAnimateRegionBean> regionMap = ncAnimateConfig.getRegions();
if (regionMap == null || regionMap.isEmpty()) {
throw new IllegalStateException(String.format("Invalid NcAnimate configuration ID %s. The configuration contains no region.", productId));
}
if (this.regionId != null) {
NcAnimateRegionBean selectedRegion = regionMap.get(this.regionId);
if (selectedRegion == null) {
throw new IllegalStateException(String.format("Can not generate NcAnimate products for region ID %s, configuration ID %s. The region is invalid.", regionId, productId));
}
}
try {
LOGGER.info(String.format("Region ID: %s", (this.regionId == null ? "unset (generating for all regions)" : this.regionId)));
// Get all video frames and files
LOGGER.info("Generate list of outdated videos");
Map<DateTimeRange, List<FrameTimetableMap>> videoFrameMap = productTimetable.getVideoFrames();
List<NcAnimateGenerateFileBean> videoOutputFileBeans = productTimetable.getVideoOutputFiles();
// Filter outdated video files
List<NcAnimateGenerateFileBean> outdatedVideoOutputFileBeans = new ArrayList<NcAnimateGenerateFileBean>();
for (NcAnimateGenerateFileBean videoOutputFileBean : videoOutputFileBeans) {
if (NcAnimateUtils.isOutdated(this.s3Client, videoOutputFileBean, videoFrameMap, ncAnimateConfig, this.regionId, outdatedVideoOutputFileBeans.size() < LOG_OUTDATED_LIMIT)) {
outdatedVideoOutputFileBeans.add(videoOutputFileBean);
}
}
LOGGER.info(String.format("Found %d outdated videos", outdatedVideoOutputFileBeans.size()));
// Get all map frames and files
LOGGER.info("Generate list of outdated maps");
Map<DateTimeRange, List<FrameTimetableMap>> mapFrameMap = productTimetable.getMapFrames();
List<NcAnimateGenerateFileBean> mapOutputFileBeans = productTimetable.getMapOutputFiles();
// Filter outdated map files
List<NcAnimateGenerateFileBean> outdatedMapOutputFileBeans = new ArrayList<NcAnimateGenerateFileBean>();
for (NcAnimateGenerateFileBean mapOutputFileBean : mapOutputFileBeans) {
if (NcAnimateUtils.isOutdated(this.s3Client, mapOutputFileBean, mapFrameMap, ncAnimateConfig, this.regionId, outdatedMapOutputFileBeans.size() < LOG_OUTDATED_LIMIT)) {
outdatedMapOutputFileBeans.add(mapOutputFileBean);
}
}
LOGGER.info(String.format("Found %d outdated maps", outdatedMapOutputFileBeans.size()));
NcAnimateUtils.printMemoryUsage("NcAnimate outdated products");
if (!outdatedVideoOutputFileBeans.isEmpty() || !outdatedMapOutputFileBeans.isEmpty()) {
TimeIncrement frameTimeIncrement = ncAnimateConfig.getFrameTimeIncrement();
// Create a (very big) list of all the frame files that will be generated
LOGGER.info("Plan out how frame files needs to be generated");
Map<String, File> allFrameFiles = new HashMap<String, File>();
if (!outdatedVideoOutputFileBeans.isEmpty()) {
for (NcAnimateGenerateFileBean outdatedVideoOutdatedFileBean : outdatedVideoOutputFileBeans) {
allFrameFiles.putAll(this.getFrameFiles(ncAnimateConfig, outdatedVideoOutdatedFileBean, videoFrameMap, frameTimeIncrement));
}
}
if (!outdatedMapOutputFileBeans.isEmpty()) {
for (NcAnimateGenerateFileBean outdatedMapOutdatedFileBean : outdatedMapOutputFileBeans) {
allFrameFiles.putAll(this.getFrameFiles(ncAnimateConfig, outdatedMapOutdatedFileBean, mapFrameMap, frameTimeIncrement));
}
}
// Group all video and map frames into one big collection (since the process to generate video frame and map is the same)
Map<DateTimeRange, List<FrameTimetableMap>> allFrames = combineFrames(videoFrameMap, mapFrameMap);
NcAnimateUtils.printMemoryUsage("NcAnimate allFrames map");
// Create a list of all product date range that needs to be generated
List<DateTimeRange> unmergedDateRanges = new ArrayList<DateTimeRange>();
for (NcAnimateGenerateFileBean outdatedVideoOutputFileBean : outdatedVideoOutputFileBeans) {
unmergedDateRanges.add(outdatedVideoOutputFileBean.getDateRange());
}
for (NcAnimateGenerateFileBean outdatedMapOutputFileBean : outdatedMapOutputFileBeans) {
unmergedDateRanges.add(outdatedMapOutputFileBean.getDateRange());
}
if (!unmergedDateRanges.isEmpty()) {
// Merge product date range into long continuous date ranges (defragmentation)
SortedSet<DateTimeRange> mergedDateRanges = DateTimeRange.mergeDateRanges(unmergedDateRanges);
if (mergedDateRanges != null && !mergedDateRanges.isEmpty()) {
SortedSet<DateTimeRange> generatedDateRanges = new TreeSet<DateTimeRange>();
for (DateTimeRange mergedDateRange : mergedDateRanges) {
// Split the long continuous date range into smaller date range containing frames that use the same input files
Map<Set<String>, SortedSet<DateTimeRange>> groupedFrames = this.groupFrames(mergedDateRange, allFrames);
// Sort all date ranges in a single collection
SortedSet<DateTimeRange> sortedDateRanges = new TreeSet<DateTimeRange>();
for (SortedSet<DateTimeRange> fileGroupDateRange : groupedFrames.values()) {
sortedDateRanges.addAll(fileGroupDateRange);
}
if (!sortedDateRanges.isEmpty()) {
// Add missing frames, to generate "No data" frames where there is no data available
SortedSet<DateTimeRange> noGapSortedDateRanges = new TreeSet<DateTimeRange>();
DateTime lastEndDate = null;
for (DateTimeRange dateRange : sortedDateRanges) {
noGapSortedDateRanges.add(dateRange);
if (lastEndDate != null) {
if (lastEndDate.compareTo(dateRange.getStartDate()) < 0) {
DateTimeRange noDataDateRange = DateTimeRange.create(lastEndDate, dateRange.getStartDate());
noGapSortedDateRanges.add(noDataDateRange);
}
}
lastEndDate = dateRange.getEndDate();
}
// Add missing frames at the beginning
if (!DateTimeRange.ALL_TIME.equals(mergedDateRange)) {
DateTimeRange firstDateRange = sortedDateRanges.first();
if (mergedDateRange.getStartDate().compareTo(firstDateRange.getStartDate()) < 0) {
noGapSortedDateRanges.add(DateTimeRange.create(mergedDateRange.getStartDate(), firstDateRange.getStartDate()));
}
// Add missing frames at the end
DateTimeRange lastDateRange = sortedDateRanges.last();
if (mergedDateRange.getEndDate().compareTo(lastDateRange.getEndDate()) > 0) {
noGapSortedDateRanges.add(DateTimeRange.create(lastDateRange.getEndDate(), mergedDateRange.getEndDate()));
}
}
for (DateTimeRange dateRange : noGapSortedDateRanges) {
LOGGER.info(String.format("Generate frame files for date range [%s - %s]", dateRange.getStartDate(), dateRange.getEndDate()));
NcAnimateUtils.printMemoryUsage("NcAnimate before generateFrames");
// Generate video frames & map frames per group of dates that share the same input files
this.frameGenerator.generateFrames(ncAnimateConfig, dateRange);
NcAnimateUtils.printMemoryUsage("NcAnimate after generateFrames");
generatedDateRanges.add(dateRange);
generatedDateRanges = DateTimeRange.mergeDateRanges(generatedDateRanges);
// Generate maps and videos that can be generated with the frames we currently have
// Generate outdated videos
if (!outdatedVideoOutputFileBeans.isEmpty()) {
List<NcAnimateGenerateFileBean> newOutdatedVideoOutputFiles = new ArrayList<NcAnimateGenerateFileBean>();
for (NcAnimateGenerateFileBean outdatedVideoOutputFileBean : outdatedVideoOutputFileBeans) {
DateTimeRange videoDateRange = outdatedVideoOutputFileBean.getDateRange();
if (this.isReady(generatedDateRanges, videoDateRange)) {
videoGenerator.generateVideo(outdatedVideoOutputFileBean, videoFrameMap, frameTimeIncrement, this.regionId);
} else {
newOutdatedVideoOutputFiles.add(outdatedVideoOutputFileBean);
}
}
outdatedVideoOutputFileBeans = newOutdatedVideoOutputFiles;
}
// Generate outdated maps
if (!outdatedMapOutputFileBeans.isEmpty()) {
List<NcAnimateGenerateFileBean> newOutdatedMapOutputFiles = new ArrayList<NcAnimateGenerateFileBean>();
for (NcAnimateGenerateFileBean outdatedMapOutputFileBean : outdatedMapOutputFileBeans) {
DateTimeRange mapDateRange = outdatedMapOutputFileBean.getDateRange();
if (this.isReady(generatedDateRanges, mapDateRange)) {
mapGenerator.generateMap(outdatedMapOutputFileBean, mapFrameMap, frameTimeIncrement, this.regionId);
} else {
newOutdatedMapOutputFiles.add(outdatedMapOutputFileBean);
}
}
outdatedMapOutputFileBeans = newOutdatedMapOutputFiles;
}
// Delete generated frame files that are not needed anymore to generate other products (video or map)
this.cleanupFrames(
ncAnimateConfig,
videoFrameMap,
frameTimeIncrement,
mapFrameMap,
frameTimeIncrement,
outdatedVideoOutputFileBeans,
outdatedMapOutputFileBeans,
allFrameFiles);
}
}
}
}
}
}
LOGGER.info("--------------------------------------------------");
LOGGER.info("---------------- End of NcAnimate ----------------");
LOGGER.info("--------------------------------------------------");
if (!outdatedVideoOutputFileBeans.isEmpty()) {
LOGGER.error("Some videos could not be generated:");
for (NcAnimateGenerateFileBean outdatedVideoOutputFileBean : outdatedVideoOutputFileBeans) {
DateTimeRange dateRange = outdatedVideoOutputFileBean.getDateRange();
LOGGER.error(String.format(" - %s (%s - %s)",
outdatedVideoOutputFileBean.getFileId(),
dateRange == null ? null : dateRange.getStartDate(),
dateRange == null ? null : dateRange.getEndDate()));
}
}
if (!outdatedMapOutputFileBeans.isEmpty()) {
LOGGER.error("Some maps could not be generated:");
for (NcAnimateGenerateFileBean outdatedMapOutputFileBean : outdatedMapOutputFileBeans) {
DateTimeRange dateRange = outdatedMapOutputFileBean.getDateRange();
LOGGER.error(String.format(" - %s (%s - %s)",
outdatedMapOutputFileBean.getFileId(),
dateRange == null ? null : dateRange.getStartDate(),
dateRange == null ? null : dateRange.getEndDate()));
}
}
if (!outdatedVideoOutputFileBeans.isEmpty() || !outdatedMapOutputFileBeans.isEmpty()) {
throw new IllegalStateException("Some output products could not be generated.");
}
} finally {
NcAnimateUtils.clearCache();
// Delete temporary working directory before exiting
File workingDirectory = ncAnimateConfig.getRender().getWorkingDirectoryFile();
if (workingDirectory.exists()) {
Utils.deleteDirectory(workingDirectory);
}
}
}
/**
* Check if a product (video or map) has all the frame files needed to generate it.
* @param generatedDateRanges
* @param productDateRange
* @return
*/
private boolean isReady(SortedSet<DateTimeRange> generatedDateRanges, DateTimeRange productDateRange) {
for (DateTimeRange generatedDateRange : generatedDateRanges) {
if (generatedDateRange.contains(productDateRange)) {
return true;
}
}
return false;
}
/**
* Delete generated frames files that are no longer needed.
* NOTE: This method needs to be called after the generation of maps / videos.
* NcAnimate frame generate many GB of frames. If those frames stay on disk
* until the end, on a long generation, the server may run out of disk space.
* @param ncAnimateConfig
* @param videoFrameMap
* @param videoFrameTimeIncrement
* @param mapFrameMap
* @param mapFrameTimeIncrement
* @param remainingVideoOutdatedFileBeans
* @param remainingMapOutdatedFileBeans
* @param allFrameFiles
*/
private void cleanupFrames(
NcAnimateConfigBean ncAnimateConfig,
Map<DateTimeRange, List<FrameTimetableMap>> videoFrameMap,
TimeIncrement videoFrameTimeIncrement,
Map<DateTimeRange, List<FrameTimetableMap>> mapFrameMap,
TimeIncrement mapFrameTimeIncrement,
List<NcAnimateGenerateFileBean> remainingVideoOutdatedFileBeans,
List<NcAnimateGenerateFileBean> remainingMapOutdatedFileBeans,
Map<String, File> allFrameFiles) {
LOGGER.info("Cleanup old frame files");
// Create a (very big) list of all the frame files needed for the remaining products (maps & videos) to create
Map<String, File> frameFileNeeded = new HashMap<String, File>();
if (remainingVideoOutdatedFileBeans != null && !remainingVideoOutdatedFileBeans.isEmpty()) {
for (NcAnimateGenerateFileBean remainingVideoOutdatedFileBean : remainingVideoOutdatedFileBeans) {
frameFileNeeded.putAll(this.getFrameFiles(ncAnimateConfig, remainingVideoOutdatedFileBean, videoFrameMap, videoFrameTimeIncrement));
}
}
if (remainingMapOutdatedFileBeans != null && !remainingMapOutdatedFileBeans.isEmpty()) {
for (NcAnimateGenerateFileBean remainingMapOutdatedFileBean : remainingMapOutdatedFileBeans) {
frameFileNeeded.putAll(this.getFrameFiles(ncAnimateConfig, remainingMapOutdatedFileBean, mapFrameMap, mapFrameTimeIncrement));
}
}
// Loop through all frame files and delete the one which are not required anymore
Set<File> deletedFiles = new TreeSet<File>();
if (allFrameFiles != null && !allFrameFiles.isEmpty()) {
for (Map.Entry<String, File> allFrameFileEntry : allFrameFiles.entrySet()) {
if (!frameFileNeeded.containsKey(allFrameFileEntry.getKey())) {
File unneededFrameFile = allFrameFileEntry.getValue();
if (unneededFrameFile != null && unneededFrameFile.exists()) {
if (!unneededFrameFile.delete()) {
LOGGER.warn(String.format("Could not delete old frame file: %s", unneededFrameFile));
} else {
deletedFiles.add(unneededFrameFile);
}
}
}
}
}
if (!deletedFiles.isEmpty()) {
LOGGER.info(String.format("Deleted %d old frame files", deletedFiles.size()));
// Only generate the following debug message is the LOGGER level is DEBUG or higher
if (LOGGER.isDebugEnabled()) {
StringBuilder debugMessage = new StringBuilder("Deleted old frame files:");
for (File deletedFile : deletedFiles) {
debugMessage.append(String.format("%n- %s", deletedFile));
}
LOGGER.debug(debugMessage);
}
}
}
private Map<String, File> getFrameFiles(
NcAnimateConfigBean ncAnimateConfig,
NcAnimateGenerateFileBean outputFile,
Map<DateTimeRange, List<FrameTimetableMap>> frameMap,
TimeIncrement frameTimeIncrement) {
Map<String, File> frameFiles = new HashMap<String, File>();
if (outputFile == null || frameMap == null || frameMap.isEmpty()) {
return frameFiles;
}
DateTimeRange dateRange = outputFile.getDateRange();
List<FrameTimetableMap> productFrameTimetableMaps = frameMap.get(dateRange);
if (productFrameTimetableMaps == null || productFrameTimetableMaps.isEmpty()) {
return frameFiles;
}
Map<String, NcAnimateRegionBean> regionMap = ncAnimateConfig.getRegions();
List<Double> targetHeights = ncAnimateConfig.getTargetHeights();
if (targetHeights == null || targetHeights.isEmpty()) {
targetHeights = new ArrayList<Double>();
targetHeights.add(null);
}
GeneratorContext context = new GeneratorContext(ncAnimateConfig);
Map<String, AbstractNcAnimateRenderFileBean> renderFiles = outputFile.getRenderFiles();
if (regionMap != null) {
Collection<NcAnimateRegionBean> regions = regionMap.values();
// If regionId is specified, filter out regions
if (this.regionId != null) {
regions = new ArrayList<NcAnimateRegionBean>();
regions.add(regionMap.get(this.regionId));
}
for (NcAnimateRegionBean region : regions) {
for (Double targetHeight : targetHeights) {
for (FrameTimetableMap productFrameTimetableMap : productFrameTimetableMaps) {
for (DateTimeRange frameDateRange : productFrameTimetableMap.keySet()) {
context.setFrameTimeIncrement(frameTimeIncrement);
context.setRegion(region);
context.setTargetHeight(targetHeight);
context.setDateRange(frameDateRange);
for (AbstractNcAnimateRenderFileBean renderFile : renderFiles.values()) {
context.setRenderFile(renderFile);
NcAnimateRenderMapBean.MapFormat frameFormat = null;
if (renderFile instanceof NcAnimateRenderVideoBean) {
frameFormat = GeneratorContext.VIDEO_FRAME_FORMAT;
} else if (renderFile instanceof NcAnimateRenderMapBean) {
frameFormat = NcAnimateRenderMapBean.MapFormat.fromExtension(renderFile.getFileExtension());
}
File frameFile = AbstractMediaGenerator.getFrameFile(context, frameDateRange, frameFormat);
if (frameFile != null) {
frameFiles.put(frameFile.getAbsolutePath(), frameFile);
}
}
}
}
}
}
}
return frameFiles;
}
/**
* Create a Map containing the FrameTimetableMap of videoFrameMap and mapFrameMap.
* This method do not combine DateTimeRange, it just put them all in List.
* @param videoFrameMap
* @param mapFrameMap
* @return A new Map containing all the FrameTimetableMap for the videos and maps.
*/
private Map<DateTimeRange, List<FrameTimetableMap>> combineFrames(Map<DateTimeRange, List<FrameTimetableMap>> videoFrameMap, Map<DateTimeRange, List<FrameTimetableMap>> mapFrameMap) {
Map<DateTimeRange, List<FrameTimetableMap>> allFrames = new HashMap<DateTimeRange, List<FrameTimetableMap>>();
if (videoFrameMap != null) {
for (Map.Entry<DateTimeRange, List<FrameTimetableMap>> videoFrameMapEntry : videoFrameMap.entrySet()) {
DateTimeRange dateRange = videoFrameMapEntry.getKey();
List<FrameTimetableMap> frames = videoFrameMapEntry.getValue();
allFrames.put(dateRange, new ArrayList<FrameTimetableMap>(frames));
}
}
if (mapFrameMap != null) {
for (Map.Entry<DateTimeRange, List<FrameTimetableMap>> mapFrameMapEntry : mapFrameMap.entrySet()) {
DateTimeRange dateRange = mapFrameMapEntry.getKey();
List<FrameTimetableMap> frames = mapFrameMapEntry.getValue();
List<FrameTimetableMap> collectedFrames = allFrames.get(dateRange);
if (collectedFrames == null) {
collectedFrames = new ArrayList<FrameTimetableMap>();
allFrames.put(dateRange, collectedFrames);
}
collectedFrames.addAll(frames);
}
}
return allFrames;
}
private Map<Set<String>, SortedSet<DateTimeRange>> groupFrames(DateTimeRange mergedDateRange, Map<DateTimeRange, List<FrameTimetableMap>> frameMap) {
Map<Set<String>, SortedSet<DateTimeRange>> dateRangeMap = new HashMap<Set<String>, SortedSet<DateTimeRange>>();
if (frameMap != null) {
for (Map.Entry<DateTimeRange, List<FrameTimetableMap>> frameMapEntry : frameMap.entrySet()) {
DateTimeRange frameDateRange = frameMapEntry.getKey();
if (mergedDateRange.contains(frameDateRange)) {
List<FrameTimetableMap> frameList = frameMapEntry.getValue();
for (FrameTimetableMap frameTimetableMap : frameList) {
for (Map.Entry<DateTimeRange, FrameTimetable> frameTimetableMapEntry : frameTimetableMap.entrySet()) {
FrameTimetable frameTimetable = frameTimetableMapEntry.getValue();
Set<String> metadataIds = this.getMetadataIds(frameTimetable);
if (!metadataIds.isEmpty()) {
// NOTE: Date ranges can not simply be merged here.
// That could be a problem if we have gaps in the data:
// Input:
// File 1: [----------] [------------]
// File 2: [------------------------------]
// Output:
// [File 1, File 2]: [------------------------------]
// [File 2]: [------]
// Expected:
// [File 1, File 2]: [----------] [------------]
// [File 2]: [------]
// To do this, store all frameTimetableMapEntry.getKey() dateRange into a list, then merge the list at the end
DateTimeRange newDateRange = frameTimetableMapEntry.getKey();
if (newDateRange != null) {
SortedSet<DateTimeRange> dateRangeList = dateRangeMap.get(metadataIds);
if (dateRangeList == null) {
dateRangeList = new TreeSet<DateTimeRange>();
dateRangeMap.put(metadataIds, dateRangeList);
}
dateRangeList.add(newDateRange);
}
}
}
}
}
}
}
// Merge date ranges
for (Map.Entry<Set<String>, SortedSet<DateTimeRange>> dateRangeMapEntry : dateRangeMap.entrySet()) {
SortedSet<DateTimeRange> unmergedDateRanges = dateRangeMapEntry.getValue();
SortedSet<DateTimeRange> mergedDateRanges = DateTimeRange.mergeDateRanges(unmergedDateRanges);
dateRangeMap.put(dateRangeMapEntry.getKey(), mergedDateRanges);
}
return dateRangeMap;
}
private Set<String> getMetadataIds(FrameTimetable frameTimetable) {
Set<String> metadataIds = new HashSet<String>();
if (frameTimetable != null) {
for (NetCDFMetadataSet netCDFMetadataSet : frameTimetable.values()) {
for (NetCDFMetadataFrame netCDFMetadataFrame : netCDFMetadataSet) {
NetCDFMetadataBean netCDFMetadataBean = netCDFMetadataFrame.getMetadata();
if (netCDFMetadataBean != null) {
String metadataId = netCDFMetadataBean.getId();
if (metadataId != null) {
metadataIds.add(metadataId);
}
}
}
}
}
return metadataIds;
}
}
| 51.437588 | 189 | 0.587267 |
141a1b96ff053719669974ac9471d4ddac7f833e | 1,555 |
/*
* Copyright (c) 2012 Yan Pujante
*
* 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.pongasoft.kiwidoc.model.resource;
/**
* Identifies a resource which is resolvable.
*
* @author [email protected]
*/
public interface ResolvableResource<R extends Resource, P extends Resource> extends VersionableResource<R, P>
{
/**
* @return <code>true</code> if the resource is already resolved
*/
boolean isResolved();
/**
* Resolves the resource
* @throws IllegalStateException if the resource is already resolved
*/
void resolve(LibraryVersionResource libraryVersionResource);
/**
* @return the library version resource (note that it is <code>null</code> if {@link #isResolved()}
* returns <code>false</code> and not <code>null</code> otherwise)
*/
LibraryVersionResource getLibraryVersionResource();
/**
* @return the name of the package
*/
String getPackageName();
/**
* @return the name of the class (simple name, may be <code>null</code>)
*/
String getSimpleClassName();
} | 29.339623 | 110 | 0.713183 |
109f7757d3e1a546c2ae0146d288296f0075e8b2 | 370 | package org.springframework.samples.petclinic.repository.springdatajpa;
import org.springframework.data.repository.Repository;
import org.springframework.samples.petclinic.model.Booking;
import org.springframework.samples.petclinic.repository.BookingRepository;
public interface SpringDataBookingRepository extends BookingRepository, Repository<Booking, Integer> {
}
| 37 | 102 | 0.867568 |
871f24744f3e05deec152db586b9ccf255c51553 | 243 | package water.webserver.iface;
import java.io.IOException;
/**
* All the functionality that we need to call on an existing instance of HTTP proxy.
*/
public interface ProxyServer {
void start(String ip, int port) throws IOException;
}
| 18.692308 | 84 | 0.748971 |
f5fbf4298889fefc6a1a1a11edeb7d049d90ab13 | 2,673 | /*******************************************************************************
* Copyright (c) 2013 United States Government as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package gov.nasa.rapid.v2.e4.preferences;
import gov.nasa.rapid.v2.e4.agent.Agent;
import java.io.File;
import org.apache.log4j.Logger;
public final class RapidPreferences {
private static final Logger logger = Logger.getLogger(RapidPreferences.class);
private static IRapidPreferences s_impl = null;
public static void setImpl(IRapidPreferences impl) {
s_impl = impl;
}
/**
* @return default log dir (guaranteed to include trailing separator)
*/
public static String getDefaultLogDir() {
String retVal = assertImpl().getDefaultLogDir();
if(!retVal.endsWith(File.separator)) {
retVal = retVal + File.separator;
}
return retVal;
}
/**
* @return preferred agent of interest
*/
public static Agent getAgentOfInterest() {
return assertImpl().getAgentOfInterest();
}
/**
* @return preferred agent of interest
*/
public static void setAgentOfInterest(Agent agent) {
assertImpl().setAgentOfInterest(agent);
}
protected static IRapidPreferences assertImpl() {
if(s_impl != null) {
return s_impl;
}
else {
// note that when running in Eclipse RCP, the gov.nasa.rapid.v2.ui plugin must
// have activated before this is called for the Eclipse RCP preferences to be set
System.err.println("*ERROR* RapidPreferences implementation is null. Creating fallback implementation.");
logger.error("RapidPreferences implementation is null. Creating fallback implementation.");
s_impl = new FallbackRapidPreferences();
return s_impl;
}
}
}
| 35.64 | 118 | 0.61691 |
0aba29eccda36fc751a0ca0572bf41e034028ab8 | 11,147 | package net.evendanan.bazel.mvn.impl;
import com.google.common.io.Resources;
import net.evendanan.bazel.mvn.api.RuleClassifier;
import net.evendanan.bazel.mvn.api.TargetsBuilder;
import net.evendanan.bazel.mvn.api.model.Dependency;
import net.evendanan.bazel.mvn.api.model.MavenCoordinate;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
public class RuleClassifiersTest {
private MavenCoordinate mMavenCoordinate;
@Before
public void setUp() {
mMavenCoordinate = MavenCoordinate.create("g", "a", "1", "jar");
}
@Test
public void testAarClassifier() {
Dependency dep =
Dependency.builder()
.mavenCoordinate(MavenCoordinate.create("", "", "", "aar"))
.build();
Assert.assertSame(
TargetsBuilders.AAR_IMPORT_WITHOUT_EXPORTS,
new RuleClassifiers.AarClassifier().classifyRule(dep).get(0));
dep =
Dependency.builder()
.mavenCoordinate(MavenCoordinate.create("", "", "", "jar"))
.build();
Assert.assertTrue(new RuleClassifiers.AarClassifier().classifyRule(dep).isEmpty());
dep =
Dependency.builder()
.mavenCoordinate(MavenCoordinate.create("", "", "", "pom"))
.build();
Assert.assertTrue(new RuleClassifiers.AarClassifier().classifyRule(dep).isEmpty());
}
@Test
public void testPomClassifier() {
Dependency dep =
Dependency.builder()
.mavenCoordinate(MavenCoordinate.create("", "", "", "pom"))
.build();
Assert.assertSame(
TargetsBuilders.POM_IMPORT,
new RuleClassifiers.PomClassifier().classifyRule(dep).get(0));
dep =
Dependency.builder()
.mavenCoordinate(MavenCoordinate.create("", "", "", "jar"))
.build();
Assert.assertTrue(new RuleClassifiers.PomClassifier().classifyRule(dep).isEmpty());
}
@Test
public void testJarInspector_unknown() throws Exception {
final Dependency dependency =
Dependency.builder().mavenCoordinate(mMavenCoordinate).build();
final Function<Dependency, URI> dependencyURIFunction =
dep -> {
try {
return RuleClassifiersTest.class
.getClassLoader()
.getResource("dataenum-1.0.2.jar")
.toURI();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
};
Assert.assertTrue(
new RuleClassifiers.JarInspector(dependencyURIFunction)
.findAllPossibleBuilders(dependency)
.isEmpty());
}
@Test
public void testJarInspector_java_plugin() throws Exception {
final Dependency dependency =
Dependency.builder().mavenCoordinate(mMavenCoordinate).build();
final Function<Dependency, URI> dependencyURIFunction =
dep -> {
try {
return Resources.getResource("dataenum-processor-1.0.2.jar")
.toURI();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
};
final TargetsBuilder processorFormatter =
new RuleClassifiers.JarInspector(dependencyURIFunction)
.findAllPossibleBuilders(dependency)
.stream()
.filter(possibleBuilder -> possibleBuilder instanceof TargetsBuilders.JavaPluginFormatter)
.findFirst()
.orElse(null);
Assert.assertNotNull(processorFormatter);
List<String> processorClasses =
((TargetsBuilders.JavaPluginFormatter) processorFormatter).getProcessorClasses();
Assert.assertEquals(1, processorClasses.size());
Assert.assertEquals(
"com.spotify.dataenum.processor.DataEnumProcessor", processorClasses.get(0));
}
@Test
public void testJarInspector_java_plugin_with_comments() throws Exception {
final Dependency dependency =
Dependency.builder().mavenCoordinate(mMavenCoordinate).build();
final Function<Dependency, URI> dependencyURIFunction =
dep -> {
try {
return Resources.getResource("dataenum-processor-1.0.2-with-comments.jar")
.toURI();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
};
final TargetsBuilder processorFormatter =
new RuleClassifiers.JarInspector(dependencyURIFunction)
.findAllPossibleBuilders(dependency)
.stream()
.filter(targetsBuilder -> targetsBuilder instanceof TargetsBuilders.JavaPluginFormatter)
.findFirst()
.orElse(null);
Assert.assertNotNull(processorFormatter);
List<String> processorClasses =
((TargetsBuilders.JavaPluginFormatter) processorFormatter).getProcessorClasses();
Assert.assertEquals(1, processorClasses.size());
Assert.assertEquals(
"com.spotify.dataenum.processor.DataEnumProcessor", processorClasses.get(0));
}
@Test
public void testJarInspector_java_plugin_native() throws Exception {
final Dependency dependency =
Dependency.builder().mavenCoordinate(mMavenCoordinate).build();
final Function<Dependency, URI> dependencyURIFunction =
dep -> {
try {
return RuleClassifiersTest.class
.getClassLoader()
.getResource("dataenum-processor-1.0.2.jar")
.toURI();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
};
final TargetsBuilder processorFormatter =
new RuleClassifiers.JarInspector(dependencyURIFunction)
.findAllPossibleBuilders(dependency)
.stream()
.filter(targetsBuilder -> targetsBuilder instanceof TargetsBuilders.JavaPluginFormatter)
.findFirst()
.orElse(null);
Assert.assertNotNull(processorFormatter);
List<String> processorClasses =
((TargetsBuilders.JavaPluginFormatter) processorFormatter).getProcessorClasses();
Assert.assertEquals(1, processorClasses.size());
Assert.assertEquals(
"com.spotify.dataenum.processor.DataEnumProcessor", processorClasses.get(0));
}
@Test
public void testPriority() {
RuleClassifier classifier1 = Mockito.mock(RuleClassifier.class);
Mockito.when(classifier1.classifyRule(Mockito.any())).thenReturn(Collections.emptyList());
RuleClassifier classifier2 = Mockito.mock(RuleClassifier.class);
TargetsBuilder targetsBuilder2 = Mockito.mock(TargetsBuilder.class);
Mockito.when(classifier2.classifyRule(Mockito.any()))
.thenReturn(Collections.singletonList(targetsBuilder2));
RuleClassifier classifier3 = Mockito.mock(RuleClassifier.class);
TargetsBuilder targetsBuilder3 = Mockito.mock(TargetsBuilder.class);
Mockito.when(classifier3.classifyRule(Mockito.any()))
.thenReturn(Collections.singletonList(targetsBuilder3));
TargetsBuilder defaultTargetBuilder = Mockito.mock(TargetsBuilder.class);
TargetsBuilder actualTargetBuilder =
RuleClassifiers.priorityRuleClassifier(
Arrays.asList(classifier1, classifier2, classifier3),
defaultTargetBuilder,
Dependency.builder()
.mavenCoordinate(MavenCoordinate.create("g", "a", "1", ""))
.build());
Assert.assertTrue(actualTargetBuilder instanceof TargetsBuilders.CompositeBuilder);
TargetsBuilders.CompositeBuilder compositeBuilder = (TargetsBuilders.CompositeBuilder) actualTargetBuilder;
Assert.assertEquals(1, compositeBuilder.getTargetsBuilders().size());
Assert.assertTrue(compositeBuilder.getTargetsBuilders().contains(targetsBuilder2));
}
@Test
public void testPriorityToDefault() {
RuleClassifier classifier1 = Mockito.mock(RuleClassifier.class);
Mockito.when(classifier1.classifyRule(Mockito.any())).thenReturn(Collections.emptyList());
RuleClassifier classifier2 = Mockito.mock(RuleClassifier.class);
Mockito.when(classifier2.classifyRule(Mockito.any())).thenReturn(Collections.emptyList());
RuleClassifier classifier3 = Mockito.mock(RuleClassifier.class);
Mockito.when(classifier3.classifyRule(Mockito.any())).thenReturn(Collections.emptyList());
TargetsBuilder defaultTargetBuilder = Mockito.mock(TargetsBuilder.class);
TargetsBuilder actualTargetBuilder =
RuleClassifiers.priorityRuleClassifier(
Arrays.asList(classifier1, classifier2, classifier3),
defaultTargetBuilder,
Dependency.builder()
.mavenCoordinate(MavenCoordinate.create("g", "a", "1", ""))
.build());
Assert.assertSame(defaultTargetBuilder, actualTargetBuilder);
}
@Test
public void testJarClassifierNoResults() {
RuleClassifier classifier = new RuleClassifiers.JarClassifier(dependency -> Collections.emptyList());
final Dependency dependency =
Dependency.builder().mavenCoordinate(mMavenCoordinate).build();
Assert.assertTrue(classifier.classifyRule(dependency).isEmpty());
}
@Test
public void testJarClassifierUnknownResults() {
RuleClassifier classifier = new RuleClassifiers.JarClassifier(dependency -> Collections.singletonList(TargetsBuilders.AAR_IMPORT));
final Dependency dependency =
Dependency.builder().mavenCoordinate(mMavenCoordinate).build();
//just passes that along
Assert.assertEquals(1, classifier.classifyRule(dependency).size());
Assert.assertSame(TargetsBuilders.AAR_IMPORT, classifier.classifyRule(dependency).get(0));
}
}
| 44.767068 | 139 | 0.601507 |
8010b40687fd069fc94a44f1744359812eeae5e1 | 7,619 | /*******************************************************************************
* Copyright (c) 2012 Secure Software Engineering Group at EC SPRIDE.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors: Christian Fritz, Steven Arzt, Siegfried Rasthofer, Eric
* Bodden, and others.
******************************************************************************/
package soot.jimple.infoflow.test.junit;
import java.util.ArrayList;
import java.util.List;
import org.junit.Ignore;
import org.junit.Test;
import soot.jimple.infoflow.IInfoflow;
/**
* check taint propagation in all sorts of lists, for example LinkedLists, ArrayLists and Stacks.
*/
public class ListTests extends JUnitTests {
@Test(timeout=300000)
public void concreteArrayListPos0Test(){
IInfoflow infoflow = initInfoflow();
List<String> epoints = new ArrayList<String>();
epoints.add("<soot.jimple.infoflow.test.ListTestCode: void concreteWriteReadPos0Test()>");
infoflow.computeInfoflow(appPath, libPath, epoints, sources, sinks);
checkInfoflow(infoflow, 1);
}
@Test(timeout=300000)
public void concreteArrayListPos1Test(){
IInfoflow infoflow = initInfoflow();
List<String> epoints = new ArrayList<String>();
epoints.add("<soot.jimple.infoflow.test.ListTestCode: void concreteWriteReadPos1Test()>");
infoflow.computeInfoflow(appPath, libPath, epoints, sources, sinks);
checkInfoflow(infoflow, 1);
}
@Test(timeout=300000)
@Ignore // no longer works due to changes in JDK 1.7.0_45
public void concreteArrayListNegativeTest(){
IInfoflow infoflow = initInfoflow();
List<String> epoints = new ArrayList<String>();
epoints.add("<soot.jimple.infoflow.test.ListTestCode: void concreteWriteReadNegativeTest()>");
infoflow.computeInfoflow(appPath, libPath, epoints, sources, sinks);
negativeCheckInfoflow(infoflow);
}
@Test(timeout=300000)
public void listTest(){
IInfoflow infoflow = initInfoflow();
List<String> epoints = new ArrayList<String>();
epoints.add("<soot.jimple.infoflow.test.ListTestCode: void writeReadTest()>");
infoflow.computeInfoflow(appPath, libPath, epoints, sources, sinks);
checkInfoflow(infoflow, 1);
}
@Test(timeout=300000)
public void listIteratorTest(){
IInfoflow infoflow = initInfoflow();
List<String> epoints = new ArrayList<String>();
epoints.add("<soot.jimple.infoflow.test.ListTestCode: void iteratorTest()>");
infoflow.computeInfoflow(appPath, libPath, epoints, sources, sinks);
checkInfoflow(infoflow, 1);
}
@Test(timeout=300000)
public void listsubListTest(){
IInfoflow infoflow = initInfoflow();
List<String> epoints = new ArrayList<String>();
epoints.add("<soot.jimple.infoflow.test.ListTestCode: void subListTest()>");
infoflow.computeInfoflow(appPath, libPath, epoints, sources, sinks);
checkInfoflow(infoflow, 1);
}
@Test(timeout=300000)
public void concreteLinkedListNegativeTest(){
IInfoflow infoflow = initInfoflow();
List<String> epoints = new ArrayList<String>();
epoints.add("<soot.jimple.infoflow.test.ListTestCode: void linkedListConcreteWriteReadNegativeTest()>");
infoflow.computeInfoflow(appPath, libPath, epoints, sources, sinks);
negativeCheckInfoflow(infoflow);
}
@Test(timeout=300000)
public void concreteLinkedListTest(){
IInfoflow infoflow = initInfoflow();
List<String> epoints = new ArrayList<String>();
epoints.add("<soot.jimple.infoflow.test.ListTestCode: void linkedListConcreteWriteReadTest()>");
infoflow.computeInfoflow(appPath, libPath, epoints, sources, sinks);
checkInfoflow(infoflow, 1);
}
@Test(timeout=300000)
public void writeReadLinkedListTest(){
IInfoflow infoflow = initInfoflow();
List<String> epoints = new ArrayList<String>();
epoints.add("<soot.jimple.infoflow.test.ListTestCode: void linkedListWriteReadTest()>");
infoflow.computeInfoflow(appPath, libPath, epoints, sources, sinks);
checkInfoflow(infoflow, 1);
}
@Test(timeout=300000)
public void concreteLinkedListIteratorTest(){
IInfoflow infoflow = initInfoflow();
List<String> epoints = new ArrayList<String>();
epoints.add("<soot.jimple.infoflow.test.ListTestCode: void linkedListIteratorTest()>");
infoflow.computeInfoflow(appPath, libPath, epoints, sources, sinks);
checkInfoflow(infoflow, 1);
}
@Test(timeout=250000)
public void linkedListIteratorTest(){
IInfoflow infoflow = initInfoflow();
List<String> epoints = new ArrayList<String>();
epoints.add("<soot.jimple.infoflow.test.ListTestCode: void linkedList()>");
infoflow.computeInfoflow(appPath, libPath, epoints, sources, sinks);
checkInfoflow(infoflow, 1);
}
@Test(timeout=300000)
public void staticLinkedListIteratorTest(){
IInfoflow infoflow = initInfoflow();
List<String> epoints = new ArrayList<String>();
epoints.add("<soot.jimple.infoflow.test.ListTestCode: void staticLinkedList()>");
infoflow.computeInfoflow(appPath, libPath, epoints, sources, sinks);
checkInfoflow(infoflow, 1);
}
@Test(timeout=300000)
public void subLinkedListTest(){
IInfoflow infoflow = initInfoflow();
List<String> epoints = new ArrayList<String>();
epoints.add("<soot.jimple.infoflow.test.ListTestCode: void linkedListSubListTest()>");
infoflow.computeInfoflow(appPath, libPath, epoints, sources, sinks);
checkInfoflow(infoflow, 1);
}
@Test(timeout=300000)
public void stackGetTest(){
IInfoflow infoflow = initInfoflow();
List<String> epoints = new ArrayList<String>();
epoints.add("<soot.jimple.infoflow.test.ListTestCode: void concreteWriteReadStackGetTest()>");
infoflow.computeInfoflow(appPath, libPath, epoints, sources, sinks);
checkInfoflow(infoflow, 1);
}
@Test(timeout=300000)
public void stackPeekTest(){
IInfoflow infoflow = initInfoflow();
List<String> epoints = new ArrayList<String>();
epoints.add("<soot.jimple.infoflow.test.ListTestCode: void concreteWriteReadStackPeekTest()>");
infoflow.computeInfoflow(appPath, libPath, epoints, sources, sinks);
checkInfoflow(infoflow, 1);
}
@Test(timeout=300000)
public void stackPopTest(){
IInfoflow infoflow = initInfoflow();
List<String> epoints = new ArrayList<String>();
epoints.add("<soot.jimple.infoflow.test.ListTestCode: void concreteWriteReadStackPopTest()>");
infoflow.computeInfoflow(appPath, libPath, epoints, sources, sinks);
checkInfoflow(infoflow, 1);
}
@Test(timeout=300000)
public void stackNegativeTest(){
IInfoflow infoflow = initInfoflow();
List<String> epoints = new ArrayList<String>();
epoints.add("<soot.jimple.infoflow.test.ListTestCode: void concreteWriteReadStackNegativeTest()>");
infoflow.computeInfoflow(appPath, libPath, epoints, sources, sinks);
negativeCheckInfoflow(infoflow);
}
@Test(timeout=300000)
public void iteratorHasNextTest(){
IInfoflow infoflow = initInfoflow();
List<String> epoints = new ArrayList<String>();
epoints.add("<soot.jimple.infoflow.test.ListTestCode: void iteratorHasNextTest()>");
infoflow.computeInfoflow(appPath, libPath, epoints, sources, sinks);
negativeCheckInfoflow(infoflow);
}
}
| 40.1 | 109 | 0.701929 |
feba65d056525946411b2fb57233d2d23ba94817 | 10,112 | /**
* SkillAPI
* com.sucy.skill.listener.StatusListener
*
* The MIT License (MIT)
*
* Copyright (c) 2014 Steven Sucy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software") to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.sucy.skill.listener;
import mc.promcteam.engine.mccore.util.VersionManager;
import com.sucy.skill.api.event.FlagApplyEvent;
import com.sucy.skill.api.event.PhysicalDamageEvent;
import com.sucy.skill.api.event.PlayerCastSkillEvent;
import com.sucy.skill.api.event.TrueDamageEvent;
import com.sucy.skill.api.util.FlagManager;
import com.sucy.skill.api.util.StatusFlag;
import com.sucy.skill.data.TitleType;
import com.sucy.skill.language.RPGFilter;
import com.sucy.skill.manager.TitleManager;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.ProjectileLaunchEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.util.Vector;
import java.util.HashMap;
import java.util.HashSet;
/**
* Listener for applying default status flags for the API. You should
* not use this class as it is already set up by the API.
*/
public class StatusListener extends SkillAPIListener
{
private static final HashMap<String, Long> messageTimers = new HashMap<String, Long>();
private static final HashSet<String> interrupts = new HashSet<String>()
{{
add(StatusFlag.STUN);
add(StatusFlag.SILENCE);
}};
private static final HashMap<String, String> messageMap = new HashMap<String, String>()
{{
put(StatusFlag.STUN, "stunned");
put(StatusFlag.ROOT, "rooted");
put(StatusFlag.INVINCIBLE, "invincible");
put(StatusFlag.ABSORB, "absorbed");
put(StatusFlag.DISARM, "disarmed");
put(StatusFlag.SILENCE, "silenced");
put(StatusFlag.CHANNELING, "channeling");
put(StatusFlag.CHANNEL, "channeling");
}};
private final Vector ZERO = new Vector(0, 0, 0);
/**
* Cleans up the listener data on shutdown
*/
@Override
public void cleanup()
{
messageTimers.clear();
}
/**
* Clears data for players leaving the server
*
* @param event event details
*/
@EventHandler(priority = EventPriority.MONITOR)
public void onQuit(PlayerQuitEvent event)
{
FlagManager.clearFlags(event.getPlayer());
}
/**
* Cancels player movement when stunned or rooted
*
* @param event event details
*/
@EventHandler(priority = EventPriority.HIGHEST)
public void onMove(PlayerMoveEvent event)
{
if (((event.getPlayer()).isOnGround() || event.getTo().getY() > event.getFrom().getY()) && check(event, event.getPlayer(), event.getPlayer(), StatusFlag.STUN, StatusFlag.ROOT, StatusFlag.CHANNELING))
{
event.getPlayer().setVelocity(ZERO);
}
}
/**
* Applies interrupt effects, stopping channeling.
*
* @param event event details
*/
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onInterrupt(FlagApplyEvent event)
{
if (interrupts.contains(event.getFlag()) && FlagManager.hasFlag(event.getEntity(), StatusFlag.CHANNELING))
{
FlagManager.removeFlag(event.getEntity(), StatusFlag.CHANNELING);
FlagManager.removeFlag(event.getEntity(), StatusFlag.CHANNEL);
}
}
/**
* Applies a slow potion to mobs when stunned/rooted due to
* them not having a move event like the players.
*
* @param event event details
*/
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onFlag(FlagApplyEvent event)
{
if (event.getFlag().equals(StatusFlag.STUN)
|| event.getFlag().equals(StatusFlag.ROOT)
|| event.getFlag().equals(StatusFlag.CHANNELING))
{
if (!(event.getEntity() instanceof Player))
{
event.getEntity().addPotionEffect(new PotionEffect(PotionEffectType.SLOW, event.getTicks(), 100));
}
}
}
/**
* Cancels damage when an attacker is disarmed.
*
* @param event event details
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onDamage(EntityDamageByEntityEvent event)
{
if (event.getCause() == EntityDamageEvent.DamageCause.CUSTOM)
return;
LivingEntity damager = ListenerUtil.getDamager(event);
check(event, damager, damager, StatusFlag.STUN, StatusFlag.DISARM);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPhysicalDamage(PhysicalDamageEvent event) {
check(event, event.getDamager(), event.getDamager(), StatusFlag.CHANNEL);
}
/**
* Cancels damage when a defender is invincible or inverting damage
*
* @param event event details
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onDamaged(EntityDamageEvent event)
{
if (event.getCause() == EntityDamageEvent.DamageCause.CUSTOM
|| !(event.getEntity() instanceof LivingEntity))
return;
checkAbsorbAndInvincible((LivingEntity) event.getEntity(), event, event.getDamage());
}
/**
* Cancels damage when a defender is invincible or inverting damage
*
* @param event event details
*/
public void onTrueDamage(TrueDamageEvent event)
{
checkAbsorbAndInvincible(event.getTarget(), event, event.getDamage());
}
/**
* Shared code for true damage and regular damage events for absorb/invincible
*
* @param entity entity being hit
* @param event event details
* @param damage damage amount
*/
private void checkAbsorbAndInvincible(LivingEntity entity, Cancellable event, double damage)
{
if (check(event, entity, null, StatusFlag.ABSORB))
VersionManager.heal(entity, damage);
else
check(event, entity, null, StatusFlag.INVINCIBLE);
}
/**
* Cancels firing projectiles when the launcher is stunned or disarmed.
*
* @param event event details
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onLaunch(ProjectileLaunchEvent event)
{
if (event.getEntity().getShooter() instanceof LivingEntity)
{
LivingEntity shooter = (LivingEntity) event.getEntity().getShooter();
check(event, shooter, shooter, StatusFlag.STUN, StatusFlag.DISARM, StatusFlag.CHANNELING);
}
}
/**
* Cancels players casting skills while stunned or silenced
*
* @param event event details
*/
@EventHandler(ignoreCancelled = true)
public void onCast(PlayerCastSkillEvent event)
{
check(event, event.getPlayer(), event.getPlayer(), StatusFlag.SILENCE, StatusFlag.STUN, StatusFlag.CHANNEL);
}
/**
* Checks for the delay between sending status messages
*
* @param player player to check for
*
* @return true if can send a message, false otherwise
*/
private boolean checkTime(Player player)
{
if (!messageTimers.containsKey(player.getName())
|| System.currentTimeMillis() - messageTimers.get(player.getName()) > 1000)
{
messageTimers.put(player.getName(), System.currentTimeMillis());
return true;
}
return false;
}
/**
* Checks an entity for flags which cancel the event if applied.
*
* @param event event that is cancelled if a flag is applied
* @param entity entity to check for flags
* @param receiver entity to send messages to
* @param flags flags to check for
*
* @return the canceled state of the event
*/
private boolean check(Cancellable event, LivingEntity entity, LivingEntity receiver, String... flags)
{
for (String flag : flags)
{
if (FlagManager.hasFlag(entity, flag))
{
if (receiver instanceof Player)
{
Player player = (Player) receiver;
if (checkTime(player))
{
TitleManager.show(
player,
TitleType.STATUS,
"Status." + messageMap.get(flag),
RPGFilter.DURATION.setReplacement("" + FlagManager.getTimeLeft(entity, flag))
);
}
}
event.setCancelled(true);
return true;
}
}
return false;
}
}
| 34.394558 | 207 | 0.654173 |
9c38407d37892752caf6a0a03e8f02dab8b1a01c | 2,061 | package seedu.bookmark.testutil;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import seedu.bookmark.model.Library;
import seedu.bookmark.model.WordBank;
import seedu.bookmark.model.book.Book;
import seedu.bookmark.model.wordstore.Word;
public class TypicalWords {
public static final String HARRY = "harry";
public static final String POTTER = "potter";
public static final String AND = "and";
public static final String CHAMBER = "chamber";
public static final String SECRETS = "secrets";
public static final String MISSPELT_HARRY = "hbrry";
public static final String MISSPELT_POTTER = "pptter";
public static final String MISSPELT_AND = "abd";
public static final String MISSPELT_CHAMBER = "chabber";
public static final String MISSPELT_SECRETS = "sekrets";
//correctly spelt
public static final Word CORRECT_HARRY = new Word("harry");
public static final Word CORRECT_POTTER = new Word("potter");
public static final Word CORRECT_AND = new Word("and");
public static final Word CORRECT_CHAMBER = new Word("chamber");
public static final Word CORRECT_SECRETS = new Word("secrets");
private TypicalWords() {} //prevents instantiation
/**
* Returns an {@code WordBank} with all the typical books converted into words.
*/
public static WordBank getTypicalWordBank() {
Library lib = new Library();
for (Book book : TypicalBooks.getTypicalBooks()) {
lib.addBook(book);
}
return new WordBank(lib);
}
public static WordBank getEmptyWordBank() {
Library lib = new Library();
return new WordBank(lib);
}
public static List<Word> getTypicalWords() {
return new ArrayList<>(Arrays.asList(CORRECT_HARRY, CORRECT_POTTER, CORRECT_AND,
CORRECT_CHAMBER, CORRECT_SECRETS));
}
public static List<String> getTypicalStrings() {
return new ArrayList<>(Arrays.asList(HARRY, POTTER, AND,
CHAMBER, SECRETS));
}
}
| 31.227273 | 88 | 0.688016 |
d69133434adfef4666a8efefd024df7764533ce4 | 23,040 | /**
* Copyright © 2016-2022 The Thingsboard 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.thingsboard.server.service.edge.rpc.sync;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.DeviceProfile;
import org.thingsboard.server.common.data.EdgeUtils;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.EntityView;
import org.thingsboard.server.common.data.edge.Edge;
import org.thingsboard.server.common.data.edge.EdgeEvent;
import org.thingsboard.server.common.data.edge.EdgeEventActionType;
import org.thingsboard.server.common.data.edge.EdgeEventType;
import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.id.DeviceProfileId;
import org.thingsboard.server.common.data.id.EdgeId;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.EntityIdFactory;
import org.thingsboard.server.common.data.id.RuleChainId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.UserId;
import org.thingsboard.server.common.data.id.WidgetsBundleId;
import org.thingsboard.server.common.data.kv.AttributeKvEntry;
import org.thingsboard.server.common.data.kv.DataType;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.common.data.relation.EntityRelation;
import org.thingsboard.server.common.data.relation.EntityRelationsQuery;
import org.thingsboard.server.common.data.relation.EntitySearchDirection;
import org.thingsboard.server.common.data.relation.RelationTypeGroup;
import org.thingsboard.server.common.data.relation.RelationsSearchParameters;
import org.thingsboard.server.common.data.widget.WidgetType;
import org.thingsboard.server.common.data.widget.WidgetsBundle;
import org.thingsboard.server.dao.attributes.AttributesService;
import org.thingsboard.server.dao.device.DeviceProfileService;
import org.thingsboard.server.dao.device.DeviceService;
import org.thingsboard.server.dao.edge.EdgeEventService;
import org.thingsboard.server.dao.entityview.EntityViewService;
import org.thingsboard.server.dao.relation.RelationService;
import org.thingsboard.server.dao.widget.WidgetTypeService;
import org.thingsboard.server.dao.widget.WidgetsBundleService;
import org.thingsboard.server.gen.edge.v1.AttributesRequestMsg;
import org.thingsboard.server.gen.edge.v1.DeviceCredentialsRequestMsg;
import org.thingsboard.server.gen.edge.v1.DeviceProfileDevicesRequestMsg;
import org.thingsboard.server.gen.edge.v1.EntityViewsRequestMsg;
import org.thingsboard.server.gen.edge.v1.RelationRequestMsg;
import org.thingsboard.server.gen.edge.v1.RuleChainMetadataRequestMsg;
import org.thingsboard.server.gen.edge.v1.UserCredentialsRequestMsg;
import org.thingsboard.server.gen.edge.v1.WidgetBundleTypesRequestMsg;
import org.thingsboard.server.service.edge.rpc.EdgeEventUtils;
import org.thingsboard.server.service.executors.DbCallbackExecutorService;
import org.thingsboard.server.cluster.TbClusterService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@Service
@Slf4j
public class DefaultEdgeRequestsService implements EdgeRequestsService {
private static final ObjectMapper mapper = new ObjectMapper();
private static final int DEFAULT_PAGE_SIZE = 1000;
@Autowired
private EdgeEventService edgeEventService;
@Autowired
private AttributesService attributesService;
@Autowired
private RelationService relationService;
@Autowired
private DeviceService deviceService;
@Autowired
private EntityViewService entityViewService;
@Autowired
private DeviceProfileService deviceProfileService;
@Autowired
private WidgetsBundleService widgetsBundleService;
@Autowired
private WidgetTypeService widgetTypeService;
@Autowired
private DbCallbackExecutorService dbCallbackExecutorService;
@Autowired
private TbClusterService tbClusterService;
@Override
public ListenableFuture<Void> processRuleChainMetadataRequestMsg(TenantId tenantId, Edge edge, RuleChainMetadataRequestMsg ruleChainMetadataRequestMsg) {
log.trace("[{}] processRuleChainMetadataRequestMsg [{}][{}]", tenantId, edge.getName(), ruleChainMetadataRequestMsg);
if (ruleChainMetadataRequestMsg.getRuleChainIdMSB() != 0 && ruleChainMetadataRequestMsg.getRuleChainIdLSB() != 0) {
RuleChainId ruleChainId =
new RuleChainId(new UUID(ruleChainMetadataRequestMsg.getRuleChainIdMSB(), ruleChainMetadataRequestMsg.getRuleChainIdLSB()));
saveEdgeEvent(tenantId, edge.getId(),
EdgeEventType.RULE_CHAIN_METADATA, EdgeEventActionType.ADDED, ruleChainId, null);
}
return Futures.immediateFuture(null);
}
@Override
public ListenableFuture<Void> processAttributesRequestMsg(TenantId tenantId, Edge edge, AttributesRequestMsg attributesRequestMsg) {
log.trace("[{}] processAttributesRequestMsg [{}][{}]", tenantId, edge.getName(), attributesRequestMsg);
EntityId entityId = EntityIdFactory.getByTypeAndUuid(
EntityType.valueOf(attributesRequestMsg.getEntityType()),
new UUID(attributesRequestMsg.getEntityIdMSB(), attributesRequestMsg.getEntityIdLSB()));
final EdgeEventType type = EdgeUtils.getEdgeEventTypeByEntityType(entityId.getEntityType());
if (type != null) {
SettableFuture<Void> futureToSet = SettableFuture.create();
String scope = attributesRequestMsg.getScope();
ListenableFuture<List<AttributeKvEntry>> findAttrFuture = attributesService.findAll(tenantId, entityId, scope);
Futures.addCallback(findAttrFuture, new FutureCallback<List<AttributeKvEntry>>() {
@Override
public void onSuccess(@Nullable List<AttributeKvEntry> ssAttributes) {
if (ssAttributes != null && !ssAttributes.isEmpty()) {
try {
Map<String, Object> entityData = new HashMap<>();
ObjectNode attributes = mapper.createObjectNode();
for (AttributeKvEntry attr : ssAttributes) {
if (attr.getDataType() == DataType.BOOLEAN && attr.getBooleanValue().isPresent()) {
attributes.put(attr.getKey(), attr.getBooleanValue().get());
} else if (attr.getDataType() == DataType.DOUBLE && attr.getDoubleValue().isPresent()) {
attributes.put(attr.getKey(), attr.getDoubleValue().get());
} else if (attr.getDataType() == DataType.LONG && attr.getLongValue().isPresent()) {
attributes.put(attr.getKey(), attr.getLongValue().get());
} else {
attributes.put(attr.getKey(), attr.getValueAsString());
}
}
entityData.put("kv", attributes);
entityData.put("scope", scope);
JsonNode body = mapper.valueToTree(entityData);
log.debug("Sending attributes data msg, entityId [{}], attributes [{}]", entityId, body);
saveEdgeEvent(tenantId,
edge.getId(),
type,
EdgeEventActionType.ATTRIBUTES_UPDATED,
entityId,
body);
} catch (Exception e) {
log.error("[{}] Failed to save attribute updates to the edge", edge.getName(), e);
futureToSet.setException(new RuntimeException("[" + edge.getName() + "] Failed to send attribute updates to the edge", e));
return;
}
} else {
log.trace("[{}][{}] No attributes found for entity {} [{}]", tenantId,
edge.getName(),
entityId.getEntityType(),
entityId.getId());
}
futureToSet.set(null);
}
@Override
public void onFailure(Throwable t) {
log.error("Can't find attributes [{}]", attributesRequestMsg, t);
futureToSet.setException(t);
}
}, dbCallbackExecutorService);
return futureToSet;
} else {
log.warn("[{}] Type doesn't supported {}", tenantId, entityId.getEntityType());
return Futures.immediateFuture(null);
}
}
@Override
public ListenableFuture<Void> processRelationRequestMsg(TenantId tenantId, Edge edge, RelationRequestMsg relationRequestMsg) {
log.trace("[{}] processRelationRequestMsg [{}][{}]", tenantId, edge.getName(), relationRequestMsg);
EntityId entityId = EntityIdFactory.getByTypeAndUuid(
EntityType.valueOf(relationRequestMsg.getEntityType()),
new UUID(relationRequestMsg.getEntityIdMSB(), relationRequestMsg.getEntityIdLSB()));
List<ListenableFuture<List<EntityRelation>>> futures = new ArrayList<>();
futures.add(findRelationByQuery(tenantId, edge, entityId, EntitySearchDirection.FROM));
futures.add(findRelationByQuery(tenantId, edge, entityId, EntitySearchDirection.TO));
ListenableFuture<List<List<EntityRelation>>> relationsListFuture = Futures.allAsList(futures);
SettableFuture<Void> futureToSet = SettableFuture.create();
Futures.addCallback(relationsListFuture, new FutureCallback<List<List<EntityRelation>>>() {
@Override
public void onSuccess(@Nullable List<List<EntityRelation>> relationsList) {
try {
if (relationsList != null && !relationsList.isEmpty()) {
for (List<EntityRelation> entityRelations : relationsList) {
log.trace("[{}] [{}] [{}] relation(s) are going to be pushed to edge.", edge.getId(), entityId, entityRelations.size());
for (EntityRelation relation : entityRelations) {
try {
if (!relation.getFrom().getEntityType().equals(EntityType.EDGE) &&
!relation.getTo().getEntityType().equals(EntityType.EDGE)) {
saveEdgeEvent(tenantId,
edge.getId(),
EdgeEventType.RELATION,
EdgeEventActionType.ADDED,
null,
mapper.valueToTree(relation));
}
} catch (Exception e) {
log.error("Exception during loading relation [{}] to edge on sync!", relation, e);
futureToSet.setException(e);
return;
}
}
}
}
futureToSet.set(null);
} catch (Exception e) {
log.error("Exception during loading relation(s) to edge on sync!", e);
futureToSet.setException(e);
}
}
@Override
public void onFailure(Throwable t) {
log.error("[{}] Can't find relation by query. Entity id [{}]", tenantId, entityId, t);
futureToSet.setException(t);
}
}, dbCallbackExecutorService);
return futureToSet;
}
private ListenableFuture<List<EntityRelation>> findRelationByQuery(TenantId tenantId, Edge edge,
EntityId entityId, EntitySearchDirection direction) {
EntityRelationsQuery query = new EntityRelationsQuery();
query.setParameters(new RelationsSearchParameters(entityId, direction, -1, false));
return relationService.findByQuery(tenantId, query);
}
@Override
public ListenableFuture<Void> processDeviceCredentialsRequestMsg(TenantId tenantId, Edge edge, DeviceCredentialsRequestMsg deviceCredentialsRequestMsg) {
log.trace("[{}] processDeviceCredentialsRequestMsg [{}][{}]", tenantId, edge.getName(), deviceCredentialsRequestMsg);
if (deviceCredentialsRequestMsg.getDeviceIdMSB() != 0 && deviceCredentialsRequestMsg.getDeviceIdLSB() != 0) {
DeviceId deviceId = new DeviceId(new UUID(deviceCredentialsRequestMsg.getDeviceIdMSB(), deviceCredentialsRequestMsg.getDeviceIdLSB()));
saveEdgeEvent(tenantId, edge.getId(), EdgeEventType.DEVICE,
EdgeEventActionType.CREDENTIALS_UPDATED, deviceId, null);
}
return Futures.immediateFuture(null);
}
@Override
public ListenableFuture<Void> processUserCredentialsRequestMsg(TenantId tenantId, Edge edge, UserCredentialsRequestMsg userCredentialsRequestMsg) {
log.trace("[{}] processUserCredentialsRequestMsg [{}][{}]", tenantId, edge.getName(), userCredentialsRequestMsg);
if (userCredentialsRequestMsg.getUserIdMSB() != 0 && userCredentialsRequestMsg.getUserIdLSB() != 0) {
UserId userId = new UserId(new UUID(userCredentialsRequestMsg.getUserIdMSB(), userCredentialsRequestMsg.getUserIdLSB()));
saveEdgeEvent(tenantId, edge.getId(), EdgeEventType.USER,
EdgeEventActionType.CREDENTIALS_UPDATED, userId, null);
}
return Futures.immediateFuture(null);
}
@Override
public ListenableFuture<Void> processDeviceProfileDevicesRequestMsg(TenantId tenantId, Edge edge, DeviceProfileDevicesRequestMsg deviceProfileDevicesRequestMsg) {
log.trace("[{}] processDeviceProfileDevicesRequestMsg [{}][{}]", tenantId, edge.getName(), deviceProfileDevicesRequestMsg);
if (deviceProfileDevicesRequestMsg.getDeviceProfileIdMSB() != 0 && deviceProfileDevicesRequestMsg.getDeviceProfileIdLSB() != 0) {
DeviceProfileId deviceProfileId = new DeviceProfileId(new UUID(deviceProfileDevicesRequestMsg.getDeviceProfileIdMSB(), deviceProfileDevicesRequestMsg.getDeviceProfileIdLSB()));
DeviceProfile deviceProfileById = deviceProfileService.findDeviceProfileById(tenantId, deviceProfileId);
if (deviceProfileById != null) {
syncDevices(tenantId, edge, deviceProfileById.getName());
}
}
return Futures.immediateFuture(null);
}
private void syncDevices(TenantId tenantId, Edge edge, String deviceType) {
log.trace("[{}] syncDevices [{}][{}]", tenantId, edge.getName(), deviceType);
try {
PageLink pageLink = new PageLink(DEFAULT_PAGE_SIZE);
PageData<Device> pageData;
do {
pageData = deviceService.findDevicesByTenantIdAndEdgeIdAndType(tenantId, edge.getId(), deviceType, pageLink);
if (pageData != null && pageData.getData() != null && !pageData.getData().isEmpty()) {
log.trace("[{}] [{}] device(s) are going to be pushed to edge.", edge.getId(), pageData.getData().size());
for (Device device : pageData.getData()) {
saveEdgeEvent(tenantId, edge.getId(), EdgeEventType.DEVICE, EdgeEventActionType.ADDED, device.getId(), null);
}
if (pageData.hasNext()) {
pageLink = pageLink.nextPageLink();
}
}
} while (pageData != null && pageData.hasNext());
} catch (Exception e) {
log.error("Exception during loading edge device(s) on sync!", e);
}
}
@Override
public ListenableFuture<Void> processWidgetBundleTypesRequestMsg(TenantId tenantId, Edge edge,
WidgetBundleTypesRequestMsg widgetBundleTypesRequestMsg) {
log.trace("[{}] processWidgetBundleTypesRequestMsg [{}][{}]", tenantId, edge.getName(), widgetBundleTypesRequestMsg);
if (widgetBundleTypesRequestMsg.getWidgetBundleIdMSB() != 0 && widgetBundleTypesRequestMsg.getWidgetBundleIdLSB() != 0) {
WidgetsBundleId widgetsBundleId = new WidgetsBundleId(new UUID(widgetBundleTypesRequestMsg.getWidgetBundleIdMSB(), widgetBundleTypesRequestMsg.getWidgetBundleIdLSB()));
WidgetsBundle widgetsBundleById = widgetsBundleService.findWidgetsBundleById(tenantId, widgetsBundleId);
if (widgetsBundleById != null) {
List<WidgetType> widgetTypesToPush =
widgetTypeService.findWidgetTypesByTenantIdAndBundleAlias(widgetsBundleById.getTenantId(), widgetsBundleById.getAlias());
for (WidgetType widgetType : widgetTypesToPush) {
saveEdgeEvent(tenantId, edge.getId(), EdgeEventType.WIDGET_TYPE, EdgeEventActionType.ADDED, widgetType.getId(), null);
}
}
}
return Futures.immediateFuture(null);
}
@Override
public ListenableFuture<Void> processEntityViewsRequestMsg(TenantId tenantId, Edge edge, EntityViewsRequestMsg entityViewsRequestMsg) {
log.trace("[{}] processEntityViewsRequestMsg [{}][{}]", tenantId, edge.getName(), entityViewsRequestMsg);
EntityId entityId = EntityIdFactory.getByTypeAndUuid(
EntityType.valueOf(entityViewsRequestMsg.getEntityType()),
new UUID(entityViewsRequestMsg.getEntityIdMSB(), entityViewsRequestMsg.getEntityIdLSB()));
SettableFuture<Void> futureToSet = SettableFuture.create();
Futures.addCallback(entityViewService.findEntityViewsByTenantIdAndEntityIdAsync(tenantId, entityId), new FutureCallback<>() {
@Override
public void onSuccess(@Nullable List<EntityView> entityViews) {
try {
if (entityViews != null && !entityViews.isEmpty()) {
List<ListenableFuture<Boolean>> futures = new ArrayList<>();
for (EntityView entityView : entityViews) {
ListenableFuture<Boolean> future = relationService.checkRelation(tenantId, edge.getId(), entityView.getId(),
EntityRelation.CONTAINS_TYPE, RelationTypeGroup.EDGE);
futures.add(future);
Futures.addCallback(future, new FutureCallback<>() {
@Override
public void onSuccess(@Nullable Boolean result) {
if (Boolean.TRUE.equals(result)) {
saveEdgeEvent(tenantId, edge.getId(), EdgeEventType.ENTITY_VIEW,
EdgeEventActionType.ADDED, entityView.getId(), null);
}
}
@Override
public void onFailure(Throwable t) {
// Do nothing - error handles in allAsList
}
}, dbCallbackExecutorService);
}
Futures.addCallback(Futures.allAsList(futures), new FutureCallback<>() {
@Override
public void onSuccess(@Nullable List<Boolean> result) {
futureToSet.set(null);
}
@Override
public void onFailure(Throwable t) {
log.error("Exception during loading relation [{}] to edge on sync!", t, t);
futureToSet.setException(t);
}
}, dbCallbackExecutorService);
} else {
futureToSet.set(null);
}
} catch (Exception e) {
log.error("Exception during loading relation(s) to edge on sync!", e);
futureToSet.setException(e);
}
}
@Override
public void onFailure(Throwable t) {
log.error("[{}] Can't find entity views by entity id [{}]", tenantId, entityId, t);
futureToSet.setException(t);
}
}, dbCallbackExecutorService);
return futureToSet;
}
private void saveEdgeEvent(TenantId tenantId,
EdgeId edgeId,
EdgeEventType type,
EdgeEventActionType action,
EntityId entityId,
JsonNode body) {
log.trace("Pushing edge event to edge queue. tenantId [{}], edgeId [{}], type [{}], action[{}], entityId [{}], body [{}]",
tenantId, edgeId, type, action, entityId, body);
EdgeEvent edgeEvent = EdgeEventUtils.constructEdgeEvent(tenantId, edgeId, type, action, entityId, body);
edgeEventService.save(edgeEvent);
tbClusterService.onEdgeEventUpdate(tenantId, edgeId);
}
}
| 55.652174 | 188 | 0.622396 |
0e98419f22c000bd79f329bf54fc0b8459b5addd | 1,824 | package jdbc.magnit;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
// Генерация XML из данных базы
// Для создания xml файла нужно использовать технологию JAXB.
public class StoreXML {
// - target - Файл куда будет сохраняться данные.
private File target;
public StoreXML(File target) {
this.target = target;
}
// сохраняет данные из list в файл target
public void save(List<Entry> list) {
Entries entries = new Entries(list);
try {
target.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
JAXBContext jaxbContext = null;
try {
jaxbContext = JAXBContext.newInstance(Entries.class, Entry.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// чтобы переносы строки и пробелы тоже сериализовывались
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// запуск сериализации (что, куда)
System.out.println("сериализация в файл xml");
jaxbMarshaller.marshal(
entries,
target
// System.out // для вывода на экран
);
} catch (JAXBException e) {
e.printStackTrace();
}
}
@XmlRootElement(name = "my_entries")
static class Entries {
@XmlElement(name = "my_entry")
private List<Entry> list;
public Entries() {
}
public Entries(List<Entry> list) {
this.list = list;
}
}
}
| 28.5 | 79 | 0.619518 |
92026842687b538f6acf12a299436d958593bb0d | 7,861 | /*
* Copyright 2012-2019 CodeLibs Project and the Others.
*
* 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.codelibs.elasticsearch.vector.index.mapper;
import static org.elasticsearch.common.xcontent.XContentParserUtils.ensureExpectedToken;
import java.io.IOException;
import java.time.ZoneId;
import java.util.List;
import java.util.Map;
import org.apache.lucene.document.BinaryDocValuesField;
import org.apache.lucene.index.IndexOptions;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.search.DocValuesFieldExistsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
import org.codelibs.elasticsearch.vector.index.fielddata.BitVectorIndexFieldData;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentParser.Token;
import org.elasticsearch.index.fielddata.IndexFieldData;
import org.elasticsearch.index.mapper.ArrayValueMapperParser;
import org.elasticsearch.index.mapper.FieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.Mapper;
import org.elasticsearch.index.mapper.MapperParsingException;
import org.elasticsearch.index.mapper.ParseContext;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.search.DocValueFormat;
/**
* A {@link FieldMapper} for indexing a bit vector.
*/
public class BitVectorFieldMapper extends FieldMapper implements ArrayValueMapperParser {
public static final String CONTENT_TYPE = "bit_vector";
public static final int MAX_DIMS_COUNT = 1024 * 32; //maximum allowed number of dimensions
public static class Defaults {
public static final MappedFieldType FIELD_TYPE = new BitVectorFieldType();
static {
FIELD_TYPE.setTokenized(false);
FIELD_TYPE.setIndexOptions(IndexOptions.NONE);
FIELD_TYPE.setHasDocValues(true);
FIELD_TYPE.setOmitNorms(true);
FIELD_TYPE.freeze();
}
}
public static class Builder extends FieldMapper.Builder<Builder, BitVectorFieldMapper> {
public Builder(final String name) {
super(name, Defaults.FIELD_TYPE, Defaults.FIELD_TYPE);
builder = this;
}
@Override
public BitVectorFieldType fieldType() {
return (BitVectorFieldType) super.fieldType();
}
@Override
public BitVectorFieldMapper build(final BuilderContext context) {
setupFieldType(context);
return new BitVectorFieldMapper(
name, fieldType, defaultFieldType,
context.indexSettings(), multiFieldsBuilder.build(this, context), copyTo);
}
}
public static class TypeParser implements Mapper.TypeParser {
@Override
public Mapper.Builder<?,?> parse(final String name, final Map<String, Object> node, final ParserContext parserContext) throws MapperParsingException {
final BitVectorFieldMapper.Builder builder = new BitVectorFieldMapper.Builder(name);
return builder;
}
}
public static final class BitVectorFieldType extends MappedFieldType {
public BitVectorFieldType() {}
protected BitVectorFieldType(final BitVectorFieldType ref) {
super(ref);
}
@Override
public BitVectorFieldType clone() {
return new BitVectorFieldType(this);
}
@Override
public String typeName() {
return CONTENT_TYPE;
}
@Override
public DocValueFormat docValueFormat(final String format, final ZoneId timeZone) {
throw new UnsupportedOperationException(
"Field [" + name() + "] of type [" + typeName() + "] doesn't support docvalue_fields or aggregations");
}
@Override
public Query existsQuery(final QueryShardContext context) {
return new DocValuesFieldExistsQuery(name());
}
@Override
public IndexFieldData.Builder fielddataBuilder(final String fullyQualifiedIndexName) {
return new BitVectorIndexFieldData.Builder( );
}
@Override
public Query termQuery(final Object value, final QueryShardContext context) {
throw new UnsupportedOperationException(
"Field [" + name() + "] of type [" + typeName() + "] doesn't support queries");
}
}
private BitVectorFieldMapper(final String simpleName, final MappedFieldType fieldType, final MappedFieldType defaultFieldType,
final Settings indexSettings, final MultiFields multiFields, final CopyTo copyTo) {
super(simpleName, fieldType, defaultFieldType, indexSettings, multiFields, copyTo);
assert fieldType.indexOptions() == IndexOptions.NONE;
}
@Override
protected BitVectorFieldMapper clone() {
return (BitVectorFieldMapper) super.clone();
}
@Override
public BitVectorFieldType fieldType() {
return (BitVectorFieldType) super.fieldType();
}
@Override
public void parse(final ParseContext context) throws IOException {
if (context.externalValueSet()) {
throw new IllegalArgumentException("Field [" + name() + "] of type [" + typeName() + "] can't be used in multi-fields");
}
byte[] buf = new byte[0];
int pos = 7;
int offset = 0;
int dim = 0;
for (Token token = context.parser().nextToken(); token != Token.END_ARRAY; token = context.parser().nextToken()) {
ensureExpectedToken(Token.VALUE_NUMBER, token, context.parser()::getTokenLocation);
short value = context.parser().shortValue(true);
if (buf.length < (offset + 1)) {
buf = ArrayUtil.grow(buf, offset + 1);
}
if (value != 0) {
value = 1;
}
buf[offset] |= (byte) (value << pos);
pos--;
if (pos < 0) {
offset++;
pos = 7;
}
if (dim++ >= MAX_DIMS_COUNT) {
throw new IllegalArgumentException("Field [" + name() + "] of type [" + typeName()
+ "] has exceeded the maximum allowed number of dimensions of [" + MAX_DIMS_COUNT + "]");
}
}
offset++;
while (offset % 4 != 0) {
buf = ArrayUtil.grow(buf, offset + 1);
buf[offset] = 0;
offset++;
}
final BinaryDocValuesField field = new BinaryDocValuesField(fieldType().name(), new BytesRef(buf, 0, offset));
if (context.doc().getByKey(fieldType().name()) != null) {
throw new IllegalArgumentException("Field [" + name() + "] of type [" + typeName() +
"] doesn't not support indexing multiple values for the same field in the same document");
}
context.doc().addWithKey(fieldType().name(), field);
}
@Override
protected void parseCreateField(final ParseContext context, final List<IndexableField> fields) {
throw new UnsupportedOperationException("parse is implemented directly");
}
@Override
protected String contentType() {
return CONTENT_TYPE;
}
}
| 38.346341 | 158 | 0.657932 |
77d4f7e3cb26a4b952267fd2ac9d436182602587 | 795 | package net.collabsoft.clustering.jira.cache;
public class LocalCacheManager extends com.atlassian.cache.ehcache.EhCacheManager {
// ----------------------------------------------------------------------------------------------- Constructor
public LocalCacheManager() {
}
// ----------------------------------------------------------------------------------------------- Getters & Setters
// ----------------------------------------------------------------------------------------------- Public methods
// ----------------------------------------------------------------------------------------------- Private methods
// ----------------------------------------------------------------------------------------------- Private Getters & Setters
}
| 31.8 | 128 | 0.261635 |
8ded6c465e97cabd3b78bf012bd2df60381591c1 | 4,780 | /**
* Copyright (C) 2018 DANS - Data Archiving and Networked Services ([email protected])
*
* 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 nl.knaw.dans.build;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import static org.junit.Assert.assertEquals;
public class GenerateRpmScriptsTest {
private Path scriptsDir = Paths.get("src/test/resources/scripts");
private Path includesDir = Paths.get("src/test/resources/includes");
private Path targetDir = Paths.get("target/test/", getClass().getSimpleName());
private Path expectedOutputsDir = Paths.get("src/test/resources/expectedOutputs");
private String readFileToString(Path p) throws IOException {
return new String(Files.readAllBytes(p), StandardCharsets.UTF_8);
}
private void assertFilesEqual(Path expected, Path actual) throws IOException {
String expectedText = readFileToString(expected);
String actualText = readFileToString(actual);
assertEquals(expectedText, actualText);
}
@Before public void setUp() throws IOException {
Files.createDirectories(targetDir);
}
@Test public void emptyScriptShouldStayTheSame() throws Exception {
final String FILENAME = "DOES-NOT-EXIST.txt";
GenerateRpmScripts.execute(scriptsDir.resolve(FILENAME), includesDir, targetDir);
assertEquals(0L, Files.size(targetDir.resolve(FILENAME)));
}
@Test public void emptyIncludeShouldOnyRemoveIncludeDirective() throws Exception {
final String FILENAME = "empty-include.txt";
GenerateRpmScripts.execute(scriptsDir.resolve(FILENAME), includesDir, targetDir);
assertFilesEqual(expectedOutputsDir.resolve(FILENAME), targetDir.resolve(FILENAME));
}
@Test(expected = NoSuchFileException.class)
public void nonExistentIncludeShouldResultInFileNotFoundException() throws Exception {
final String FILENAME = "include-not-found.txt";
GenerateRpmScripts.execute(scriptsDir.resolve(FILENAME), includesDir, targetDir);
}
@Test public void multiIncludeShouldIncludeInOrder() throws Exception {
final String FILENAME = "multi-include-consecutive.txt";
GenerateRpmScripts.execute(scriptsDir.resolve(FILENAME), includesDir, targetDir);
assertFilesEqual(expectedOutputsDir.resolve(FILENAME), targetDir.resolve(FILENAME));
}
@Test public void multiIncludeDistributedShouldLeaveTextBetweenIncludesInPlace() throws Exception {
final String FILENAME = "multi-include-distributed.txt";
GenerateRpmScripts.execute(scriptsDir.resolve(FILENAME), includesDir, targetDir);
assertFilesEqual(expectedOutputsDir.resolve(FILENAME), targetDir.resolve(FILENAME));
}
@Test public void scriptWithNoIncludesShouldStayTheSame() throws Exception {
final String FILENAME = "no-includes.txt";
GenerateRpmScripts.execute(scriptsDir.resolve(FILENAME), includesDir, targetDir);
assertFilesEqual(scriptsDir.resolve(FILENAME), targetDir.resolve(FILENAME));
}
@Test public void includeAtEnd() throws Exception {
final String FILENAME = "one-include-end.txt";
GenerateRpmScripts.execute(scriptsDir.resolve(FILENAME), includesDir, targetDir);
assertFilesEqual(expectedOutputsDir.resolve(FILENAME), targetDir.resolve(FILENAME));
}
@Test public void includeInMiddle() throws Exception {
final String FILENAME = "one-include-middle.txt";
GenerateRpmScripts.execute(scriptsDir.resolve(FILENAME), includesDir, targetDir);
assertFilesEqual(expectedOutputsDir.resolve(FILENAME), targetDir.resolve(FILENAME));
}
@Test public void includeStart() throws Exception {
final String FILENAME = "one-include-start.txt";
GenerateRpmScripts.execute(scriptsDir.resolve(FILENAME), includesDir, targetDir);
assertFilesEqual(expectedOutputsDir.resolve(FILENAME), targetDir.resolve(FILENAME));
}
@Test public void nonExistentScriptResultsInEmptyResult() throws Exception {
final String FILENAME = "DOES-NOT-EXIST.txt";
GenerateRpmScripts.execute(scriptsDir.resolve(FILENAME), includesDir, targetDir);
assertFilesEqual(expectedOutputsDir.resolve(FILENAME), targetDir.resolve(FILENAME));
}
}
| 43.063063 | 101 | 0.774895 |
3869f4e0976e9e719f94d52ee23aeb1ebc42a923 | 358 | package com.goufn.permission.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.goufn.permission.common.page.PageRequest;
import com.goufn.permission.common.page.PageResult;
import com.goufn.permission.model.SysLog;
public interface SysLogService extends IService<SysLog> {
PageResult findPage(PageRequest pageRequest);
}
| 29.833333 | 59 | 0.829609 |
7c374d1853098dc57427d715ec0c779b0123a14a | 1,276 | package com.lyd.mall.order.listener;
/**
* @Author Liuyunda
* @Date 2021/6/16 20:17
* @Email [email protected]
* @Description: TODO
*/
import com.lyd.mall.order.entity.OrderEntity;
import com.lyd.mall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.Date;
@RabbitListener(queues = "order.release.order.queue")
@Service
public class OrderCloseListener {
@Autowired
OrderService orderService;
@RabbitHandler
public void listener(OrderEntity entity, Channel channel, Message message) throws IOException {
System.out.println("收到过期的订单信息:准备关闭订单:"+entity.getOrderSn()+",Time:"+new Date());
try{
orderService.closeOrder(entity);
channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
} catch (Exception e) {
e.printStackTrace();
channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
}
}
}
| 32.717949 | 99 | 0.737461 |
91ba0a58049471f804570fbea3c7486fc3071c2c | 25,719 | package com.cooey.android.vitals.dao;
import android.arch.lifecycle.ComputableLiveData;
import android.arch.lifecycle.LiveData;
import android.arch.persistence.db.SupportSQLiteStatement;
import android.arch.persistence.room.EntityDeletionOrUpdateAdapter;
import android.arch.persistence.room.EntityInsertionAdapter;
import android.arch.persistence.room.InvalidationTracker.Observer;
import android.arch.persistence.room.RoomDatabase;
import android.arch.persistence.room.RoomSQLiteQuery;
import android.arch.persistence.room.SharedSQLiteStatement;
import android.database.Cursor;
import android.support.annotation.NonNull;
import com.cooey.android.vitals.VitalBlueprint;
import com.cooey.android.vitals.converters.Converter;
import com.facebook.share.internal.ShareConstants;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class VitalBlueprintDao_Impl implements VitalBlueprintDao {
private final RoomDatabase __db;
private final EntityDeletionOrUpdateAdapter __deletionAdapterOfVitalBlueprint;
private final EntityInsertionAdapter __insertionAdapterOfVitalBlueprint;
private final SharedSQLiteStatement __preparedStmtOfDeleteAll;
public VitalBlueprintDao_Impl(RoomDatabase __db) {
this.__db = __db;
this.__insertionAdapterOfVitalBlueprint = new EntityInsertionAdapter<VitalBlueprint>(__db) {
public String createQuery() {
return "INSERT OR REPLACE INTO `vitalBlueprints`(`iconURL`,`fields`,`id`,`name`,`type`,`isGraphRequired`,`isPrimary`,`isSynced`) VALUES (?,?,?,?,?,?,?,?)";
}
public void bind(SupportSQLiteStatement stmt, VitalBlueprint value) {
Integer _tmp_1;
Integer _tmp_2;
Integer _tmp_3 = null;
int i = 1;
if (value.getIconURL() == null) {
stmt.bindNull(1);
} else {
stmt.bindString(1, value.getIconURL());
}
String _tmp = Converter.convertFieldListToString(value.getFields());
if (_tmp == null) {
stmt.bindNull(2);
} else {
stmt.bindString(2, _tmp);
}
if (value.getId() == null) {
stmt.bindNull(3);
} else {
stmt.bindString(3, value.getId());
}
if (value.getName() == null) {
stmt.bindNull(4);
} else {
stmt.bindString(4, value.getName());
}
if (value.getType() == null) {
stmt.bindNull(5);
} else {
stmt.bindString(5, value.getType());
}
if (value.isGraphRequired() == null) {
_tmp_1 = null;
} else {
_tmp_1 = Integer.valueOf(value.isGraphRequired().booleanValue() ? 1 : 0);
}
if (_tmp_1 == null) {
stmt.bindNull(6);
} else {
stmt.bindLong(6, (long) _tmp_1.intValue());
}
if (value.isPrimary() == null) {
_tmp_2 = null;
} else {
_tmp_2 = Integer.valueOf(value.isPrimary().booleanValue() ? 1 : 0);
}
if (_tmp_2 == null) {
stmt.bindNull(7);
} else {
stmt.bindLong(7, (long) _tmp_2.intValue());
}
if (value.isSynced() != null) {
if (!value.isSynced().booleanValue()) {
i = 0;
}
_tmp_3 = Integer.valueOf(i);
}
if (_tmp_3 == null) {
stmt.bindNull(8);
} else {
stmt.bindLong(8, (long) _tmp_3.intValue());
}
}
};
this.__deletionAdapterOfVitalBlueprint = new EntityDeletionOrUpdateAdapter<VitalBlueprint>(__db) {
public String createQuery() {
return "DELETE FROM `vitalBlueprints` WHERE `id` = ?";
}
public void bind(SupportSQLiteStatement stmt, VitalBlueprint value) {
if (value.getId() == null) {
stmt.bindNull(1);
} else {
stmt.bindString(1, value.getId());
}
}
};
this.__preparedStmtOfDeleteAll = new SharedSQLiteStatement(__db) {
public String createQuery() {
String _query = "DELETE FROM vitalBlueprints";
return "DELETE FROM vitalBlueprints";
}
};
}
public void insert(VitalBlueprint vitalBlueprint) {
this.__db.beginTransaction();
try {
this.__insertionAdapterOfVitalBlueprint.insert(vitalBlueprint);
this.__db.setTransactionSuccessful();
} finally {
this.__db.endTransaction();
}
}
public void insert(List<VitalBlueprint> vitalBlueprints) {
this.__db.beginTransaction();
try {
this.__insertionAdapterOfVitalBlueprint.insert(vitalBlueprints);
this.__db.setTransactionSuccessful();
} finally {
this.__db.endTransaction();
}
}
public void delete(VitalBlueprint vitalBlueprint) {
this.__db.beginTransaction();
try {
this.__deletionAdapterOfVitalBlueprint.handle(vitalBlueprint);
this.__db.setTransactionSuccessful();
} finally {
this.__db.endTransaction();
}
}
public int deleteAll() {
SupportSQLiteStatement _stmt = this.__preparedStmtOfDeleteAll.acquire();
this.__db.beginTransaction();
try {
int _result = _stmt.executeUpdateDelete();
this.__db.setTransactionSuccessful();
return _result;
} finally {
this.__db.endTransaction();
this.__preparedStmtOfDeleteAll.release(_stmt);
}
}
public LiveData<List<VitalBlueprint>> getAll() {
String _sql = "SELECT * FROM vitalBlueprints";
final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire("SELECT * FROM vitalBlueprints", 0);
return new ComputableLiveData<List<VitalBlueprint>>() {
private Observer _observer;
protected List<VitalBlueprint> compute() {
if (this._observer == null) {
this._observer = new Observer("vitalBlueprints", new String[0]) {
public void onInvalidated(@NonNull Set<String> set) {
C08204.this.invalidate();
}
};
VitalBlueprintDao_Impl.this.__db.getInvalidationTracker().addWeakObserver(this._observer);
}
Cursor _cursor = VitalBlueprintDao_Impl.this.__db.query(_statement);
try {
int _cursorIndexOfIconURL = _cursor.getColumnIndexOrThrow("iconURL");
int _cursorIndexOfFields = _cursor.getColumnIndexOrThrow("fields");
int _cursorIndexOfId = _cursor.getColumnIndexOrThrow(ShareConstants.WEB_DIALOG_PARAM_ID);
int _cursorIndexOfName = _cursor.getColumnIndexOrThrow("name");
int _cursorIndexOfType = _cursor.getColumnIndexOrThrow("type");
int _cursorIndexOfIsGraphRequired = _cursor.getColumnIndexOrThrow("isGraphRequired");
int _cursorIndexOfIsPrimary = _cursor.getColumnIndexOrThrow("isPrimary");
int _cursorIndexOfIsSynced = _cursor.getColumnIndexOrThrow("isSynced");
List<VitalBlueprint> arrayList = new ArrayList(_cursor.getCount());
while (_cursor.moveToNext()) {
Integer _tmp;
Boolean _tmpIsGraphRequired;
Integer _tmp_1;
Boolean _tmpIsPrimary;
Integer _tmp_2;
Boolean _tmpIsSynced;
String _tmpId = _cursor.getString(_cursorIndexOfId);
String _tmpName = _cursor.getString(_cursorIndexOfName);
String _tmpType = _cursor.getString(_cursorIndexOfType);
if (_cursor.isNull(_cursorIndexOfIsGraphRequired)) {
_tmp = null;
} else {
_tmp = Integer.valueOf(_cursor.getInt(_cursorIndexOfIsGraphRequired));
}
if (_tmp == null) {
_tmpIsGraphRequired = null;
} else {
_tmpIsGraphRequired = Boolean.valueOf(_tmp.intValue() != 0);
}
if (_cursor.isNull(_cursorIndexOfIsPrimary)) {
_tmp_1 = null;
} else {
_tmp_1 = Integer.valueOf(_cursor.getInt(_cursorIndexOfIsPrimary));
}
if (_tmp_1 == null) {
_tmpIsPrimary = null;
} else {
_tmpIsPrimary = Boolean.valueOf(_tmp_1.intValue() != 0);
}
if (_cursor.isNull(_cursorIndexOfIsSynced)) {
_tmp_2 = null;
} else {
_tmp_2 = Integer.valueOf(_cursor.getInt(_cursorIndexOfIsSynced));
}
if (_tmp_2 == null) {
_tmpIsSynced = null;
} else {
_tmpIsSynced = Boolean.valueOf(_tmp_2.intValue() != 0);
}
VitalBlueprint _item = new VitalBlueprint(_tmpId, _tmpName, _tmpType, _tmpIsGraphRequired, _tmpIsPrimary, _tmpIsSynced);
_item.setIconURL(_cursor.getString(_cursorIndexOfIconURL));
_item.setFields(Converter.convertStringToFieldList(_cursor.getString(_cursorIndexOfFields)));
arrayList.add(_item);
}
return arrayList;
} finally {
_cursor.close();
}
}
protected void finalize() {
_statement.release();
}
}.getLiveData();
}
public List<VitalBlueprint> getAllSync() {
String _sql = "SELECT * FROM vitalBlueprints";
RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire("SELECT * FROM vitalBlueprints", 0);
Cursor _cursor = this.__db.query(_statement);
try {
int _cursorIndexOfIconURL = _cursor.getColumnIndexOrThrow("iconURL");
int _cursorIndexOfFields = _cursor.getColumnIndexOrThrow("fields");
int _cursorIndexOfId = _cursor.getColumnIndexOrThrow(ShareConstants.WEB_DIALOG_PARAM_ID);
int _cursorIndexOfName = _cursor.getColumnIndexOrThrow("name");
int _cursorIndexOfType = _cursor.getColumnIndexOrThrow("type");
int _cursorIndexOfIsGraphRequired = _cursor.getColumnIndexOrThrow("isGraphRequired");
int _cursorIndexOfIsPrimary = _cursor.getColumnIndexOrThrow("isPrimary");
int _cursorIndexOfIsSynced = _cursor.getColumnIndexOrThrow("isSynced");
List<VitalBlueprint> arrayList = new ArrayList(_cursor.getCount());
while (_cursor.moveToNext()) {
Integer _tmp;
Boolean _tmpIsGraphRequired;
Integer _tmp_1;
Boolean _tmpIsPrimary;
Integer _tmp_2;
Boolean _tmpIsSynced;
String _tmpId = _cursor.getString(_cursorIndexOfId);
String _tmpName = _cursor.getString(_cursorIndexOfName);
String _tmpType = _cursor.getString(_cursorIndexOfType);
if (_cursor.isNull(_cursorIndexOfIsGraphRequired)) {
_tmp = null;
} else {
_tmp = Integer.valueOf(_cursor.getInt(_cursorIndexOfIsGraphRequired));
}
if (_tmp == null) {
_tmpIsGraphRequired = null;
} else {
_tmpIsGraphRequired = Boolean.valueOf(_tmp.intValue() != 0);
}
if (_cursor.isNull(_cursorIndexOfIsPrimary)) {
_tmp_1 = null;
} else {
_tmp_1 = Integer.valueOf(_cursor.getInt(_cursorIndexOfIsPrimary));
}
if (_tmp_1 == null) {
_tmpIsPrimary = null;
} else {
_tmpIsPrimary = Boolean.valueOf(_tmp_1.intValue() != 0);
}
if (_cursor.isNull(_cursorIndexOfIsSynced)) {
_tmp_2 = null;
} else {
_tmp_2 = Integer.valueOf(_cursor.getInt(_cursorIndexOfIsSynced));
}
if (_tmp_2 == null) {
_tmpIsSynced = null;
} else {
_tmpIsSynced = Boolean.valueOf(_tmp_2.intValue() != 0);
}
VitalBlueprint _item = new VitalBlueprint(_tmpId, _tmpName, _tmpType, _tmpIsGraphRequired, _tmpIsPrimary, _tmpIsSynced);
_item.setIconURL(_cursor.getString(_cursorIndexOfIconURL));
_item.setFields(Converter.convertStringToFieldList(_cursor.getString(_cursorIndexOfFields)));
arrayList.add(_item);
}
return arrayList;
} finally {
_cursor.close();
_statement.release();
}
}
public LiveData<List<VitalBlueprint>> getAll(boolean isPrimary) {
int _tmp = 1;
String _sql = "SELECT * FROM vitalBlueprints WHERE isPrimary = ?";
final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire("SELECT * FROM vitalBlueprints WHERE isPrimary = ?", 1);
if (!isPrimary) {
_tmp = 0;
}
_statement.bindLong(1, (long) _tmp);
return new ComputableLiveData<List<VitalBlueprint>>() {
private Observer _observer;
protected List<VitalBlueprint> compute() {
if (this._observer == null) {
this._observer = new Observer("vitalBlueprints", new String[0]) {
public void onInvalidated(@NonNull Set<String> set) {
C08225.this.invalidate();
}
};
VitalBlueprintDao_Impl.this.__db.getInvalidationTracker().addWeakObserver(this._observer);
}
Cursor _cursor = VitalBlueprintDao_Impl.this.__db.query(_statement);
try {
int _cursorIndexOfIconURL = _cursor.getColumnIndexOrThrow("iconURL");
int _cursorIndexOfFields = _cursor.getColumnIndexOrThrow("fields");
int _cursorIndexOfId = _cursor.getColumnIndexOrThrow(ShareConstants.WEB_DIALOG_PARAM_ID);
int _cursorIndexOfName = _cursor.getColumnIndexOrThrow("name");
int _cursorIndexOfType = _cursor.getColumnIndexOrThrow("type");
int _cursorIndexOfIsGraphRequired = _cursor.getColumnIndexOrThrow("isGraphRequired");
int _cursorIndexOfIsPrimary = _cursor.getColumnIndexOrThrow("isPrimary");
int _cursorIndexOfIsSynced = _cursor.getColumnIndexOrThrow("isSynced");
List<VitalBlueprint> arrayList = new ArrayList(_cursor.getCount());
while (_cursor.moveToNext()) {
Integer _tmp_1;
Boolean _tmpIsGraphRequired;
Integer _tmp_2;
Boolean _tmpIsPrimary;
Integer _tmp_3;
Boolean _tmpIsSynced;
String _tmpId = _cursor.getString(_cursorIndexOfId);
String _tmpName = _cursor.getString(_cursorIndexOfName);
String _tmpType = _cursor.getString(_cursorIndexOfType);
if (_cursor.isNull(_cursorIndexOfIsGraphRequired)) {
_tmp_1 = null;
} else {
_tmp_1 = Integer.valueOf(_cursor.getInt(_cursorIndexOfIsGraphRequired));
}
if (_tmp_1 == null) {
_tmpIsGraphRequired = null;
} else {
_tmpIsGraphRequired = Boolean.valueOf(_tmp_1.intValue() != 0);
}
if (_cursor.isNull(_cursorIndexOfIsPrimary)) {
_tmp_2 = null;
} else {
_tmp_2 = Integer.valueOf(_cursor.getInt(_cursorIndexOfIsPrimary));
}
if (_tmp_2 == null) {
_tmpIsPrimary = null;
} else {
_tmpIsPrimary = Boolean.valueOf(_tmp_2.intValue() != 0);
}
if (_cursor.isNull(_cursorIndexOfIsSynced)) {
_tmp_3 = null;
} else {
_tmp_3 = Integer.valueOf(_cursor.getInt(_cursorIndexOfIsSynced));
}
if (_tmp_3 == null) {
_tmpIsSynced = null;
} else {
_tmpIsSynced = Boolean.valueOf(_tmp_3.intValue() != 0);
}
VitalBlueprint _item = new VitalBlueprint(_tmpId, _tmpName, _tmpType, _tmpIsGraphRequired, _tmpIsPrimary, _tmpIsSynced);
_item.setIconURL(_cursor.getString(_cursorIndexOfIconURL));
_item.setFields(Converter.convertStringToFieldList(_cursor.getString(_cursorIndexOfFields)));
arrayList.add(_item);
}
return arrayList;
} finally {
_cursor.close();
}
}
protected void finalize() {
_statement.release();
}
}.getLiveData();
}
public List<VitalBlueprint> getAllSync(boolean isPrimary) {
String _sql = "SELECT * FROM vitalBlueprints WHERE isPrimary = ?";
RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire("SELECT * FROM vitalBlueprints WHERE isPrimary = ?", 1);
_statement.bindLong(1, (long) (isPrimary ? 1 : 0));
Cursor _cursor = this.__db.query(_statement);
try {
int _cursorIndexOfIconURL = _cursor.getColumnIndexOrThrow("iconURL");
int _cursorIndexOfFields = _cursor.getColumnIndexOrThrow("fields");
int _cursorIndexOfId = _cursor.getColumnIndexOrThrow(ShareConstants.WEB_DIALOG_PARAM_ID);
int _cursorIndexOfName = _cursor.getColumnIndexOrThrow("name");
int _cursorIndexOfType = _cursor.getColumnIndexOrThrow("type");
int _cursorIndexOfIsGraphRequired = _cursor.getColumnIndexOrThrow("isGraphRequired");
int _cursorIndexOfIsPrimary = _cursor.getColumnIndexOrThrow("isPrimary");
int _cursorIndexOfIsSynced = _cursor.getColumnIndexOrThrow("isSynced");
List<VitalBlueprint> arrayList = new ArrayList(_cursor.getCount());
while (_cursor.moveToNext()) {
Integer _tmp_1;
Boolean _tmpIsGraphRequired;
Integer _tmp_2;
Boolean _tmpIsPrimary;
Integer _tmp_3;
Boolean _tmpIsSynced;
String _tmpId = _cursor.getString(_cursorIndexOfId);
String _tmpName = _cursor.getString(_cursorIndexOfName);
String _tmpType = _cursor.getString(_cursorIndexOfType);
if (_cursor.isNull(_cursorIndexOfIsGraphRequired)) {
_tmp_1 = null;
} else {
_tmp_1 = Integer.valueOf(_cursor.getInt(_cursorIndexOfIsGraphRequired));
}
if (_tmp_1 == null) {
_tmpIsGraphRequired = null;
} else {
_tmpIsGraphRequired = Boolean.valueOf(_tmp_1.intValue() != 0);
}
if (_cursor.isNull(_cursorIndexOfIsPrimary)) {
_tmp_2 = null;
} else {
_tmp_2 = Integer.valueOf(_cursor.getInt(_cursorIndexOfIsPrimary));
}
if (_tmp_2 == null) {
_tmpIsPrimary = null;
} else {
_tmpIsPrimary = Boolean.valueOf(_tmp_2.intValue() != 0);
}
if (_cursor.isNull(_cursorIndexOfIsSynced)) {
_tmp_3 = null;
} else {
_tmp_3 = Integer.valueOf(_cursor.getInt(_cursorIndexOfIsSynced));
}
if (_tmp_3 == null) {
_tmpIsSynced = null;
} else {
_tmpIsSynced = Boolean.valueOf(_tmp_3.intValue() != 0);
}
VitalBlueprint _item = new VitalBlueprint(_tmpId, _tmpName, _tmpType, _tmpIsGraphRequired, _tmpIsPrimary, _tmpIsSynced);
_item.setIconURL(_cursor.getString(_cursorIndexOfIconURL));
_item.setFields(Converter.convertStringToFieldList(_cursor.getString(_cursorIndexOfFields)));
arrayList.add(_item);
}
return arrayList;
} finally {
_cursor.close();
_statement.release();
}
}
public VitalBlueprint getVitalBlueprintForType(String type) {
String _sql = "SELECT * FROM vitalBlueprints WHERE type = ? LIMIT 1";
RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire("SELECT * FROM vitalBlueprints WHERE type = ? LIMIT 1", 1);
if (type == null) {
_statement.bindNull(1);
} else {
_statement.bindString(1, type);
}
Cursor _cursor = this.__db.query(_statement);
try {
VitalBlueprint _result;
int _cursorIndexOfIconURL = _cursor.getColumnIndexOrThrow("iconURL");
int _cursorIndexOfFields = _cursor.getColumnIndexOrThrow("fields");
int _cursorIndexOfId = _cursor.getColumnIndexOrThrow(ShareConstants.WEB_DIALOG_PARAM_ID);
int _cursorIndexOfName = _cursor.getColumnIndexOrThrow("name");
int _cursorIndexOfType = _cursor.getColumnIndexOrThrow("type");
int _cursorIndexOfIsGraphRequired = _cursor.getColumnIndexOrThrow("isGraphRequired");
int _cursorIndexOfIsPrimary = _cursor.getColumnIndexOrThrow("isPrimary");
int _cursorIndexOfIsSynced = _cursor.getColumnIndexOrThrow("isSynced");
if (_cursor.moveToFirst()) {
Integer _tmp;
Boolean _tmpIsGraphRequired;
Integer _tmp_1;
Boolean _tmpIsPrimary;
Integer _tmp_2;
Boolean _tmpIsSynced;
String _tmpId = _cursor.getString(_cursorIndexOfId);
String _tmpName = _cursor.getString(_cursorIndexOfName);
String _tmpType = _cursor.getString(_cursorIndexOfType);
if (_cursor.isNull(_cursorIndexOfIsGraphRequired)) {
_tmp = null;
} else {
_tmp = Integer.valueOf(_cursor.getInt(_cursorIndexOfIsGraphRequired));
}
if (_tmp == null) {
_tmpIsGraphRequired = null;
} else {
_tmpIsGraphRequired = Boolean.valueOf(_tmp.intValue() != 0);
}
if (_cursor.isNull(_cursorIndexOfIsPrimary)) {
_tmp_1 = null;
} else {
_tmp_1 = Integer.valueOf(_cursor.getInt(_cursorIndexOfIsPrimary));
}
if (_tmp_1 == null) {
_tmpIsPrimary = null;
} else {
_tmpIsPrimary = Boolean.valueOf(_tmp_1.intValue() != 0);
}
if (_cursor.isNull(_cursorIndexOfIsSynced)) {
_tmp_2 = null;
} else {
_tmp_2 = Integer.valueOf(_cursor.getInt(_cursorIndexOfIsSynced));
}
if (_tmp_2 == null) {
_tmpIsSynced = null;
} else {
_tmpIsSynced = Boolean.valueOf(_tmp_2.intValue() != 0);
}
_result = new VitalBlueprint(_tmpId, _tmpName, _tmpType, _tmpIsGraphRequired, _tmpIsPrimary, _tmpIsSynced);
_result.setIconURL(_cursor.getString(_cursorIndexOfIconURL));
_result.setFields(Converter.convertStringToFieldList(_cursor.getString(_cursorIndexOfFields)));
} else {
_result = null;
}
_cursor.close();
_statement.release();
return _result;
} catch (Throwable th) {
_cursor.close();
_statement.release();
}
}
}
| 47.627778 | 171 | 0.535985 |
5d72ddde2c809062555c9458539dc013a7a0aad9 | 633 | package io.stat.nabuproject.core.net;
/**
* An exception that is thrown when a network action cannot be completed due to the fact
* that the node its directed at is leaving the cluster.
*
* @author Ilya Ostrovskiy (https://github.com/iostat/)
*/
public class NodeLeavingException extends Exception {
public NodeLeavingException() {
super();
}
public NodeLeavingException(String message) {
super(message);
}
public NodeLeavingException(Throwable cause) {
super(cause);
}
public NodeLeavingException(String message, Throwable cause) {
super(message, cause);
}
}
| 24.346154 | 88 | 0.684044 |
69027e0bdb34b14afa7d3c0278b1c10965d5e785 | 131 | package com.xhc.dao;
import com.xhc.model.Admin;
public interface IAdminDAO {
//校验登录
public Admin checkAdmin(Admin admin);
}
| 14.555556 | 39 | 0.740458 |
8c644d3303db07fa5b93524fca12757de8568ae3 | 1,719 | /*
* Copyright (c) 2018 CA. All rights reserved.
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
package com.ca.apim.gateway.cagatewayconfig.util.entity;
/**
* Constants for Gateway entity types supported by the plugin.
*/
@SuppressWarnings("squid:S2068") // sonarcloud believes this is a hardcoded password
public class EntityTypes {
public static final String CLUSTER_PROPERTY_TYPE = "CLUSTER_PROPERTY";
public static final String LISTEN_PORT_TYPE = "SSG_CONNECTOR";
public static final String ENCAPSULATED_ASSERTION_TYPE = "ENCAPSULATED_ASSERTION";
public static final String FOLDER_TYPE = "FOLDER";
public static final String POLICY_BACKED_SERVICE_TYPE = "POLICY_BACKED_SERVICE";
public static final String SERVICE_TYPE = "SERVICE";
public static final String POLICY_TYPE = "POLICY";
public static final String ID_PROVIDER_CONFIG_TYPE = "ID_PROVIDER_CONFIG";
public static final String STORED_PASSWORD_TYPE = "SECURE_PASSWORD";
public static final String JDBC_CONNECTION = "JDBC_CONNECTION";
public static final String SSG_ACTIVE_CONNECTOR = "SSG_ACTIVE_CONNECTOR";
public static final String TRUSTED_CERT_TYPE = "TRUSTED_CERT";
public static final String PRIVATE_KEY_TYPE = "SSG_KEY_ENTRY";
public static final String CASSANDRA_CONNECTION_TYPE = "CASSANDRA_CONFIGURATION";
public static final String SCHEDULED_TASK_TYPE = "SCHEDULED_TASK";
public static final String JMS_DESTINATION_TYPE = "JMS_ENDPOINT";
public static final String SOAP_RESOURCE_TYPE = "SOAP_RESOURCE";
public static final String GENERIC_TYPE = "GENERIC";
private EntityTypes() { }
}
| 47.75 | 86 | 0.773124 |
6c3fb06d8d701a154ab385122d9edf9550209cc9 | 474 | package com.wy.common;
import org.apache.hadoop.hbase.util.Bytes;
/**
* 常量配置
*
* @author ParadiseWY
* @date 2020-11-10 16:53:39
* @git {@link https://github.com/mygodness100}
*/
public interface Constants {
/** 微博内容表的表名 */
byte[] TABLE_CONTENT = Bytes.toBytes("weibo:content");
/** 微博用户关系表的表名 */
byte[] TABLE_RELATIONS = Bytes.toBytes("weibo:relations");
/** 微博收件箱表的表名 */
byte[] TABLE_RECEIVE_CONTENT_EMAIL = Bytes.toBytes("weibo:receive_content_email");
} | 21.545455 | 83 | 0.696203 |
8807bef7c163834c3bbd39b23beb45af430b6115 | 19,699 | /**
* 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.openejb.jee.wls;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.namespace.QName;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the org.apache.openejb.jee.wls package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
private final static QName _FieldGroupCmpField_QNAME = new QName("http://www.bea.com/ns/weblogic/90", "cmp-field");
private final static QName _FieldGroupCmrField_QNAME = new QName("http://www.bea.com/ns/weblogic/90", "cmr-field");
private final static QName _SecurityRoleAssignmentPrincipalName_QNAME = new QName("http://www.bea.com/ns/weblogic/90", "principal-name");
private final static QName _WeblogicEjbJar_QNAME = new QName("http://www.bea.com/ns/weblogic/90", "weblogic-ejb-jar");
private final static QName _WeblogicRdbmsRelationWeblogicRelationshipRole_QNAME = new QName("http://www.bea.com/ns/weblogic/90", "weblogic-relationship-role");
private final static QName _WeblogicRdbmsRelationTableName_QNAME = new QName("http://www.bea.com/ns/weblogic/90", "table-name");
private final static QName _WeblogicRdbmsRelationRelationName_QNAME = new QName("http://www.bea.com/ns/weblogic/90", "relation-name");
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.apache.openejb.jee.wls
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link Description }
*
*/
public Description createDescription() {
return new Description();
}
/**
* Create an instance of {@link StatefulSessionClustering }
*
*/
public StatefulSessionClustering createStatefulSessionClustering() {
return new StatefulSessionClustering();
}
/**
* Create an instance of {@link InvalidationTarget }
*
*/
public InvalidationTarget createInvalidationTarget() {
return new InvalidationTarget();
}
/**
* Create an instance of {@link ResponseTimeRequestClass }
*
*/
public ResponseTimeRequestClass createResponseTimeRequestClass() {
return new ResponseTimeRequestClass();
}
/**
* Create an instance of {@link ResourceDescription }
*
*/
public ResourceDescription createResourceDescription() {
return new ResourceDescription();
}
/**
* Create an instance of {@link RelationshipRoleMap }
*
*/
public RelationshipRoleMap createRelationshipRoleMap() {
return new RelationshipRoleMap();
}
/**
* Create an instance of {@link WorkManagerShutdownTrigger }
*
*/
public WorkManagerShutdownTrigger createWorkManagerShutdownTrigger() {
return new WorkManagerShutdownTrigger();
}
/**
* Create an instance of {@link EjbQlQuery }
*
*/
public EjbQlQuery createEjbQlQuery() {
return new EjbQlQuery();
}
/**
* Create an instance of {@link ResourceEnvDescription }
*
*/
public ResourceEnvDescription createResourceEnvDescription() {
return new ResourceEnvDescription();
}
/**
* Create an instance of {@link CachingName }
*
*/
public CachingName createCachingName() {
return new CachingName();
}
/**
* Create an instance of {@link WeblogicEnterpriseBean }
*
*/
public WeblogicEnterpriseBean createWeblogicEnterpriseBean() {
return new WeblogicEnterpriseBean();
}
/**
* Create an instance of {@link TransportRequirements }
*
*/
public TransportRequirements createTransportRequirements() {
return new TransportRequirements();
}
/**
* Create an instance of {@link IiopSecurityDescriptor }
*
*/
public IiopSecurityDescriptor createIiopSecurityDescriptor() {
return new IiopSecurityDescriptor();
}
/**
* Create an instance of {@link EjbReferenceDescription }
*
*/
public EjbReferenceDescription createEjbReferenceDescription() {
return new EjbReferenceDescription();
}
/**
* Create an instance of {@link UnknownPrimaryKeyField }
*
*/
public UnknownPrimaryKeyField createUnknownPrimaryKeyField() {
return new UnknownPrimaryKeyField();
}
/**
* Create an instance of {@link CachingElement }
*
*/
public CachingElement createCachingElement() {
return new CachingElement();
}
/**
* Create an instance of {@link MessageDestinationDescriptor }
*
*/
public MessageDestinationDescriptor createMessageDestinationDescriptor() {
return new MessageDestinationDescriptor();
}
/**
* Create an instance of {@link StatefulSessionCache }
*
*/
public StatefulSessionCache createStatefulSessionCache() {
return new StatefulSessionCache();
}
/**
* Create an instance of {@link MessageDrivenDescriptor }
*
*/
public MessageDrivenDescriptor createMessageDrivenDescriptor() {
return new MessageDrivenDescriptor();
}
/**
* Create an instance of {@link FairShareRequestClass }
*
*/
public FairShareRequestClass createFairShareRequestClass() {
return new FairShareRequestClass();
}
/**
* Create an instance of {@link Compatibility }
*
*/
public Compatibility createCompatibility() {
return new Compatibility();
}
/**
* Create an instance of {@link MinThreadsConstraint }
*
*/
public MinThreadsConstraint createMinThreadsConstraint() {
return new MinThreadsConstraint();
}
/**
* Create an instance of {@link TimerDescriptor }
*
*/
public TimerDescriptor createTimerDescriptor() {
return new TimerDescriptor();
}
/**
* Create an instance of {@link StatelessClustering }
*
*/
public StatelessClustering createStatelessClustering() {
return new StatelessClustering();
}
/**
* Create an instance of {@link StatelessSessionDescriptor }
*
*/
public StatelessSessionDescriptor createStatelessSessionDescriptor() {
return new StatelessSessionDescriptor();
}
/**
* Create an instance of {@link QueryMethod }
*
*/
public QueryMethod createQueryMethod() {
return new QueryMethod();
}
/**
* Create an instance of {@link PortInfo }
*
*/
public PortInfo createPortInfo() {
return new PortInfo();
}
/**
* Create an instance of {@link ApplicationAdminModeTrigger }
*
*/
public ApplicationAdminModeTrigger createApplicationAdminModeTrigger() {
return new ApplicationAdminModeTrigger();
}
/**
* Create an instance of {@link FieldGroup }
*
*/
public FieldGroup createFieldGroup() {
return new FieldGroup();
}
/**
* Create an instance of {@link WeblogicRdbmsBean }
*
*/
public WeblogicRdbmsBean createWeblogicRdbmsBean() {
return new WeblogicRdbmsBean();
}
/**
* Create an instance of {@link DistributedDestinationConnection }
*
*/
public DistributedDestinationConnection createDistributedDestinationConnection() {
return new DistributedDestinationConnection();
}
/**
* Create an instance of {@link TransactionDescriptor }
*
*/
public TransactionDescriptor createTransactionDescriptor() {
return new TransactionDescriptor();
}
/**
* Create an instance of {@link WeblogicQuery }
*
*/
public WeblogicQuery createWeblogicQuery() {
return new WeblogicQuery();
}
/**
* Create an instance of {@link WeblogicCompatibility }
*
*/
public WeblogicCompatibility createWeblogicCompatibility() {
return new WeblogicCompatibility();
}
/**
* Create an instance of {@link PersistenceUse }
*
*/
public PersistenceUse createPersistenceUse() {
return new PersistenceUse();
}
/**
* Create an instance of {@link WeblogicRdbmsRelation }
*
*/
public WeblogicRdbmsRelation createWeblogicRdbmsRelation() {
return new WeblogicRdbmsRelation();
}
/**
* Create an instance of {@link ContextCase }
*
*/
public ContextCase createContextCase() {
return new ContextCase();
}
/**
* Create an instance of {@link Capacity }
*
*/
public Capacity createCapacity() {
return new Capacity();
}
/**
* Create an instance of {@link Logging }
*
*/
public Logging createLogging() {
return new Logging();
}
/**
* Create an instance of {@link AutomaticKeyGeneration }
*
*/
public AutomaticKeyGeneration createAutomaticKeyGeneration() {
return new AutomaticKeyGeneration();
}
/**
* Create an instance of {@link WeblogicEjbJar }
*
*/
public WeblogicEjbJar createWeblogicEjbJar() {
return new WeblogicEjbJar();
}
/**
* Create an instance of {@link SecurityRoleAssignment }
*
*/
public SecurityRoleAssignment createSecurityRoleAssignment() {
return new SecurityRoleAssignment();
}
/**
* Create an instance of {@link Persistence }
*
*/
public Persistence createPersistence() {
return new Persistence();
}
/**
* Create an instance of {@link ConnectionPoolParams }
*
*/
public ConnectionPoolParams createConnectionPoolParams() {
return new ConnectionPoolParams();
}
/**
* Create an instance of {@link RunAsRoleAssignment }
*
*/
public RunAsRoleAssignment createRunAsRoleAssignment() {
return new RunAsRoleAssignment();
}
/**
* Create an instance of {@link Method }
*
*/
public Method createMethod() {
return new Method();
}
/**
* Create an instance of {@link Pool }
*
*/
public Pool createPool() {
return new Pool();
}
/**
* Create an instance of {@link EntityCacheRef }
*
*/
public EntityCacheRef createEntityCacheRef() {
return new EntityCacheRef();
}
/**
* Create an instance of {@link WeblogicRelationshipRole }
*
*/
public WeblogicRelationshipRole createWeblogicRelationshipRole() {
return new WeblogicRelationshipRole();
}
/**
* Create an instance of {@link MaxThreadsConstraint }
*
*/
public MaxThreadsConstraint createMaxThreadsConstraint() {
return new MaxThreadsConstraint();
}
/**
* Create an instance of {@link FieldMap }
*
*/
public FieldMap createFieldMap() {
return new FieldMap();
}
/**
* Create an instance of {@link TableMap }
*
*/
public TableMap createTableMap() {
return new TableMap();
}
/**
* Create an instance of {@link PropertyNamevalue }
*
*/
public PropertyNamevalue createPropertyNamevalue() {
return new PropertyNamevalue();
}
/**
* Create an instance of {@link Table }
*
*/
public Table createTable() {
return new Table();
}
/**
* Create an instance of {@link WorkManager }
*
*/
public WorkManager createWorkManager() {
return new WorkManager();
}
/**
* Create an instance of {@link RetryMethodsOnRollback }
*
*/
public RetryMethodsOnRollback createRetryMethodsOnRollback() {
return new RetryMethodsOnRollback();
}
/**
* Create an instance of {@link IdempotentMethods }
*
*/
public IdempotentMethods createIdempotentMethods() {
return new IdempotentMethods();
}
/**
* Create an instance of {@link EntityDescriptor }
*
*/
public EntityDescriptor createEntityDescriptor() {
return new EntityDescriptor();
}
/**
* Create an instance of {@link MethodParams }
*
*/
public MethodParams createMethodParams() {
return new MethodParams();
}
/**
* Create an instance of {@link ServiceReferenceDescription }
*
*/
public ServiceReferenceDescription createServiceReferenceDescription() {
return new ServiceReferenceDescription();
}
/**
* Create an instance of {@link Empty }
*
*/
public Empty createEmpty() {
return new Empty();
}
/**
* Create an instance of {@link EntityClustering }
*
*/
public EntityClustering createEntityClustering() {
return new EntityClustering();
}
/**
* Create an instance of {@link SqlShape }
*
*/
public SqlShape createSqlShape() {
return new SqlShape();
}
/**
* Create an instance of {@link EntityCache }
*
*/
public EntityCache createEntityCache() {
return new EntityCache();
}
/**
* Create an instance of {@link SqlQuery }
*
*/
public SqlQuery createSqlQuery() {
return new SqlQuery();
}
/**
* Create an instance of {@link StatefulSessionDescriptor }
*
*/
public StatefulSessionDescriptor createStatefulSessionDescriptor() {
return new StatefulSessionDescriptor();
}
/**
* Create an instance of {@link RelationshipCaching }
*
*/
public RelationshipCaching createRelationshipCaching() {
return new RelationshipCaching();
}
/**
* Create an instance of {@link WeblogicRdbmsJar }
*
*/
public WeblogicRdbmsJar createWeblogicRdbmsJar() {
return new WeblogicRdbmsJar();
}
/**
* Create an instance of {@link ContextRequestClass }
*
*/
public ContextRequestClass createContextRequestClass() {
return new ContextRequestClass();
}
/**
* Create an instance of {@link SecurityPermission }
*
*/
public SecurityPermission createSecurityPermission() {
return new SecurityPermission();
}
/**
* Create an instance of {@link DatabaseSpecificSql }
*
*/
public DatabaseSpecificSql createDatabaseSpecificSql() {
return new DatabaseSpecificSql();
}
/**
* Create an instance of {@link SecurityPlugin }
*
*/
public SecurityPlugin createSecurityPlugin() {
return new SecurityPlugin();
}
/**
* Create an instance of {@link TransactionIsolation }
*
*/
public TransactionIsolation createTransactionIsolation() {
return new TransactionIsolation();
}
/**
* Create an instance of {@link ColumnMap }
*
*/
public ColumnMap createColumnMap() {
return new ColumnMap();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://www.bea.com/ns/weblogic/90", name = "cmp-field", scope = FieldGroup.class)
public JAXBElement<String> createFieldGroupCmpField(String value) {
return new JAXBElement<String>(_FieldGroupCmpField_QNAME, String.class, FieldGroup.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://www.bea.com/ns/weblogic/90", name = "cmr-field", scope = FieldGroup.class)
public JAXBElement<String> createFieldGroupCmrField(String value) {
return new JAXBElement<String>(_FieldGroupCmrField_QNAME, String.class, FieldGroup.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://www.bea.com/ns/weblogic/90", name = "principal-name", scope = SecurityRoleAssignment.class)
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
public JAXBElement<String> createSecurityRoleAssignmentPrincipalName(String value) {
return new JAXBElement<String>(_SecurityRoleAssignmentPrincipalName_QNAME, String.class, SecurityRoleAssignment.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link WeblogicEjbJar }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://www.bea.com/ns/weblogic/90", name = "weblogic-ejb-jar")
public JAXBElement<WeblogicEjbJar> createWeblogicEjbJar(WeblogicEjbJar value) {
return new JAXBElement<WeblogicEjbJar>(_WeblogicEjbJar_QNAME, WeblogicEjbJar.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link WeblogicRelationshipRole }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://www.bea.com/ns/weblogic/90", name = "weblogic-relationship-role", scope = WeblogicRdbmsRelation.class)
public JAXBElement<WeblogicRelationshipRole> createWeblogicRdbmsRelationWeblogicRelationshipRole(WeblogicRelationshipRole value) {
return new JAXBElement<WeblogicRelationshipRole>(_WeblogicRdbmsRelationWeblogicRelationshipRole_QNAME, WeblogicRelationshipRole.class, WeblogicRdbmsRelation.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://www.bea.com/ns/weblogic/90", name = "table-name", scope = WeblogicRdbmsRelation.class)
public JAXBElement<String> createWeblogicRdbmsRelationTableName(String value) {
return new JAXBElement<String>(_WeblogicRdbmsRelationTableName_QNAME, String.class, WeblogicRdbmsRelation.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://www.bea.com/ns/weblogic/90", name = "relation-name", scope = WeblogicRdbmsRelation.class)
public JAXBElement<String> createWeblogicRdbmsRelationRelationName(String value) {
return new JAXBElement<String>(_WeblogicRdbmsRelationRelationName_QNAME, String.class, WeblogicRdbmsRelation.class, value);
}
}
| 27.51257 | 179 | 0.641911 |
2f54b8a2de807dca9d0e8595e8dad637fb07bcbb | 2,815 | /**
* 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.crunch.io;
import static org.junit.Assert.assertEquals;
import com.google.common.collect.ImmutableList;
import org.apache.crunch.CreateOptions;
import org.apache.crunch.DoFn;
import org.apache.crunch.Emitter;
import org.apache.crunch.PCollection;
import org.apache.crunch.Pipeline;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.writable.Writables;
import org.apache.crunch.types.avro.Avros;
import org.apache.hadoop.conf.Configuration;
import org.junit.Rule;
import org.junit.Test;
import java.util.List;
public class NLineInputIT {
private static List<String> URLS = ImmutableList.of(
"www.A.com www.B.com",
"www.A.com www.C.com",
"www.A.com www.D.com",
"www.A.com www.E.com",
"www.B.com www.D.com",
"www.B.com www.E.com",
"www.C.com www.D.com",
"www.D.com www.B.com",
"www.E.com www.A.com",
"www.F.com www.B.com",
"www.F.com www.C.com");
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testNLine() throws Exception {
Configuration conf = new Configuration(tmpDir.getDefaultConfiguration());
conf.setInt("io.sort.mb", 10);
Pipeline pipeline = new MRPipeline(NLineInputIT.class, conf);
PCollection<String> urls = pipeline.create(URLS, Writables.strings(),
CreateOptions.parallelism(6));
assertEquals(new Integer(2),
urls.parallelDo(new LineCountFn(), Avros.ints()).max().getValue());
}
private static class LineCountFn extends DoFn<String, Integer> {
private int lineCount = 0;
@Override
public void initialize() {
this.lineCount = 0;
}
@Override
public void process(String input, Emitter<Integer> emitter) {
lineCount++;
}
@Override
public void cleanup(Emitter<Integer> emitter) {
emitter.emit(lineCount);
}
}
}
| 31.988636 | 77 | 0.702664 |
4e900cbadffcfc6851420914e1f4d8c40c89be4e | 9,658 | // This file was generated by Mendix Modeler.
//
// WARNING: Code you write here will be lost the next time you deploy the project.
package queryrequests.proxies;
public class SelectableQueryCode
{
private final com.mendix.systemwideinterfaces.core.IMendixObject selectableQueryCodeMendixObject;
private final com.mendix.systemwideinterfaces.core.IContext context;
/**
* Internal name of this entity
*/
public static final java.lang.String entityName = "QueryRequests.SelectableQueryCode";
/**
* Enum describing members of this entity
*/
public enum MemberNames
{
DateCode("DateCode"),
CodeType("CodeType"),
StringCode("StringCode");
private java.lang.String metaName;
MemberNames(java.lang.String s)
{
metaName = s;
}
@Override
public java.lang.String toString()
{
return metaName;
}
}
public SelectableQueryCode(com.mendix.systemwideinterfaces.core.IContext context)
{
this(context, com.mendix.core.Core.instantiate(context, "QueryRequests.SelectableQueryCode"));
}
protected SelectableQueryCode(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixObject selectableQueryCodeMendixObject)
{
if (selectableQueryCodeMendixObject == null)
throw new java.lang.IllegalArgumentException("The given object cannot be null.");
if (!com.mendix.core.Core.isSubClassOf("QueryRequests.SelectableQueryCode", selectableQueryCodeMendixObject.getType()))
throw new java.lang.IllegalArgumentException("The given object is not a QueryRequests.SelectableQueryCode");
this.selectableQueryCodeMendixObject = selectableQueryCodeMendixObject;
this.context = context;
}
/**
* @deprecated Use 'SelectableQueryCode.load(IContext, IMendixIdentifier)' instead.
*/
@Deprecated
public static queryrequests.proxies.SelectableQueryCode initialize(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixIdentifier mendixIdentifier) throws com.mendix.core.CoreException
{
return queryrequests.proxies.SelectableQueryCode.load(context, mendixIdentifier);
}
/**
* Initialize a proxy using context (recommended). This context will be used for security checking when the get- and set-methods without context parameters are called.
* The get- and set-methods with context parameter should be used when for instance sudo access is necessary (IContext.createSudoClone() can be used to obtain sudo access).
*/
public static queryrequests.proxies.SelectableQueryCode initialize(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixObject mendixObject)
{
return new queryrequests.proxies.SelectableQueryCode(context, mendixObject);
}
public static queryrequests.proxies.SelectableQueryCode load(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixIdentifier mendixIdentifier) throws com.mendix.core.CoreException
{
com.mendix.systemwideinterfaces.core.IMendixObject mendixObject = com.mendix.core.Core.retrieveId(context, mendixIdentifier);
return queryrequests.proxies.SelectableQueryCode.initialize(context, mendixObject);
}
public static java.util.List<queryrequests.proxies.SelectableQueryCode> load(com.mendix.systemwideinterfaces.core.IContext context, java.lang.String xpathConstraint) throws com.mendix.core.CoreException
{
java.util.List<queryrequests.proxies.SelectableQueryCode> result = new java.util.ArrayList<queryrequests.proxies.SelectableQueryCode>();
for (com.mendix.systemwideinterfaces.core.IMendixObject obj : com.mendix.core.Core.retrieveXPathQuery(context, "//QueryRequests.SelectableQueryCode" + xpathConstraint))
result.add(queryrequests.proxies.SelectableQueryCode.initialize(context, obj));
return result;
}
/**
* Commit the changes made on this proxy object.
*/
public final void commit() throws com.mendix.core.CoreException
{
com.mendix.core.Core.commit(context, getMendixObject());
}
/**
* Commit the changes made on this proxy object using the specified context.
*/
public final void commit(com.mendix.systemwideinterfaces.core.IContext context) throws com.mendix.core.CoreException
{
com.mendix.core.Core.commit(context, getMendixObject());
}
/**
* Delete the object.
*/
public final void delete()
{
com.mendix.core.Core.delete(context, getMendixObject());
}
/**
* Delete the object using the specified context.
*/
public final void delete(com.mendix.systemwideinterfaces.core.IContext context)
{
com.mendix.core.Core.delete(context, getMendixObject());
}
/**
* Set value of DateCode
* @param datecode
*/
public final queryrequests.proxies.DateCodes getDateCode()
{
return getDateCode(getContext());
}
/**
* @param context
* @return value of DateCode
*/
public final queryrequests.proxies.DateCodes getDateCode(com.mendix.systemwideinterfaces.core.IContext context)
{
Object obj = getMendixObject().getValue(context, MemberNames.DateCode.toString());
if (obj == null)
return null;
return queryrequests.proxies.DateCodes.valueOf((java.lang.String) obj);
}
/**
* Set value of DateCode
* @param datecode
*/
public final void setDateCode(queryrequests.proxies.DateCodes datecode)
{
setDateCode(getContext(), datecode);
}
/**
* Set value of DateCode
* @param context
* @param datecode
*/
public final void setDateCode(com.mendix.systemwideinterfaces.core.IContext context, queryrequests.proxies.DateCodes datecode)
{
if (datecode != null)
getMendixObject().setValue(context, MemberNames.DateCode.toString(), datecode.toString());
else
getMendixObject().setValue(context, MemberNames.DateCode.toString(), null);
}
/**
* Set value of CodeType
* @param codetype
*/
public final queryrequests.proxies.QuerySelectCodeType getCodeType()
{
return getCodeType(getContext());
}
/**
* @param context
* @return value of CodeType
*/
public final queryrequests.proxies.QuerySelectCodeType getCodeType(com.mendix.systemwideinterfaces.core.IContext context)
{
Object obj = getMendixObject().getValue(context, MemberNames.CodeType.toString());
if (obj == null)
return null;
return queryrequests.proxies.QuerySelectCodeType.valueOf((java.lang.String) obj);
}
/**
* Set value of CodeType
* @param codetype
*/
public final void setCodeType(queryrequests.proxies.QuerySelectCodeType codetype)
{
setCodeType(getContext(), codetype);
}
/**
* Set value of CodeType
* @param context
* @param codetype
*/
public final void setCodeType(com.mendix.systemwideinterfaces.core.IContext context, queryrequests.proxies.QuerySelectCodeType codetype)
{
if (codetype != null)
getMendixObject().setValue(context, MemberNames.CodeType.toString(), codetype.toString());
else
getMendixObject().setValue(context, MemberNames.CodeType.toString(), null);
}
/**
* Set value of StringCode
* @param stringcode
*/
public final queryrequests.proxies.StringCodes getStringCode()
{
return getStringCode(getContext());
}
/**
* @param context
* @return value of StringCode
*/
public final queryrequests.proxies.StringCodes getStringCode(com.mendix.systemwideinterfaces.core.IContext context)
{
Object obj = getMendixObject().getValue(context, MemberNames.StringCode.toString());
if (obj == null)
return null;
return queryrequests.proxies.StringCodes.valueOf((java.lang.String) obj);
}
/**
* Set value of StringCode
* @param stringcode
*/
public final void setStringCode(queryrequests.proxies.StringCodes stringcode)
{
setStringCode(getContext(), stringcode);
}
/**
* Set value of StringCode
* @param context
* @param stringcode
*/
public final void setStringCode(com.mendix.systemwideinterfaces.core.IContext context, queryrequests.proxies.StringCodes stringcode)
{
if (stringcode != null)
getMendixObject().setValue(context, MemberNames.StringCode.toString(), stringcode.toString());
else
getMendixObject().setValue(context, MemberNames.StringCode.toString(), null);
}
/**
* @return the IMendixObject instance of this proxy for use in the Core interface.
*/
public final com.mendix.systemwideinterfaces.core.IMendixObject getMendixObject()
{
return selectableQueryCodeMendixObject;
}
/**
* @return the IContext instance of this proxy, or null if no IContext instance was specified at initialization.
*/
public final com.mendix.systemwideinterfaces.core.IContext getContext()
{
return context;
}
@Override
public boolean equals(Object obj)
{
if (obj == this)
return true;
if (obj != null && getClass().equals(obj.getClass()))
{
final queryrequests.proxies.SelectableQueryCode that = (queryrequests.proxies.SelectableQueryCode) obj;
return getMendixObject().equals(that.getMendixObject());
}
return false;
}
@Override
public int hashCode()
{
return getMendixObject().hashCode();
}
/**
* @return String name of this class
*/
public static java.lang.String getType()
{
return "QueryRequests.SelectableQueryCode";
}
/**
* @return String GUID from this object, format: ID_0000000000
* @deprecated Use getMendixObject().getId().toLong() to get a unique identifier for this object.
*/
@Deprecated
public java.lang.String getGUID()
{
return "ID_" + getMendixObject().getId().toLong();
}
}
| 31.562092 | 233 | 0.735763 |
2c7bacc17b10761cd8b021bede1dbd1bc5f5e8f0 | 358 | package com.usaa.bank.graph.common.identity;
/**
* A class that specifies the GUID specific to Dependency Management tool. This is a specific to DeMa in terms of implementation.
*/
public class GUID extends SimpleImmutableIdentifier {
private static final long serialVersionUID = 1L;
GUID(String identifier) {
super(identifier);
}
}
| 25.571429 | 129 | 0.734637 |
1612dcf7c7be47b5a04a175802b1217747d88394 | 437 | package org.tutar.pattern.chain.simple.handlers;
import org.tutar.pattern.chain.simple.Handler;
import org.tutar.pattern.chain.simple.Request;
/**
* @author tutar
*/
public class SocketHandler implements Handler {
public Boolean isHandleAble(Request request) {
return true;
}
public Boolean process(Request request) {
System.out.println(SocketHandler.class.getSimpleName());
return true;
}
}
| 23 | 64 | 0.71167 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.