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
|
---|---|---|---|---|---|
0d6d11fba911307ff6a9f5385c026c1acf7391f6 | 389 | package com.orm.model;
import com.orm.annotation.Table;
@Table
public class NestedMixedBBModel {
private RelationshipMixedBModel nested;
private Long id;
public NestedMixedBBModel() {}
public NestedMixedBBModel(RelationshipMixedBModel nested) {
this.nested = nested;
}
public RelationshipMixedBModel getNested() {
return nested;
}
public Long getId() {
return id;
}
}
| 16.208333 | 60 | 0.755784 |
74fd1092bf3a40408971a9e73d0d715a4ffb6424 | 445 | package org.learning;
import java.util.Comparator;
/**
* Created by Zdenca on 7/19/2017.
*/
public class StringLengthComparator implements Comparator<String> {
@Override
public int compare(String s1, String s2) {
int len1 = s1.length();
int len2 = s2.length();
if (len1 > len2) {
return 1;
} else if (len1 < len2) {
return -1;
}
return 0;
}
}
| 19.347826 | 67 | 0.539326 |
d68c2f458a8e36cdc2f1ac017ce80b67cf58b111 | 4,340 | /*
* Spring JDBC Plus
*
* Copyright 2020-present NAVER Corp.
*
* 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.navercorp.spring.data.jdbc.plus.sql.convert;
import static org.assertj.core.api.AssertionsForClassTypes.*;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.data.relational.core.mapping.Column;
import org.springframework.data.relational.core.mapping.Embedded;
import org.springframework.data.relational.core.mapping.NamingStrategy;
import org.springframework.data.relational.core.mapping.RelationalPersistentProperty;
import org.springframework.data.relational.core.mapping.Table;
/**
* @author Myeonghyeon Lee
*/
class SqlProviderTest {
@Test
@DisplayName("테이블 기본 컬럼 생성 규칙")
@Disabled
void columns() {
// given
SqlProvider sut = null; //new SqlProvider(new RelationalMappingContext());
// when
String columns = sut.columns(TestInnerEntity.class);
// then
assertThat(columns).isEqualTo(
"test_inner_entity.cty AS cty,\n"
+ "test_inner_entity.state AS state");
}
@Test
@DisplayName("Embedded 된 column을 찾아가서 변환한다.")
@Disabled("SqlTableAlias 를 지원할 때까지 테스트를 Disabled 한다.")
void columnsWithEmbedded() {
// given
SqlProvider sut = null; // new SqlProvider(new RelationalMappingContext());
// when
String columns = sut.columns(TestOuterEntity.class);
// then
assertThat(columns).isEqualTo(
"ts.tester_id AS tester_id,\n"
+ "ts.tester_nm AS tester_nm,\n"
+ "address.state AS adr_state,\n"
+ "address.cty AS adr_cty");
}
@Test
@DisplayName("@SqlTemplate 은 Column 변환식을 사용한다")
@Disabled("SqlTableAlias 를 지원할 때까지 테스트를 Disabled 한다.")
void columnsWithNonNullValue() {
// given
SqlProvider sut = null; // new SqlProvider(new RelationalMappingContext());
// when
String columns = sut.columns(TestEntityWithNonNullValue.class);
// then
assertThat(columns).isEqualTo(
"ts.tester_id AS tester_id,\n"
+ "ts.tester_nm AS tester_nm,\n"
+ "COALESCE(ts.age, 0) as age");
}
@Test
@DisplayName("@Column 이 붙어있지 않으면, namingStrategy 를 따른다.")
@Disabled("SqlTableAlias 를 지원할 때까지 테스트를 Disabled 한다.")
void namingStrategyForNonColumnAnnotatedField() {
// given
SqlProvider sut = null; //new SqlProvider(new RelationalMappingContext(new PrefixingNamingStrategy()));
// when
String columns = sut.columns(TestOuterEntity.class);
// then
assertThat(columns).isEqualTo(
"ts.x_tester_id AS x_tester_id,\n"
+ "ts.tester_nm AS tester_nm,\n"
+ "address.x_state AS adr_x_state,\n"
+ "address.cty AS adr_cty");
}
// @SqlTableAlias("ts")
static class TestOuterEntity {
private Long testerId;
@Column("tester_nm")
private String testerName;
// @SqlTableAlias("address")
@Embedded.Nullable(prefix = "adr_")
private TestInnerEntity testInner;
}
static class TestInnerEntity {
@Column
private String state;
@Column("cty")
private String city;
}
// @SqlTableAlias("ts")
static class TestEntityWithNonNullValue {
@Column
private Long testerId;
@Column("tester_nm")
private String testerName;
@Column
private int age;
}
// @SqlTableAlias("ts")
static class TestEntityWithIgnoredColumn {
private Long testerId;
@Column("tester_nm")
private String testerName;
private String phoneNumber; // This column will be ignored
}
@Table("teie")
static class TestEmbeddedIgnoreEntity {
private Long testerId;
@Column("tester_nm")
private String testerName;
@Embedded.Nullable(prefix = "adr_")
private TestInnerEntity testInner;
}
private static class PrefixingNamingStrategy implements NamingStrategy {
@Override
public String getColumnName(RelationalPersistentProperty property) {
return "x_" + NamingStrategy.super.getColumnName(property);
}
}
}
| 25.988024 | 105 | 0.732719 |
d6b3d42adc70ca266a413d3ed22a44fecd50ca06 | 49,588 | package net.minecraft.world.level;
import com.google.common.collect.Lists;
import com.mojang.serialization.Codec;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import javax.annotation.Nullable;
import net.minecraft.CrashReport;
import net.minecraft.CrashReportSystemDetails;
import net.minecraft.ReportedException;
import net.minecraft.core.BlockPosition;
import net.minecraft.core.EnumDirection;
import net.minecraft.core.IRegistry;
import net.minecraft.core.SectionPosition;
import net.minecraft.core.particles.ParticleParam;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.protocol.Packet;
import net.minecraft.resources.MinecraftKey;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.PlayerChunk;
import net.minecraft.sounds.SoundCategory;
import net.minecraft.sounds.SoundEffect;
import net.minecraft.tags.ITagRegistry;
import net.minecraft.util.MathHelper;
import net.minecraft.util.profiling.GameProfilerFiller;
import net.minecraft.world.DifficultyDamageScaler;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.boss.EntityComplexPart;
import net.minecraft.world.entity.boss.enderdragon.EntityEnderDragon;
import net.minecraft.world.entity.player.EntityHuman;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.CraftingManager;
import net.minecraft.world.level.biome.BiomeBase;
import net.minecraft.world.level.biome.BiomeManager;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.BlockFireAbstract;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.entity.TickingBlockEntity;
import net.minecraft.world.level.block.entity.TileEntity;
import net.minecraft.world.level.block.state.IBlockData;
import net.minecraft.world.level.border.WorldBorder;
import net.minecraft.world.level.chunk.Chunk;
import net.minecraft.world.level.chunk.ChunkStatus;
import net.minecraft.world.level.chunk.IChunkAccess;
import net.minecraft.world.level.chunk.IChunkProvider;
import net.minecraft.world.level.dimension.DimensionManager;
import net.minecraft.world.level.entity.EntityTypeTest;
import net.minecraft.world.level.entity.LevelEntityGetter;
import net.minecraft.world.level.gameevent.GameEvent;
import net.minecraft.world.level.levelgen.HeightMap;
import net.minecraft.world.level.lighting.LightEngine;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.level.material.FluidTypes;
import net.minecraft.world.level.saveddata.maps.WorldMap;
import net.minecraft.world.level.storage.WorldData;
import net.minecraft.world.level.storage.WorldDataMutable;
import net.minecraft.world.phys.AxisAlignedBB;
import net.minecraft.world.scores.Scoreboard;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
// CraftBukkit start
import java.util.HashMap;
import java.util.Map;
import net.minecraft.network.protocol.game.ClientboundSetBorderCenterPacket;
import net.minecraft.network.protocol.game.ClientboundSetBorderLerpSizePacket;
import net.minecraft.network.protocol.game.ClientboundSetBorderSizePacket;
import net.minecraft.network.protocol.game.ClientboundSetBorderWarningDelayPacket;
import net.minecraft.network.protocol.game.ClientboundSetBorderWarningDistancePacket;
import net.minecraft.server.level.WorldServer;
import net.minecraft.world.entity.item.EntityItem;
import net.minecraft.world.level.border.IWorldBorderListener;
import net.minecraft.world.level.dimension.WorldDimension;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.craftbukkit.CraftServer;
import org.bukkit.craftbukkit.CraftWorld;
import org.bukkit.craftbukkit.block.CapturedBlockState;
import org.bukkit.craftbukkit.block.data.CraftBlockData;
import org.bukkit.craftbukkit.util.CraftNamespacedKey;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.world.GenericGameEvent;
// CraftBukkit end
public abstract class World implements GeneratorAccess, AutoCloseable {
protected static final Logger LOGGER = LogManager.getLogger();
public static final Codec<ResourceKey<World>> RESOURCE_KEY_CODEC = MinecraftKey.CODEC.xmap(ResourceKey.elementKey(IRegistry.DIMENSION_REGISTRY), ResourceKey::location);
public static final ResourceKey<World> OVERWORLD = ResourceKey.create(IRegistry.DIMENSION_REGISTRY, new MinecraftKey("overworld"));
public static final ResourceKey<World> NETHER = ResourceKey.create(IRegistry.DIMENSION_REGISTRY, new MinecraftKey("the_nether"));
public static final ResourceKey<World> END = ResourceKey.create(IRegistry.DIMENSION_REGISTRY, new MinecraftKey("the_end"));
public static final int MAX_LEVEL_SIZE = 30000000;
public static final int LONG_PARTICLE_CLIP_RANGE = 512;
public static final int SHORT_PARTICLE_CLIP_RANGE = 32;
private static final EnumDirection[] DIRECTIONS = EnumDirection.values();
public static final int MAX_BRIGHTNESS = 15;
public static final int TICKS_PER_DAY = 24000;
public static final int MAX_ENTITY_SPAWN_Y = 20000000;
public static final int MIN_ENTITY_SPAWN_Y = -20000000;
protected final List<TickingBlockEntity> blockEntityTickers = Lists.newArrayList();
private final List<TickingBlockEntity> pendingBlockEntityTickers = Lists.newArrayList();
private boolean tickingBlockEntities;
public final Thread thread;
private final boolean isDebug;
private int skyDarken;
protected int randValue = (new Random()).nextInt();
protected final int addend = 1013904223;
protected float oRainLevel;
public float rainLevel;
protected float oThunderLevel;
public float thunderLevel;
public final Random random = new Random();
private final DimensionManager dimensionType;
public final WorldDataMutable levelData;
private final Supplier<GameProfilerFiller> profiler;
public final boolean isClientSide;
private final WorldBorder worldBorder;
private final BiomeManager biomeManager;
private final ResourceKey<World> dimension;
private long subTickCount;
// CraftBukkit start Added the following
private final CraftWorld world;
public boolean pvpMode;
public boolean keepSpawnInMemory = true;
public org.bukkit.generator.ChunkGenerator generator;
public boolean preventPoiUpdated = false; // CraftBukkit - SPIGOT-5710
public boolean captureBlockStates = false;
public boolean captureTreeGeneration = false;
public Map<BlockPosition, CapturedBlockState> capturedBlockStates = new java.util.LinkedHashMap<>();
public Map<BlockPosition, TileEntity> capturedTileEntities = new HashMap<>();
public List<EntityItem> captureDrops;
public long ticksPerAnimalSpawns;
public long ticksPerMonsterSpawns;
public long ticksPerWaterSpawns;
public long ticksPerWaterAmbientSpawns;
public long ticksPerWaterUndergroundCreatureSpawns;
public long ticksPerAmbientSpawns;
public boolean populating;
public CraftWorld getWorld() {
return this.world;
}
public CraftServer getCraftServer() {
return (CraftServer) Bukkit.getServer();
}
public abstract ResourceKey<WorldDimension> getTypeKey();
protected World(WorldDataMutable worlddatamutable, ResourceKey<World> resourcekey, final DimensionManager dimensionmanager, Supplier<GameProfilerFiller> supplier, boolean flag, boolean flag1, long i, org.bukkit.generator.ChunkGenerator gen, org.bukkit.generator.BiomeProvider biomeProvider, org.bukkit.World.Environment env) {
this.generator = gen;
this.world = new CraftWorld((WorldServer) this, gen, biomeProvider, env);
this.ticksPerAnimalSpawns = this.getCraftServer().getTicksPerAnimalSpawns(); // CraftBukkit
this.ticksPerMonsterSpawns = this.getCraftServer().getTicksPerMonsterSpawns(); // CraftBukkit
this.ticksPerWaterSpawns = this.getCraftServer().getTicksPerWaterSpawns(); // CraftBukkit
this.ticksPerWaterAmbientSpawns = this.getCraftServer().getTicksPerWaterAmbientSpawns(); // CraftBukkit
this.ticksPerWaterUndergroundCreatureSpawns = this.getCraftServer().getTicksPerWaterUndergroundCreatureSpawns(); // CraftBukkit
this.ticksPerAmbientSpawns = this.getCraftServer().getTicksPerAmbientSpawns(); // CraftBukkit
// CraftBukkit end
this.profiler = supplier;
this.levelData = worlddatamutable;
this.dimensionType = dimensionmanager;
this.dimension = resourcekey;
this.isClientSide = flag;
if (dimensionmanager.coordinateScale() != 1.0D) {
this.worldBorder = new WorldBorder() {
@Override
public double getCenterX() {
return super.getCenterX(); // CraftBukkit
}
@Override
public double getCenterZ() {
return super.getCenterZ(); // CraftBukkit
}
};
} else {
this.worldBorder = new WorldBorder();
}
this.thread = Thread.currentThread();
this.biomeManager = new BiomeManager(this, i);
this.isDebug = flag1;
// CraftBukkit start
getWorldBorder().world = (WorldServer) this;
// From PlayerList.setPlayerFileData
getWorldBorder().addListener(new IWorldBorderListener() {
@Override
public void onBorderSizeSet(WorldBorder worldborder, double d0) {
getCraftServer().getHandle().broadcastAll(new ClientboundSetBorderSizePacket(worldborder), worldborder.world);
}
@Override
public void onBorderSizeLerping(WorldBorder worldborder, double d0, double d1, long i) {
getCraftServer().getHandle().broadcastAll(new ClientboundSetBorderLerpSizePacket(worldborder), worldborder.world);
}
@Override
public void onBorderCenterSet(WorldBorder worldborder, double d0, double d1) {
getCraftServer().getHandle().broadcastAll(new ClientboundSetBorderCenterPacket(worldborder), worldborder.world);
}
@Override
public void onBorderSetWarningTime(WorldBorder worldborder, int i) {
getCraftServer().getHandle().broadcastAll(new ClientboundSetBorderWarningDelayPacket(worldborder), worldborder.world);
}
@Override
public void onBorderSetWarningBlocks(WorldBorder worldborder, int i) {
getCraftServer().getHandle().broadcastAll(new ClientboundSetBorderWarningDistancePacket(worldborder), worldborder.world);
}
@Override
public void onBorderSetDamagePerBlock(WorldBorder worldborder, double d0) {}
@Override
public void onBorderSetDamageSafeZOne(WorldBorder worldborder, double d0) {}
});
// CraftBukkit end
}
@Override
public boolean isClientSide() {
return this.isClientSide;
}
@Nullable
@Override
public MinecraftServer getServer() {
return null;
}
public boolean isInWorldBounds(BlockPosition blockposition) {
return !this.isOutsideBuildHeight(blockposition) && isInWorldBoundsHorizontal(blockposition);
}
public static boolean isInSpawnableBounds(BlockPosition blockposition) {
return !isOutsideSpawnableHeight(blockposition.getY()) && isInWorldBoundsHorizontal(blockposition);
}
private static boolean isInWorldBoundsHorizontal(BlockPosition blockposition) {
return blockposition.getX() >= -30000000 && blockposition.getZ() >= -30000000 && blockposition.getX() < 30000000 && blockposition.getZ() < 30000000;
}
private static boolean isOutsideSpawnableHeight(int i) {
return i < -20000000 || i >= 20000000;
}
public Chunk getChunkAt(BlockPosition blockposition) {
return this.getChunk(SectionPosition.blockToSectionCoord(blockposition.getX()), SectionPosition.blockToSectionCoord(blockposition.getZ()));
}
@Override
public Chunk getChunk(int i, int j) {
return (Chunk) this.getChunk(i, j, ChunkStatus.FULL);
}
@Nullable
@Override
public IChunkAccess getChunk(int i, int j, ChunkStatus chunkstatus, boolean flag) {
IChunkAccess ichunkaccess = this.getChunkSource().getChunk(i, j, chunkstatus, flag);
if (ichunkaccess == null && flag) {
throw new IllegalStateException("Should always be able to create a chunk!");
} else {
return ichunkaccess;
}
}
@Override
public boolean setBlock(BlockPosition blockposition, IBlockData iblockdata, int i) {
return this.setBlock(blockposition, iblockdata, i, 512);
}
@Override
public boolean setBlock(BlockPosition blockposition, IBlockData iblockdata, int i, int j) {
// CraftBukkit start - tree generation
if (this.captureTreeGeneration) {
CapturedBlockState blockstate = capturedBlockStates.get(blockposition);
if (blockstate == null) {
blockstate = CapturedBlockState.getTreeBlockState(this, blockposition, i);
this.capturedBlockStates.put(blockposition.immutable(), blockstate);
}
blockstate.setData(iblockdata);
return true;
}
// CraftBukkit end
if (this.isOutsideBuildHeight(blockposition)) {
return false;
} else if (!this.isClientSide && this.isDebug()) {
return false;
} else {
Chunk chunk = this.getChunkAt(blockposition);
Block block = iblockdata.getBlock();
// CraftBukkit start - capture blockstates
boolean captured = false;
if (this.captureBlockStates && !this.capturedBlockStates.containsKey(blockposition)) {
CapturedBlockState blockstate = CapturedBlockState.getBlockState(this, blockposition, i);
this.capturedBlockStates.put(blockposition.immutable(), blockstate);
captured = true;
}
// CraftBukkit end
IBlockData iblockdata1 = chunk.setBlockState(blockposition, iblockdata, (i & 64) != 0, (i & 1024) == 0); // CraftBukkit custom NO_PLACE flag
if (iblockdata1 == null) {
// CraftBukkit start - remove blockstate if failed (or the same)
if (this.captureBlockStates && captured) {
this.capturedBlockStates.remove(blockposition);
}
// CraftBukkit end
return false;
} else {
IBlockData iblockdata2 = this.getBlockState(blockposition);
if ((i & 128) == 0 && iblockdata2 != iblockdata1 && (iblockdata2.getLightBlock(this, blockposition) != iblockdata1.getLightBlock(this, blockposition) || iblockdata2.getLightEmission() != iblockdata1.getLightEmission() || iblockdata2.useShapeForLightOcclusion() || iblockdata1.useShapeForLightOcclusion())) {
this.getProfiler().push("queueCheckLight");
this.getChunkSource().getLightEngine().checkBlock(blockposition);
this.getProfiler().pop();
}
/*
if (iblockdata2 == iblockdata) {
if (iblockdata1 != iblockdata2) {
this.setBlocksDirty(blockposition, iblockdata1, iblockdata2);
}
if ((i & 2) != 0 && (!this.isClientSide || (i & 4) == 0) && (this.isClientSide || chunk.getFullStatus() != null && chunk.getFullStatus().isOrAfter(PlayerChunk.State.TICKING))) {
this.sendBlockUpdated(blockposition, iblockdata1, iblockdata, i);
}
if ((i & 1) != 0) {
this.blockUpdated(blockposition, iblockdata1.getBlock());
if (!this.isClientSide && iblockdata.hasAnalogOutputSignal()) {
this.updateNeighbourForOutputSignal(blockposition, block);
}
}
if ((i & 16) == 0 && j > 0) {
int k = i & -34;
iblockdata1.updateIndirectNeighbourShapes(this, blockposition, k, j - 1);
iblockdata.updateNeighbourShapes(this, blockposition, k, j - 1);
iblockdata.updateIndirectNeighbourShapes(this, blockposition, k, j - 1);
}
this.onBlockStateChange(blockposition, iblockdata1, iblockdata2);
}
*/
// CraftBukkit start
if (!this.captureBlockStates) { // Don't notify clients or update physics while capturing blockstates
// Modularize client and physic updates
notifyAndUpdatePhysics(blockposition, chunk, iblockdata1, iblockdata, iblockdata2, i, j);
}
// CraftBukkit end
return true;
}
}
}
// CraftBukkit start - Split off from above in order to directly send client and physic updates
public void notifyAndUpdatePhysics(BlockPosition blockposition, Chunk chunk, IBlockData oldBlock, IBlockData newBlock, IBlockData actualBlock, int i, int j) {
IBlockData iblockdata = newBlock;
IBlockData iblockdata1 = oldBlock;
IBlockData iblockdata2 = actualBlock;
if (iblockdata2 == iblockdata) {
if (iblockdata1 != iblockdata2) {
this.setBlocksDirty(blockposition, iblockdata1, iblockdata2);
}
if ((i & 2) != 0 && (!this.isClientSide || (i & 4) == 0) && (this.isClientSide || chunk == null || (chunk.getFullStatus() != null && chunk.getFullStatus().isOrAfter(PlayerChunk.State.TICKING)))) { // allow chunk to be null here as chunk.isReady() is false when we send our notification during block placement
this.sendBlockUpdated(blockposition, iblockdata1, iblockdata, i);
}
if ((i & 1) != 0) {
this.blockUpdated(blockposition, iblockdata1.getBlock());
if (!this.isClientSide && iblockdata.hasAnalogOutputSignal()) {
this.updateNeighbourForOutputSignal(blockposition, newBlock.getBlock());
}
}
if ((i & 16) == 0 && j > 0) {
int k = i & -34;
// CraftBukkit start
iblockdata1.updateIndirectNeighbourShapes(this, blockposition, k, j - 1); // Don't call an event for the old block to limit event spam
CraftWorld world = ((WorldServer) this).getWorld();
if (world != null) {
BlockPhysicsEvent event = new BlockPhysicsEvent(world.getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()), CraftBlockData.fromData(iblockdata));
this.getCraftServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
}
// CraftBukkit end
iblockdata.updateNeighbourShapes(this, blockposition, k, j - 1);
iblockdata.updateIndirectNeighbourShapes(this, blockposition, k, j - 1);
}
// CraftBukkit start - SPIGOT-5710
if (!preventPoiUpdated) {
this.onBlockStateChange(blockposition, iblockdata1, iblockdata2);
}
// CraftBukkit end
}
}
// CraftBukkit end
public void onBlockStateChange(BlockPosition blockposition, IBlockData iblockdata, IBlockData iblockdata1) {}
@Override
public boolean removeBlock(BlockPosition blockposition, boolean flag) {
Fluid fluid = this.getFluidState(blockposition);
return this.setBlock(blockposition, fluid.createLegacyBlock(), 3 | (flag ? 64 : 0));
}
@Override
public boolean destroyBlock(BlockPosition blockposition, boolean flag, @Nullable Entity entity, int i) {
IBlockData iblockdata = this.getBlockState(blockposition);
if (iblockdata.isAir()) {
return false;
} else {
Fluid fluid = this.getFluidState(blockposition);
if (!(iblockdata.getBlock() instanceof BlockFireAbstract)) {
this.levelEvent(2001, blockposition, Block.getId(iblockdata));
}
if (flag) {
TileEntity tileentity = iblockdata.hasBlockEntity() ? this.getBlockEntity(blockposition) : null;
Block.dropResources(iblockdata, this, blockposition, tileentity, entity, ItemStack.EMPTY);
}
boolean flag1 = this.setBlock(blockposition, fluid.createLegacyBlock(), 3, i);
if (flag1) {
this.gameEvent(entity, GameEvent.BLOCK_DESTROY, blockposition);
}
return flag1;
}
}
public void addDestroyBlockEffect(BlockPosition blockposition, IBlockData iblockdata) {}
public boolean setBlockAndUpdate(BlockPosition blockposition, IBlockData iblockdata) {
return this.setBlock(blockposition, iblockdata, 3);
}
public abstract void sendBlockUpdated(BlockPosition blockposition, IBlockData iblockdata, IBlockData iblockdata1, int i);
public void setBlocksDirty(BlockPosition blockposition, IBlockData iblockdata, IBlockData iblockdata1) {}
public void updateNeighborsAt(BlockPosition blockposition, Block block) {
this.neighborChanged(blockposition.west(), block, blockposition);
this.neighborChanged(blockposition.east(), block, blockposition);
this.neighborChanged(blockposition.below(), block, blockposition);
this.neighborChanged(blockposition.above(), block, blockposition);
this.neighborChanged(blockposition.north(), block, blockposition);
this.neighborChanged(blockposition.south(), block, blockposition);
}
public void updateNeighborsAtExceptFromFacing(BlockPosition blockposition, Block block, EnumDirection enumdirection) {
if (enumdirection != EnumDirection.WEST) {
this.neighborChanged(blockposition.west(), block, blockposition);
}
if (enumdirection != EnumDirection.EAST) {
this.neighborChanged(blockposition.east(), block, blockposition);
}
if (enumdirection != EnumDirection.DOWN) {
this.neighborChanged(blockposition.below(), block, blockposition);
}
if (enumdirection != EnumDirection.UP) {
this.neighborChanged(blockposition.above(), block, blockposition);
}
if (enumdirection != EnumDirection.NORTH) {
this.neighborChanged(blockposition.north(), block, blockposition);
}
if (enumdirection != EnumDirection.SOUTH) {
this.neighborChanged(blockposition.south(), block, blockposition);
}
}
public void neighborChanged(BlockPosition blockposition, Block block, BlockPosition blockposition1) {
if (!this.isClientSide) {
IBlockData iblockdata = this.getBlockState(blockposition);
try {
// CraftBukkit start
CraftWorld world = ((WorldServer) this).getWorld();
if (world != null) {
BlockPhysicsEvent event = new BlockPhysicsEvent(world.getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()), CraftBlockData.fromData(iblockdata), world.getBlockAt(blockposition1.getX(), blockposition1.getY(), blockposition1.getZ()));
this.getCraftServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
}
// CraftBukkit end
iblockdata.neighborChanged(this, blockposition, block, blockposition1, false);
} catch (Throwable throwable) {
CrashReport crashreport = CrashReport.forThrowable(throwable, "Exception while updating neighbours");
CrashReportSystemDetails crashreportsystemdetails = crashreport.addCategory("Block being updated");
crashreportsystemdetails.setDetail("Source block type", () -> {
try {
return String.format("ID #%s (%s // %s)", IRegistry.BLOCK.getKey(block), block.getDescriptionId(), block.getClass().getCanonicalName());
} catch (Throwable throwable1) {
return "ID #" + IRegistry.BLOCK.getKey(block);
}
});
CrashReportSystemDetails.populateBlockDetails(crashreportsystemdetails, this, blockposition, iblockdata);
throw new ReportedException(crashreport);
}
}
}
@Override
public int getHeight(HeightMap.Type heightmap_type, int i, int j) {
int k;
if (i >= -30000000 && j >= -30000000 && i < 30000000 && j < 30000000) {
if (this.hasChunk(SectionPosition.blockToSectionCoord(i), SectionPosition.blockToSectionCoord(j))) {
k = this.getChunk(SectionPosition.blockToSectionCoord(i), SectionPosition.blockToSectionCoord(j)).getHeight(heightmap_type, i & 15, j & 15) + 1;
} else {
k = this.getMinBuildHeight();
}
} else {
k = this.getSeaLevel() + 1;
}
return k;
}
@Override
public LightEngine getLightEngine() {
return this.getChunkSource().getLightEngine();
}
@Override
public IBlockData getBlockState(BlockPosition blockposition) {
// CraftBukkit start - tree generation
if (captureTreeGeneration) {
CapturedBlockState previous = capturedBlockStates.get(blockposition);
if (previous != null) {
return previous.getHandle();
}
}
// CraftBukkit end
if (this.isOutsideBuildHeight(blockposition)) {
return Blocks.VOID_AIR.defaultBlockState();
} else {
Chunk chunk = this.getChunk(SectionPosition.blockToSectionCoord(blockposition.getX()), SectionPosition.blockToSectionCoord(blockposition.getZ()));
return chunk.getBlockState(blockposition);
}
}
@Override
public Fluid getFluidState(BlockPosition blockposition) {
if (this.isOutsideBuildHeight(blockposition)) {
return FluidTypes.EMPTY.defaultFluidState();
} else {
Chunk chunk = this.getChunkAt(blockposition);
return chunk.getFluidState(blockposition);
}
}
public boolean isDay() {
return !this.dimensionType().hasFixedTime() && this.skyDarken < 4;
}
public boolean isNight() {
return !this.dimensionType().hasFixedTime() && !this.isDay();
}
@Override
public void playSound(@Nullable EntityHuman entityhuman, BlockPosition blockposition, SoundEffect soundeffect, SoundCategory soundcategory, float f, float f1) {
this.playSound(entityhuman, (double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.5D, (double) blockposition.getZ() + 0.5D, soundeffect, soundcategory, f, f1);
}
public abstract void playSound(@Nullable EntityHuman entityhuman, double d0, double d1, double d2, SoundEffect soundeffect, SoundCategory soundcategory, float f, float f1);
public abstract void playSound(@Nullable EntityHuman entityhuman, Entity entity, SoundEffect soundeffect, SoundCategory soundcategory, float f, float f1);
public void playLocalSound(double d0, double d1, double d2, SoundEffect soundeffect, SoundCategory soundcategory, float f, float f1, boolean flag) {}
@Override
public void addParticle(ParticleParam particleparam, double d0, double d1, double d2, double d3, double d4, double d5) {}
public void addParticle(ParticleParam particleparam, boolean flag, double d0, double d1, double d2, double d3, double d4, double d5) {}
public void addAlwaysVisibleParticle(ParticleParam particleparam, double d0, double d1, double d2, double d3, double d4, double d5) {}
public void addAlwaysVisibleParticle(ParticleParam particleparam, boolean flag, double d0, double d1, double d2, double d3, double d4, double d5) {}
public float getSunAngle(float f) {
float f1 = this.getTimeOfDay(f);
return f1 * 6.2831855F;
}
public void addBlockEntityTicker(TickingBlockEntity tickingblockentity) {
(this.tickingBlockEntities ? this.pendingBlockEntityTickers : this.blockEntityTickers).add(tickingblockentity);
}
protected void tickBlockEntities() {
GameProfilerFiller gameprofilerfiller = this.getProfiler();
gameprofilerfiller.push("blockEntities");
this.tickingBlockEntities = true;
if (!this.pendingBlockEntityTickers.isEmpty()) {
this.blockEntityTickers.addAll(this.pendingBlockEntityTickers);
this.pendingBlockEntityTickers.clear();
}
Iterator iterator = this.blockEntityTickers.iterator();
while (iterator.hasNext()) {
TickingBlockEntity tickingblockentity = (TickingBlockEntity) iterator.next();
if (tickingblockentity.isRemoved()) {
iterator.remove();
} else if (this.shouldTickBlocksAt(ChunkCoordIntPair.asLong(tickingblockentity.getPos()))) {
tickingblockentity.tick();
}
}
this.tickingBlockEntities = false;
gameprofilerfiller.pop();
}
public <T extends Entity> void guardEntityTick(Consumer<T> consumer, T t0) {
try {
consumer.accept(t0);
} catch (Throwable throwable) {
CrashReport crashreport = CrashReport.forThrowable(throwable, "Ticking entity");
CrashReportSystemDetails crashreportsystemdetails = crashreport.addCategory("Entity being ticked");
t0.fillCrashReportCategory(crashreportsystemdetails);
throw new ReportedException(crashreport);
}
}
public boolean shouldTickDeath(Entity entity) {
return true;
}
public boolean shouldTickBlocksAt(long i) {
return true;
}
public Explosion explode(@Nullable Entity entity, double d0, double d1, double d2, float f, Explosion.Effect explosion_effect) {
return this.explode(entity, (DamageSource) null, (ExplosionDamageCalculator) null, d0, d1, d2, f, false, explosion_effect);
}
public Explosion explode(@Nullable Entity entity, double d0, double d1, double d2, float f, boolean flag, Explosion.Effect explosion_effect) {
return this.explode(entity, (DamageSource) null, (ExplosionDamageCalculator) null, d0, d1, d2, f, flag, explosion_effect);
}
public Explosion explode(@Nullable Entity entity, @Nullable DamageSource damagesource, @Nullable ExplosionDamageCalculator explosiondamagecalculator, double d0, double d1, double d2, float f, boolean flag, Explosion.Effect explosion_effect) {
Explosion explosion = new Explosion(this, entity, damagesource, explosiondamagecalculator, d0, d1, d2, f, flag, explosion_effect);
explosion.explode();
explosion.finalizeExplosion(true);
return explosion;
}
public abstract String gatherChunkSourceStats();
@Nullable
@Override
public TileEntity getBlockEntity(BlockPosition blockposition) {
// CraftBukkit start
return getBlockEntity(blockposition, true);
}
@Nullable
public TileEntity getBlockEntity(BlockPosition blockposition, boolean validate) {
if (capturedTileEntities.containsKey(blockposition)) {
return capturedTileEntities.get(blockposition);
}
// CraftBukkit end
return this.isOutsideBuildHeight(blockposition) ? null : (!this.isClientSide && Thread.currentThread() != this.thread ? null : this.getChunkAt(blockposition).getBlockEntity(blockposition, Chunk.EnumTileEntityState.IMMEDIATE));
}
public void setBlockEntity(TileEntity tileentity) {
BlockPosition blockposition = tileentity.getBlockPos();
if (!this.isOutsideBuildHeight(blockposition)) {
// CraftBukkit start
if (captureBlockStates) {
capturedTileEntities.put(blockposition.immutable(), tileentity);
return;
}
// CraftBukkit end
this.getChunkAt(blockposition).addAndRegisterBlockEntity(tileentity);
}
}
public void removeBlockEntity(BlockPosition blockposition) {
if (!this.isOutsideBuildHeight(blockposition)) {
this.getChunkAt(blockposition).removeBlockEntity(blockposition);
}
}
public boolean isLoaded(BlockPosition blockposition) {
return this.isOutsideBuildHeight(blockposition) ? false : this.getChunkSource().hasChunk(SectionPosition.blockToSectionCoord(blockposition.getX()), SectionPosition.blockToSectionCoord(blockposition.getZ()));
}
public boolean loadedAndEntityCanStandOnFace(BlockPosition blockposition, Entity entity, EnumDirection enumdirection) {
if (this.isOutsideBuildHeight(blockposition)) {
return false;
} else {
IChunkAccess ichunkaccess = this.getChunk(SectionPosition.blockToSectionCoord(blockposition.getX()), SectionPosition.blockToSectionCoord(blockposition.getZ()), ChunkStatus.FULL, false);
return ichunkaccess == null ? false : ichunkaccess.getBlockState(blockposition).entityCanStandOnFace(this, blockposition, entity, enumdirection);
}
}
public boolean loadedAndEntityCanStandOn(BlockPosition blockposition, Entity entity) {
return this.loadedAndEntityCanStandOnFace(blockposition, entity, EnumDirection.UP);
}
public void updateSkyBrightness() {
double d0 = 1.0D - (double) (this.getRainLevel(1.0F) * 5.0F) / 16.0D;
double d1 = 1.0D - (double) (this.getThunderLevel(1.0F) * 5.0F) / 16.0D;
double d2 = 0.5D + 2.0D * MathHelper.clamp((double) MathHelper.cos(this.getTimeOfDay(1.0F) * 6.2831855F), -0.25D, 0.25D);
this.skyDarken = (int) ((1.0D - d2 * d0 * d1) * 11.0D);
}
public void setSpawnSettings(boolean flag, boolean flag1) {
this.getChunkSource().setSpawnSettings(flag, flag1);
}
protected void prepareWeather() {
if (this.levelData.isRaining()) {
this.rainLevel = 1.0F;
if (this.levelData.isThundering()) {
this.thunderLevel = 1.0F;
}
}
}
public void close() throws IOException {
this.getChunkSource().close();
}
@Nullable
@Override
public IBlockAccess getChunkForCollisions(int i, int j) {
return this.getChunk(i, j, ChunkStatus.FULL, false);
}
@Override
public List<Entity> getEntities(@Nullable Entity entity, AxisAlignedBB axisalignedbb, Predicate<? super Entity> predicate) {
this.getProfiler().incrementCounter("getEntities");
List<Entity> list = Lists.newArrayList();
this.getEntities().get(axisalignedbb, (entity1) -> {
if (entity1 != entity && predicate.test(entity1)) {
list.add(entity1);
}
if (entity1 instanceof EntityEnderDragon) {
EntityComplexPart[] aentitycomplexpart = ((EntityEnderDragon) entity1).getSubEntities();
int i = aentitycomplexpart.length;
for (int j = 0; j < i; ++j) {
EntityComplexPart entitycomplexpart = aentitycomplexpart[j];
if (entity1 != entity && predicate.test(entitycomplexpart)) {
list.add(entitycomplexpart);
}
}
}
});
return list;
}
@Override
public <T extends Entity> List<T> getEntities(EntityTypeTest<Entity, T> entitytypetest, AxisAlignedBB axisalignedbb, Predicate<? super T> predicate) {
this.getProfiler().incrementCounter("getEntities");
List<T> list = Lists.newArrayList();
this.getEntities().get(entitytypetest, axisalignedbb, (entity) -> {
if (predicate.test(entity)) {
list.add(entity);
}
if (entity instanceof EntityEnderDragon) {
EntityEnderDragon entityenderdragon = (EntityEnderDragon) entity;
EntityComplexPart[] aentitycomplexpart = entityenderdragon.getSubEntities();
int i = aentitycomplexpart.length;
for (int j = 0; j < i; ++j) {
EntityComplexPart entitycomplexpart = aentitycomplexpart[j];
T t0 = entitytypetest.tryCast(entitycomplexpart); // CraftBukkit - decompile error
if (t0 != null && predicate.test(t0)) {
list.add(t0);
}
}
}
});
return list;
}
@Nullable
public abstract Entity getEntity(int i);
public void blockEntityChanged(BlockPosition blockposition) {
if (this.hasChunkAt(blockposition)) {
this.getChunkAt(blockposition).setUnsaved(true);
}
}
@Override
public int getSeaLevel() {
return 63;
}
public int getDirectSignalTo(BlockPosition blockposition) {
byte b0 = 0;
int i = Math.max(b0, this.getDirectSignal(blockposition.below(), EnumDirection.DOWN));
if (i >= 15) {
return i;
} else {
i = Math.max(i, this.getDirectSignal(blockposition.above(), EnumDirection.UP));
if (i >= 15) {
return i;
} else {
i = Math.max(i, this.getDirectSignal(blockposition.north(), EnumDirection.NORTH));
if (i >= 15) {
return i;
} else {
i = Math.max(i, this.getDirectSignal(blockposition.south(), EnumDirection.SOUTH));
if (i >= 15) {
return i;
} else {
i = Math.max(i, this.getDirectSignal(blockposition.west(), EnumDirection.WEST));
if (i >= 15) {
return i;
} else {
i = Math.max(i, this.getDirectSignal(blockposition.east(), EnumDirection.EAST));
return i >= 15 ? i : i;
}
}
}
}
}
}
public boolean hasSignal(BlockPosition blockposition, EnumDirection enumdirection) {
return this.getSignal(blockposition, enumdirection) > 0;
}
public int getSignal(BlockPosition blockposition, EnumDirection enumdirection) {
IBlockData iblockdata = this.getBlockState(blockposition);
int i = iblockdata.getSignal(this, blockposition, enumdirection);
return iblockdata.isRedstoneConductor(this, blockposition) ? Math.max(i, this.getDirectSignalTo(blockposition)) : i;
}
public boolean hasNeighborSignal(BlockPosition blockposition) {
return this.getSignal(blockposition.below(), EnumDirection.DOWN) > 0 ? true : (this.getSignal(blockposition.above(), EnumDirection.UP) > 0 ? true : (this.getSignal(blockposition.north(), EnumDirection.NORTH) > 0 ? true : (this.getSignal(blockposition.south(), EnumDirection.SOUTH) > 0 ? true : (this.getSignal(blockposition.west(), EnumDirection.WEST) > 0 ? true : this.getSignal(blockposition.east(), EnumDirection.EAST) > 0))));
}
public int getBestNeighborSignal(BlockPosition blockposition) {
int i = 0;
EnumDirection[] aenumdirection = World.DIRECTIONS;
int j = aenumdirection.length;
for (int k = 0; k < j; ++k) {
EnumDirection enumdirection = aenumdirection[k];
int l = this.getSignal(blockposition.relative(enumdirection), enumdirection);
if (l >= 15) {
return 15;
}
if (l > i) {
i = l;
}
}
return i;
}
public void disconnect() {}
public long getGameTime() {
return this.levelData.getGameTime();
}
public long getDayTime() {
return this.levelData.getDayTime();
}
public boolean mayInteract(EntityHuman entityhuman, BlockPosition blockposition) {
return true;
}
public void broadcastEntityEvent(Entity entity, byte b0) {}
public void blockEvent(BlockPosition blockposition, Block block, int i, int j) {
this.getBlockState(blockposition).triggerEvent(this, blockposition, i, j);
}
@Override
public WorldData getLevelData() {
return this.levelData;
}
public GameRules getGameRules() {
return this.levelData.getGameRules();
}
public float getThunderLevel(float f) {
return MathHelper.lerp(f, this.oThunderLevel, this.thunderLevel) * this.getRainLevel(f);
}
public void setThunderLevel(float f) {
float f1 = MathHelper.clamp(f, 0.0F, 1.0F);
this.oThunderLevel = f1;
this.thunderLevel = f1;
}
public float getRainLevel(float f) {
return MathHelper.lerp(f, this.oRainLevel, this.rainLevel);
}
public void setRainLevel(float f) {
float f1 = MathHelper.clamp(f, 0.0F, 1.0F);
this.oRainLevel = f1;
this.rainLevel = f1;
}
public boolean isThundering() {
return this.dimensionType().hasSkyLight() && !this.dimensionType().hasCeiling() ? (double) this.getThunderLevel(1.0F) > 0.9D : false;
}
public boolean isRaining() {
return (double) this.getRainLevel(1.0F) > 0.2D;
}
public boolean isRainingAt(BlockPosition blockposition) {
if (!this.isRaining()) {
return false;
} else if (!this.canSeeSky(blockposition)) {
return false;
} else if (this.getHeightmapPos(HeightMap.Type.MOTION_BLOCKING, blockposition).getY() > blockposition.getY()) {
return false;
} else {
BiomeBase biomebase = this.getBiome(blockposition);
return biomebase.getPrecipitation() == BiomeBase.Precipitation.RAIN && biomebase.warmEnoughToRain(blockposition);
}
}
public boolean isHumidAt(BlockPosition blockposition) {
BiomeBase biomebase = this.getBiome(blockposition);
return biomebase.isHumid();
}
@Nullable
public abstract WorldMap getMapData(String s);
public abstract void setMapData(String s, WorldMap worldmap);
public abstract int getFreeMapId();
public void globalLevelEvent(int i, BlockPosition blockposition, int j) {}
public CrashReportSystemDetails fillReportDetails(CrashReport crashreport) {
CrashReportSystemDetails crashreportsystemdetails = crashreport.addCategory("Affected level", 1);
crashreportsystemdetails.setDetail("All players", () -> {
int i = this.players().size();
return i + " total; " + this.players();
});
IChunkProvider ichunkprovider = this.getChunkSource();
Objects.requireNonNull(ichunkprovider);
crashreportsystemdetails.setDetail("Chunk stats", ichunkprovider::gatherStats);
crashreportsystemdetails.setDetail("Level dimension", () -> {
return this.dimension().location().toString();
});
try {
this.levelData.fillCrashReportCategory(crashreportsystemdetails, this);
} catch (Throwable throwable) {
crashreportsystemdetails.setDetailError("Level Data Unobtainable", throwable);
}
return crashreportsystemdetails;
}
public abstract void destroyBlockProgress(int i, BlockPosition blockposition, int j);
public void createFireworks(double d0, double d1, double d2, double d3, double d4, double d5, @Nullable NBTTagCompound nbttagcompound) {}
public abstract Scoreboard getScoreboard();
public void updateNeighbourForOutputSignal(BlockPosition blockposition, Block block) {
Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator();
while (iterator.hasNext()) {
EnumDirection enumdirection = (EnumDirection) iterator.next();
BlockPosition blockposition1 = blockposition.relative(enumdirection);
if (this.hasChunkAt(blockposition1)) {
IBlockData iblockdata = this.getBlockState(blockposition1);
if (iblockdata.is(Blocks.COMPARATOR)) {
iblockdata.neighborChanged(this, blockposition1, block, blockposition, false);
} else if (iblockdata.isRedstoneConductor(this, blockposition1)) {
blockposition1 = blockposition1.relative(enumdirection);
iblockdata = this.getBlockState(blockposition1);
if (iblockdata.is(Blocks.COMPARATOR)) {
iblockdata.neighborChanged(this, blockposition1, block, blockposition, false);
}
}
}
}
}
@Override
public DifficultyDamageScaler getCurrentDifficultyAt(BlockPosition blockposition) {
long i = 0L;
float f = 0.0F;
if (this.hasChunkAt(blockposition)) {
f = this.getMoonBrightness();
i = this.getChunkAt(blockposition).getInhabitedTime();
}
return new DifficultyDamageScaler(this.getDifficulty(), this.getDayTime(), i, f);
}
@Override
public int getSkyDarken() {
return this.skyDarken;
}
public void setSkyFlashTime(int i) {}
@Override
public WorldBorder getWorldBorder() {
return this.worldBorder;
}
public void sendPacketToServer(Packet<?> packet) {
throw new UnsupportedOperationException("Can't send packets to server unless you're on the client.");
}
@Override
public DimensionManager dimensionType() {
return this.dimensionType;
}
public ResourceKey<World> dimension() {
return this.dimension;
}
@Override
public Random getRandom() {
return this.random;
}
@Override
public boolean isStateAtPosition(BlockPosition blockposition, Predicate<IBlockData> predicate) {
return predicate.test(this.getBlockState(blockposition));
}
@Override
public boolean isFluidAtPosition(BlockPosition blockposition, Predicate<Fluid> predicate) {
return predicate.test(this.getFluidState(blockposition));
}
public abstract CraftingManager getRecipeManager();
public abstract ITagRegistry getTagManager();
public BlockPosition getBlockRandomPos(int i, int j, int k, int l) {
this.randValue = this.randValue * 3 + 1013904223;
int i1 = this.randValue >> 2;
return new BlockPosition(i + (i1 & 15), j + (i1 >> 16 & l), k + (i1 >> 8 & 15));
}
public boolean noSave() {
return false;
}
public GameProfilerFiller getProfiler() {
return (GameProfilerFiller) this.profiler.get();
}
public Supplier<GameProfilerFiller> getProfilerSupplier() {
return this.profiler;
}
@Override
public BiomeManager getBiomeManager() {
return this.biomeManager;
}
public final boolean isDebug() {
return this.isDebug;
}
public abstract LevelEntityGetter<Entity> getEntities();
protected void postGameEventInRadius(@Nullable Entity entity, GameEvent gameevent, BlockPosition blockposition, int i) {
// CraftBukkit start
GenericGameEvent event = new GenericGameEvent(org.bukkit.GameEvent.getByKey(CraftNamespacedKey.fromMinecraft(IRegistry.GAME_EVENT.getKey(gameevent))), new Location(this.getWorld(), blockposition.getX(), blockposition.getY(), blockposition.getZ()), (entity == null) ? null : entity.getBukkitEntity(), i);
getCraftServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
i = event.getRadius();
// CraftBukkit end
int j = SectionPosition.blockToSectionCoord(blockposition.getX() - i);
int k = SectionPosition.blockToSectionCoord(blockposition.getZ() - i);
int l = SectionPosition.blockToSectionCoord(blockposition.getX() + i);
int i1 = SectionPosition.blockToSectionCoord(blockposition.getZ() + i);
int j1 = SectionPosition.blockToSectionCoord(blockposition.getY() - i);
int k1 = SectionPosition.blockToSectionCoord(blockposition.getY() + i);
for (int l1 = j; l1 <= l; ++l1) {
for (int i2 = k; i2 <= i1; ++i2) {
Chunk chunk = this.getChunkSource().getChunkNow(l1, i2);
if (chunk != null) {
for (int j2 = j1; j2 <= k1; ++j2) {
chunk.getEventDispatcher(j2).post(gameevent, entity, blockposition);
}
}
}
}
}
@Override
public long nextSubTickCount() {
return (long) (this.subTickCount++);
}
public boolean shouldDelayFallingBlockEntityRemoval(Entity.RemovalReason entity_removalreason) {
return false;
}
}
| 41.705635 | 438 | 0.659474 |
dc14b985815fcf3c8bdcf02f04703d6101d79f7d | 6,721 | /*
* Copyright (C) 2017 Orange
*
* This software is distributed under the terms and conditions of the 'Apache-2.0'
* license which can be found in the file 'LICENSE.txt' in this package distribution
* or at 'http://www.apache.org/licenses/LICENSE-2.0'.
*/
package com.orange.common.logging.web;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.MDC;
/**
* A {@link Filter servlet filter} that adds a generated unique request ID to
* the logging context ({@link MDC})
* <p>
* Requires SLF4J as the logging facade API.
* <p>
* With a log management system such as ELK, this will help you track a complete
* callflow, filtering logs from a unique request. Quite valuable when your
* system processes thousands of requests per second and produces terabytes of
* logs each day...
* <p>
* Note that in a micro-services architecture, upon calling other services you
* can transfer this generated {@code requestId} in a request header
* {@code X-Track-RequestId}, thus implementing an end-to-end callflow tracking.
*
* <h2>configuration</h2>
* The request attribute, MDC attribute and request header can be overridden programmatically,
* with filter init parameters or Java properties:
*
* <table border=1>
* <tr>
* <th>parameter</th>
* <th>Java property</th>
* <th>filter init param</th>
* <th>default value</th>
* </tr>
* <tr>
* <td>request header name</td>
* <td>{@code slf4j.tools.request_filter.header}</td>
* <td>{@code header}</td>
* <td>{@code X-Track-RequestId}</td>
* </tr>
* <tr>
* <td>request attribute name</td>
* <td>{@code slf4j.tools.request_filter.attribute}</td>
* <td>{@code attribute}</td>
* <td>{@code track.requestId}</td>
* </tr>
* <tr>
* <td>MDC attribute name</td>
* <td>{@code slf4j.tools.request_filter.mdc}</td>
* <td>{@code mdc}</td>
* <td>{@code requestId}</td>
* </tr>
* </table>
*
* <h2>web.xml configuration example</h2>
*
* <pre style="font-size: medium">
* <?xml version="1.0" encoding="UTF-8"?>
* <web-app>
*
* <!-- filter declaration with init params -->
* <filter>
* <filter-name>RequestIdFilter</filter-name>
* <filter-class>com.orange.experts.utils.logging.web.RequestIdFilter</filter-class>
* <init-param>
* <!-- example: request id is passed by Apache mod_unique_id -->
* <param-name>header</param-name>
* <param-value>UNIQUE_ID</param-value>
* </init-param>
* </filter>
*
* <!-- filter mapping -->
* <filter-mapping>
* <filter-name>RequestIdFilter</filter-name>
* <url-pattern>/*</url-pattern>
* </filter-mapping>
* </web-app>
* </pre>
*
* @author pismy
*/
public class RequestIdFilter implements Filter {
private String headerName;
private String attributeName;
private String mdcName;
/**
* Default constructor
* <p>
* Retrieves configuration from Java properties (see class doc)
*/
public RequestIdFilter() {
headerName = System.getProperty("slf4j.tools.request_filter.header", "X-Track-RequestId");
attributeName = System.getProperty("slf4j.tools.request_filter.attribute", "track.requestId");
mdcName = System.getProperty("slf4j.tools.request_filter.mdc", "requestId");
}
/**
* Filter init method
* <p>
* Loads configuration from filter configuration
*/
public void init(FilterConfig filterConfig) throws ServletException {
headerName = getConfig(filterConfig, "header", headerName);
attributeName = getConfig(filterConfig, "attribute", attributeName);
mdcName = getConfig(filterConfig, "mdc", mdcName);
}
private String getConfig(FilterConfig filterConfig, String param, String defaultValue) {
String valueFromConfig = filterConfig.getInitParameter(param);
return valueFromConfig == null ? defaultValue : valueFromConfig;
}
/**
* The (incoming) request header name specifying the request ID
* <p>
* That can be used when chaining several tiers, for end-to-end callflow tracking.
* <p>
* Default: {@code X-Track-RequestId}
*/
public String getHeaderName() {
return headerName;
}
/**
* The (incoming) request header name specifying the request ID
* <p>
* That can be used when chaining several tiers, for end-to-end callflow tracking.
* <p>
* Default: {@code X-Track-RequestId}
*/
public void setHeaderName(String headerName) {
this.headerName = headerName;
}
/**
* The internal attribute name where the request ID will be stored
* <p>
* Default: {@code track.requestId}
*/
public String getAttributeName() {
return attributeName;
}
/**
* The internal attribute name where the request ID will be stored
* <p>
* Default: {@code track.requestId}
*/
public void setAttributeName(String attributeName) {
this.attributeName = attributeName;
}
/**
* The MDC attribute name that will be used to store the request ID
* <p>
* Default: {@code requestId}
*/
public String getMdcName() {
return mdcName;
}
/**
* The MDC attribute name that will be used to store the request ID
* <p>
* Default: {@code requestId}
*/
public void setMdcName(String mdcName) {
this.mdcName = mdcName;
}
/**
* Filter implementation
* <ul>
* <li>checks whether the current request has an attached request id,
* <li>if not, tries to get one from request headers (implements end-to-end
* callflow traceability),
* <li>if not, generates one
* <li>attaches it to the request (as an attribute) and to the {@link MDC}
* context.
* </ul>
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// checks whether the current request has an attached request id
String reqId = (String) request.getAttribute(attributeName);
if (reqId == null) {
// retrieve id from request headers
if (request instanceof HttpServletRequest) {
reqId = ((HttpServletRequest) request).getHeader(headerName);
}
if (reqId == null) {
// no requestId (either from attributes or headers): generate
// one
reqId = Long.toHexString(System.nanoTime());
}
// attach to request
request.setAttribute(attributeName, reqId);
}
// attach to MDC context
MDC.put(mdcName, reqId);
try {
chain.doFilter(request, response);
} finally {
// remove from MDC context
MDC.remove(mdcName);
}
}
public void destroy() {
}
} | 29.60793 | 129 | 0.690373 |
d1a612ca3b4e8bc02a2bffc37f654e42d463bb87 | 1,348 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.dadoco.cat.event;
import com.dadoco.cat.model.Contribuyente;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author dfcalderio
*/
public class BuscadorContribuyente {
private String tipoIdentificacion;
private String numeroIdentificacion;
private String nombreContribuyente;
private List<Contribuyente> listaContribuyentes = null;
public BuscadorContribuyente(){
listaContribuyentes = new ArrayList<Contribuyente>();
}
public String getTipoIdentificacion() {
return tipoIdentificacion;
}
public void setTipoIdentificacion(String tipoIdentificacion) {
this.tipoIdentificacion = tipoIdentificacion;
}
public String getNumeroIdentificacion() {
return numeroIdentificacion;
}
public void setNumeroIdentificacion(String numeroIdentificacion) {
this.numeroIdentificacion = numeroIdentificacion;
}
public String getNombreContribuyente() {
return nombreContribuyente;
}
public void setNombreContribuyente(String nombreContribuyente) {
this.nombreContribuyente = nombreContribuyente;
}
}
| 24.962963 | 79 | 0.722552 |
4eed24d480f5a57b0ecaf9eef9fdf6ad507af95d | 7,095 | /*
* The MIT License (MIT)
*
* Copyright (c) 2017 Red Hat, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.cloudstats;
import org.junit.Test;
import java.util.Arrays;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
/**
* @author ogondza.
*/
public class HealthTest {
// Use since moment to base ages on to avoid undesired millisecond differences cased by the speed of test execution
public final long NOW = System.currentTimeMillis();
public static final ProvisioningActivity.Id SUCCESS_ID = new ProvisioningActivity.Id("Success");
public static final ProvisioningActivity.Id FAILURE_ID = new ProvisioningActivity.Id("Failure");
public static final ProvisioningActivity SUCCESS = new ProvisioningActivity(SUCCESS_ID);
public static final ProvisioningActivity FAILURE = new ProvisioningActivity(FAILURE_ID);
public static final PhaseExecutionAttachment FAILED_ATTACHMENT = new PhaseExecutionAttachment(ProvisioningActivity.Status.FAIL, "It failed alright");
static {
FAILURE.attach(ProvisioningActivity.Phase.PROVISIONING, FAILED_ATTACHMENT);
}
@Test
public void overall() throws Exception {
Health.Report actual = health().getOverall();
assertEquals(new Health.Report(Float.NaN), actual);
assertEquals("?", actual.toString());
actual = health(SUCCESS).getOverall();
assertEquals(new Health.Report(100), actual);
assertEquals("100%", actual.toString());
actual = health(FAILURE).getOverall();
assertEquals(new Health.Report(0), actual);
assertEquals("0%", actual.toString());
assertEquals("66.7%", health(SUCCESS, FAILURE, SUCCESS).getOverall().toString());
}
@Test
public void currentTrivial() throws Exception {
Health.Report actual = health().getCurrent();
assertEquals(new Health.Report(Float.NaN), actual);
assertEquals("?", actual.toString());
actual = health(success(0)).getCurrent();
assertFalse(Float.isNaN(actual.getPercentage()));
assertThat(actual.getPercentage(), greaterThanOrEqualTo(99f));
actual = health(failure(0)).getCurrent();
assertFalse(Float.isNaN(actual.getPercentage()));
assertThat(actual.getPercentage(), lessThanOrEqualTo(1f));
actual = health(success(60)).getCurrent();
assertFalse(Float.isNaN(actual.getPercentage()));
assertThat(actual.getPercentage(), greaterThanOrEqualTo(99f));
actual = health(failure(60)).getCurrent();
assertFalse(Float.isNaN(actual.getPercentage()));
assertThat(actual.getPercentage(), lessThanOrEqualTo(1f));
}
@Test
public void currentSameAge() throws Exception {
Health.Report actual = health(failure(0), success(0)).getCurrent();
assertFalse(Float.isNaN(actual.getPercentage()));
assertThat(actual.getPercentage(), equalTo(50F));
assertEquals(
health(success(50), failure(10), failure(50), success(10)).getCurrent().getPercentage(),
health(success(10), failure(10), success(50), failure(50)).getCurrent().getPercentage(),
0D
);
}
@Test
public void currentDifferentAge() throws Exception {
// Current implementation considers same sequences equally successful regardless of the latest sample age
assertThat(health(success(1)).getCurrent(), equalTo(health(success(0)).getCurrent()));
assertEquals(
health(failure(1), failure(11)).getCurrent(),
health(failure(100), failure(110)).getCurrent()
);
assertThat(
health(success(0), failure(1)).getCurrent(), lessThan(
health(success(0), failure(2)).getCurrent()
));
assertThat(
health(success(0), failure(1)).getCurrent(), lessThan(
health(success(1), failure(3)).getCurrent()
));
assertThat(
health(success(0), success(1), failure(2)).getCurrent(), greaterThan(
health(success(0), failure(1), success(2)).getCurrent()
));
}
@Test
public void timeDecay() throws Exception {
assertThat(
health(success(0), success(1000), success(2000), success(3000), success(4000), success(5000), success(6000)).getCurrent().getPercentage(),
equalTo(100F)
);
assertEquals(0, health(failure(0)).getCurrent().getPercentage(), 0F);
assertEquals(50, health(success(0), failure(1)).getCurrent().getPercentage(), 1F);
assertEquals(66, health(success(0), success(1), failure(2)).getCurrent().getPercentage(), 2F);
assertEquals(75, health(success(0), success(1), success(2), failure(3)).getCurrent().getPercentage(), 2F);
assertEquals(57, health(success(0), failure(10)).getCurrent().getPercentage(), 1F);
assertEquals(81, health(success(0), failure(100)).getCurrent().getPercentage(), 1F);
assertEquals(97, health(success(0), failure(1000)).getCurrent().getPercentage(), 1F);
assertEquals(99, health(success(0), failure(10000)).getCurrent().getPercentage(), 1F);
}
private Health health(ProvisioningActivity... pas) {
return new Health(Arrays.asList(pas));
}
private ProvisioningActivity success(int age){
return new ProvisioningActivity(SUCCESS_ID, NOW - age * 60 * 1000);
}
private ProvisioningActivity failure(int age){
ProvisioningActivity pa = new ProvisioningActivity(FAILURE_ID, NOW - age * 60 * 1000);
pa.attach(ProvisioningActivity.Phase.PROVISIONING, FAILED_ATTACHMENT);
return pa;
}
}
| 41.982249 | 154 | 0.684003 |
36d29f1109ecc8f09a8133860f77cfde72635131 | 6,430 | package tests;
import models.CampaignProduct;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.testng.Assert.assertTrue;
public class CampaignProductsTests extends TestBase {
@Test // check name, regular, price are correct on main page and product page
public void checkProductTest() {
List<CampaignProduct> mainPageList = campaignProductsFromMainPage();
CampaignProduct mainPageProduct = mainPageList.get(0);
openProductCampaignPage(0);
CampaignProduct product = infoFromProductPage();
assertThat(mainPageProduct, equalTo(product));
}
@Test //main Page - check colour is grey and stikethrough
public void regularPriceMainPageTest() {
mainPage();
WebElement campaign = wd.findElement(By.id("box-campaigns"));
List<WebElement> products = campaign.findElements(By.tagName("li"));
for (WebElement product : products) {
WebElement regularPrice = product.findElement(By.className("regular-price"));
String style = regularPrice.getCssValue("text-decoration").split(" ", 2)[0];
String color = regularPrice.getCssValue("color");
assertThat(style, equalTo("line-through"));
assertTrue(isColourGrey(color));
}
}
@Test //product Page - check colour is grey and stikethrough
public void regularPriceProductPageTest() {
mainPage();
openProductCampaignPage(0);
WebElement regularPrice = wd.findElement(By.cssSelector("div.information .regular-price"));
String style = regularPrice.getCssValue("text-decoration").split(" ", 2)[0];
String color = regularPrice.getCssValue("color");
assertThat(style, equalTo("line-through"));
assertTrue(isColourGrey(color));
}
@Test //main Page - check colour is red
public void campaignPriceColourMainPageTest() {
mainPage();
WebElement campaign = wd.findElement(By.id("box-campaigns"));
List<WebElement> products = campaign.findElements(By.cssSelector(".column.product.shadow"));
for (WebElement product : products) {
WebElement discountPrice = product.findElement(By.className("campaign-price"));
String color = discountPrice.getCssValue("color");
assertTrue(isColourRed(color));
}
}
@Test
public void campaignPriceColourProductPageTest() {
mainPage();
openProductCampaignPage(1);
WebElement discountPrice = wd.findElement(By.cssSelector("div.information .campaign-price"));
String color = discountPrice.getCssValue("color");
assertTrue(isColourRed(color));
}
private boolean isColourRed(String color) {
String s = color.replaceAll("[^\\d-\\s+]", "").trim();
List<String> str = Arrays.asList(s.split(" "));
List<String> newStr = new ArrayList<>();
newStr.add(str.get(1));
newStr.add(str.get(2));
return newStr.stream().allMatch((c) -> c.equals("0"));
}
private boolean isColourGrey(String color) {
String s = color.replaceAll("[^\\d-\\s+]", "").trim();
List<String> str = Arrays.asList(s.split(" "));
List<String> newStr = new ArrayList<>();
if (str.size() > 3) {
for (int i = 0; i < str.size() - 1; i++) {
newStr.add(str.get(i));
}
} else {
newStr = new ArrayList<>(str);
}
return newStr.stream().allMatch(c -> c.equals(str.get(1)));
}
@Test //main page
public void priceSizeMainPageTest() {
mainPage();
WebElement campaign = wd.findElement(By.id("box-campaigns"));
List<WebElement> products = campaign.findElements(By.tagName("li"));
for (WebElement product : products) {
WebElement regularPrice = product.findElement(By.className("regular-price"));
WebElement discountPrice = product.findElement(By.className("campaign-price"));
double discountSize = trimPx(discountPrice.getCssValue("font-size"));
double regularSize = trimPx(regularPrice.getCssValue("font-size"));
assertTrue(isSize(discountSize, regularSize));
}
}
@Test //product page
public void priceSizeProductPageTest() {
mainPage();
openProductCampaignPage(0);
WebElement discountPrice = wd.findElement(By.cssSelector("div.information .campaign-price"));
WebElement regularPrice = wd.findElement(By.cssSelector("div.information .regular-price"));
double discountSize = trimPx(discountPrice.getCssValue("font-size"));
double regularSize = trimPx(regularPrice.getCssValue("font-size"));
assertTrue(isSize(discountSize, regularSize));
}
private CampaignProduct infoFromProductPage() {
String name = wd.findElement(By.tagName("h1")).getAttribute("textContent");
String regularPrice = wd.findElement(By.cssSelector("div.information .regular-price")).getAttribute("textContent");
String discountPrice = wd.findElement(By.cssSelector("div.information .campaign-price")).getAttribute("textContent");
return new CampaignProduct().withName(name).withPrice(regularPrice).withDiscountPrice(discountPrice);
}
private List<CampaignProduct> campaignProductsFromMainPage() {
mainPage();
List<CampaignProduct> campaignProducts = new ArrayList<>();
WebElement campaign = wd.findElement(By.id("box-campaigns"));
List<WebElement> products = campaign.findElements(By.cssSelector(".column.product.shadow"));
for (WebElement product : products) {
String name = product.findElement(By.className("name")).getAttribute("textContent");
String regularPrice = product.findElement(By.className("regular-price")).getAttribute("textContent");
String discountPrice = product.findElement(By.className("campaign-price")).getAttribute("textContent");
campaignProducts.add(new CampaignProduct().withName(name).withPrice(regularPrice).withDiscountPrice(discountPrice));
}
return campaignProducts;
}
private void openProductCampaignPage(int id) {
WebElement campaign = wd.findElement(By.id("box-campaigns"));
campaign.findElements(By.tagName("li")).get(id).click();
}
private double trimPx(String font) {
return Double.parseDouble(font.replaceAll("[^0-9\\.,]", "").trim());
}
private boolean isSize(double discountP, double regularP) {
if (discountP > regularP) {
return true;
} else {
return false;
}
}
}
| 36.534091 | 122 | 0.706843 |
c1306711cf1590f9cc34ac0c059bb54a667905af | 502 | /*
Ex048 Faça um programa que calcule a soma entre todos os números impares que
são múltiplos de três e que se encontram no intervalo de 1 até 500.
*/
package ex048;
public class Ex048 {
public static void main(String[] args) {
int s = 0;
for (int c = 0; c <= 500; c+=3)
if(c % 2 == 1){
s = s+c;
}
System.out.printf("A soma de todos os números impares múltiplos de três no intervalo de 1 a 500 é %d\n",s);
}
}
| 22.818182 | 115 | 0.559761 |
72fb5eb70b3da62ef4d2b04432c36e1bede5fdb9 | 4,770 | /*
* Mastercard Loyalty Connect Service
* Connecting payment and retail loyalty into a single checkout experience
*
* The version of the OpenAPI document: 2.2.1
* Contact: [email protected]
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.mastercard.developer.mastercard_loyalty_connect_client.model;
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 io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
/**
* PaymentCardDetails
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-09-07T19:05:09.264+05:30[Asia/Calcutta]")
public class PaymentCardDetails {
public static final String SERIALIZED_NAME_BANK_CARD_NUMBER = "bankCardNumber";
@SerializedName(SERIALIZED_NAME_BANK_CARD_NUMBER)
private String bankCardNumber;
public static final String SERIALIZED_NAME_BANK_CARD_PRODUCT = "bankCardProduct";
@SerializedName(SERIALIZED_NAME_BANK_CARD_PRODUCT)
private String bankCardProduct;
public static final String SERIALIZED_NAME_PAYMENT_CARD_REFERENCE_ID = "paymentCardReferenceId";
@SerializedName(SERIALIZED_NAME_PAYMENT_CARD_REFERENCE_ID)
private String paymentCardReferenceId;
public PaymentCardDetails bankCardNumber(String bankCardNumber) {
this.bankCardNumber = bankCardNumber;
return this;
}
/**
* Payment Card number that represents a valid card the MLC user wants to connect
* @return bankCardNumber
**/
@ApiModelProperty(example = "XXXXXXXXXXXX4444", required = true, value = "Payment Card number that represents a valid card the MLC user wants to connect")
public String getBankCardNumber() {
return bankCardNumber;
}
public void setBankCardNumber(String bankCardNumber) {
this.bankCardNumber = bankCardNumber;
}
public PaymentCardDetails bankCardProduct(String bankCardProduct) {
this.bankCardProduct = bankCardProduct;
return this;
}
/**
* Card product assigned by the Issuer for the payment card
* @return bankCardProduct
**/
@ApiModelProperty(example = "BLACK", required = true, value = "Card product assigned by the Issuer for the payment card")
public String getBankCardProduct() {
return bankCardProduct;
}
public void setBankCardProduct(String bankCardProduct) {
this.bankCardProduct = bankCardProduct;
}
public PaymentCardDetails paymentCardReferenceId(String paymentCardReferenceId) {
this.paymentCardReferenceId = paymentCardReferenceId;
return this;
}
/**
* Unique reference key for a member's payment card
* @return paymentCardReferenceId
**/
@ApiModelProperty(example = "5f0d07c1-6fc4-4e74-9152-0e20bb7104d9", required = true, value = "Unique reference key for a member's payment card")
public String getPaymentCardReferenceId() {
return paymentCardReferenceId;
}
public void setPaymentCardReferenceId(String paymentCardReferenceId) {
this.paymentCardReferenceId = paymentCardReferenceId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PaymentCardDetails paymentCardDetails = (PaymentCardDetails) o;
return Objects.equals(this.bankCardNumber, paymentCardDetails.bankCardNumber) &&
Objects.equals(this.bankCardProduct, paymentCardDetails.bankCardProduct) &&
Objects.equals(this.paymentCardReferenceId, paymentCardDetails.paymentCardReferenceId);
}
@Override
public int hashCode() {
return Objects.hash(bankCardNumber, bankCardProduct, paymentCardReferenceId);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PaymentCardDetails {\n");
sb.append(" bankCardNumber: ").append(toIndentedString(bankCardNumber)).append("\n");
sb.append(" bankCardProduct: ").append(toIndentedString(bankCardProduct)).append("\n");
sb.append(" paymentCardReferenceId: ").append(toIndentedString(paymentCardReferenceId)).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(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 30.774194 | 156 | 0.743187 |
43c46546a57d0fbedef9e10bcc68db0c5afeaf5e | 1,167 | package com.examples.game.tetris.shape;
import java.awt.Color;
import static com.examples.game.tetris.common.Constants.BG_COLOR;
public final class ZShape extends AbstractShape {
private static final Color COLOR = new Color(255, 0, 0);
public ZShape(Point rotationPoint, RotationState state) {
super(rotationPoint, state, COLOR);
}
@Override
public boolean isRotatable(Color[][] fillingColors) {
if (isNotInBounds(1)) {
return false;
}
int rotPx = rotationPoint.x;
int rotPy = rotationPoint.y;
if (state == RotationState.DOWN || state == RotationState.UP) {
return fillingColors[rotPx + 1][rotPy + 1] == BG_COLOR
&& fillingColors[rotPx - 1][rotPy] == BG_COLOR;
}
return fillingColors[rotPx + 1][rotPy] == BG_COLOR
&& fillingColors[rotPx + 1][rotPy - 1] == BG_COLOR;
}
@Override
public synchronized void updateRotationState() {
resetPoints();
if (state == RotationState.UP || state == RotationState.DOWN) {
points[0].x += 1;
points[0].y -= 1;
} else {
points[1].x -= 1;
points[2].y += 1;
}
points[2].x += 1;
points[3].y += 1;
}
} | 24.829787 | 67 | 0.62982 |
af4e131e0252c4415f1d04deb61a1a185899a6fb | 203 | package gestione.pubblicazioni.service;
import java.util.List;
import gestione.pubblicazioni.entities.Fumetto;
public interface FumettoService {
List<Fumetto> getAll();
Fumetto add(Fumetto f);
}
| 15.615385 | 47 | 0.783251 |
8bdddc4ae6a41010ca5a182b4f7aaafd2857e178 | 545 | class org.junit.runners.ParentRunner$ClassRuleCollector implements org.junit.runners.model.MemberValueConsumer<org.junit.rules.TestRule> {
final java.util.List<org.junit.runners.RuleContainer$RuleEntry> entries;
public void accept(org.junit.runners.model.FrameworkMember<?>, org.junit.rules.TestRule);
public java.util.List<org.junit.rules.TestRule> getOrderedRules();
public void accept(org.junit.runners.model.FrameworkMember, java.lang.Object);
org.junit.runners.ParentRunner$ClassRuleCollector(org.junit.runners.ParentRunner$1);
}
| 68.125 | 138 | 0.816514 |
7d954b6c278a12d71c5468561ee3a7b9b3f164bf | 1,593 | package com.example.activitytest;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Register extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Button button1 = (Button) findViewById(R.id.button_1);
Button button2 = (Button) findViewById(R.id.button_2);
button1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
switch (v.getId()){
case R.id.button_1:Intent intent = new Intent(Register.this,FirstActivity.class);
startActivity(intent);
overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
break;
default:break;
}
}
});
button2.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
switch (v.getId()){
case R.id.button_2:Intent intent = new Intent(Register.this,FirstActivity.class);
startActivity(intent);
overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
break;
default:break;
}
}
});
}
}
| 34.630435 | 101 | 0.57941 |
82ac1b91c8ad40aaf5798b793a170a6779a840db | 394 |
package charj.translator;
public class LiteralType extends ClassSymbol implements Type {
public Type baseType;
public String literal;
public LiteralType(SymbolTable symtab, Type _baseType) {
super(symtab, _baseType.getTypeName());
baseType = _baseType;
}
public String getTypeName() {
return baseType.getTypeName() + "[" + literal + "]";
}
}
| 23.176471 | 62 | 0.667513 |
d3ed75e584c0ec3c762e1a045ac014c230a51757 | 2,103 | package extracells.gridblock;
import appeng.api.networking.*;
import appeng.api.networking.storage.IStorageGrid;
import appeng.api.parts.PartItemStack;
import appeng.api.storage.IMEMonitor;
import appeng.api.storage.data.IAEFluidStack;
import appeng.api.util.AEColor;
import appeng.api.util.DimensionalCoord;
import extracells.part.PartECBase;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.util.ForgeDirection;
import java.util.EnumSet;
public class ECBaseGridBlock implements IGridBlock {
protected AEColor color;
protected IGrid grid;
protected int usedChannels;
protected PartECBase host;
public ECBaseGridBlock(PartECBase _host) {
this.host = _host;
}
@Override
public final EnumSet<ForgeDirection> getConnectableSides() {
return EnumSet.noneOf(ForgeDirection.class);
}
@Override
public EnumSet<GridFlags> getFlags() {
return EnumSet.of(GridFlags.REQUIRE_CHANNEL);
}
public IMEMonitor<IAEFluidStack> getFluidMonitor() {
IGridNode node = this.host.getGridNode();
if (node == null)
return null;
IGrid grid = node.getGrid();
if (grid == null)
return null;
IStorageGrid storageGrid = grid.getCache(IStorageGrid.class);
if (storageGrid == null)
return null;
return storageGrid.getFluidInventory();
}
@Override
public final AEColor getGridColor() {
return this.color == null ? AEColor.Transparent : this.color;
}
@Override
public double getIdlePowerUsage() {
return this.host.getPowerUsage();
}
@Override
public final DimensionalCoord getLocation() {
return this.host.getLocation();
}
@Override
public IGridHost getMachine() {
return this.host;
}
@Override
public ItemStack getMachineRepresentation() {
return this.host.getItemStack(PartItemStack.Network);
}
@Override
public void gridChanged() {}
@Override
public final boolean isWorldAccessible() {
return false;
}
@Override
public void onGridNotification(GridNotification notification) {}
@Override
public final void setNetworkStatus(IGrid _grid, int _usedChannels) {
this.grid = _grid;
this.usedChannels = _usedChannels;
}
}
| 22.612903 | 69 | 0.763671 |
d0b9767a4d8301b48b8187064aed4bed685ed4f1 | 945 | package com.lt.hm.wovideo.utils;
import com.lt.hm.wovideo.interf.OnUpdateLocationListener;
import com.lt.hm.wovideo.interf.updateTagLister;
import java.util.ArrayList;
/**
* Created by xuchunhui on 16/8/17.
*/
public class UpdateRecommedMsg {
public ArrayList<updateTagLister> downloadListeners = new ArrayList<updateTagLister>();
private static UpdateRecommedMsg instance;
public static UpdateRecommedMsg getInstance() {
if (instance == null) {
synchronized (UpdateRecommedMsg.class) {
if (instance == null) {
instance = new UpdateRecommedMsg();
}
}
}
return instance;
}
public void addRegisterSucListeners(updateTagLister listener) {
this.downloadListeners.add(listener);
}
public void removeRegisterSucListeners(updateTagLister listener) {
this.downloadListeners.remove(listener);
}
}
| 27 | 91 | 0.667725 |
a166fad39e86acabd12b4a8958b2cde80449b395 | 14,256 | /*
* 07/28/2008
*
* RtfGenerator.java - Generates RTF via a simple Java API.
*
* This library is distributed under a modified BSD license. See the included
* RSyntaxTextArea.License.txt file for details.
*/
package org.fife.ui.rsyntaxtextarea;
import java.awt.Color;
import java.awt.Font;
import java.awt.Toolkit;
import java.util.ArrayList;
import java.util.List;
import org.fife.ui.rtextarea.RTextAreaBase;
/**
* Generates RTF text via a simple Java API.
* <p>
*
* The following RTF features are supported:
* <ul>
* <li>Fonts
* <li>Font sizes
* <li>Foreground and background colors
* <li>Bold, italic, and underline
* </ul>
*
* The RTF generated isn't really "optimized," but it will do, especially for
* small amounts of text, such as what's common when copy-and-pasting. It tries
* to be sufficient for the use case of copying syntax highlighted code:
* <ul>
* <li>It assumes that tokens changing foreground color often is fairly common.
* <li>It assumes that background highlighting is fairly uncommon.
* </ul>
*
* @author Robert Futrell
* @version 1.0
*/
public class RtfGenerator {
/**
* The default font size for RTF. This is point size, in half points.
*/
private static final int DEFAULT_FONT_SIZE = 12;// 24;
/**
* Returns the index of the specified item in a list. If the item is not in the
* list, it is added, and its new index is returned.
*
* @param list
* The list (possibly) containing the item.
* @param item
* The item to get the index of.
* @return The index of the item.
*/
private static int getColorIndex(final List<Color> list, final Color item) {
int pos = list.indexOf(item);
if (pos == -1) {
list.add(item);
pos = list.size() - 1;
}
return pos;
}
/**
* Returns the index of the specified font in a list of fonts. This method only
* checks for a font by its family name; its attributes such as bold and italic
* are ignored.
* <p>
*
* If the font is not in the list, it is added, and its new index is returned.
*
* @param list
* The list (possibly) containing the font.
* @param font
* The font to get the index of.
* @return The index of the font.
*/
private static int getFontIndex(final List<Font> list, final Font font) {
final String fontName = font.getFamily();
for (int i = 0; i < list.size(); i++) {
final Font font2 = list.get(i);
if (font2.getFamily().equals(fontName))
return i;
}
list.add(font);
return list.size() - 1;
}
/**
* Returns a good "default" monospaced font to use when Java's logical font
* "Monospaced" is found.
*
* @return The monospaced font family to use.
*/
private static String getMonospacedFontFamily() {
String family = RTextAreaBase.getDefaultFont().getFamily();
if ("Monospaced".equals(family))
family = "Courier";
return family;
}
private final List<Color> colorList;
private final StringBuilder document;
private final List<Font> fontList;
private boolean lastBold;
private int lastFGIndex;
private int lastFontIndex;
private int lastFontSize;
private boolean lastItalic;
private boolean lastWasControlWord;
/**
* Java2D assumes a 72 dpi screen resolution, but on Windows the screen
* resolution is either 96 dpi or 120 dpi, depending on your font display
* settings. This is an attempt to make the RTF generated match the size of
* what's displayed in the RSyntaxTextArea.
*/
private int screenRes;
/**
* Constructor.
*/
public RtfGenerator() {
this.fontList = new ArrayList<>(1); // Usually only 1.
this.colorList = new ArrayList<>(1); // Usually only 1.
this.document = new StringBuilder();
this.reset();
}
/**
* Adds a newline to the RTF document.
*
* @see #appendToDoc(String, Font, Color, Color)
*/
public void appendNewline() {
this.document.append("\\par");
this.document.append('\n'); // Just for ease of reading RTF.
this.lastWasControlWord = false;
}
/**
* Appends styled text to the RTF document being generated.
*
* @param text
* The text to append.
* @param f
* The font of the text. If this is <code>null</code>, the default
* font is used.
* @param fg
* The foreground of the text. If this is <code>null</code>, the
* default foreground color is used.
* @param bg
* The background color of the text. If this is <code>null</code>,
* the default background color is used.
* @see #appendNewline()
*/
public void appendToDoc(final String text, final Font f, final Color fg, final Color bg) {
this.appendToDoc(text, f, fg, bg, false);
}
/**
* Appends styled text to the RTF document being generated.
*
* @param text
* The text to append.
* @param f
* The font of the text. If this is <code>null</code>, the default
* font is used.
* @param fg
* The foreground of the text. If this is <code>null</code>, the
* default foreground color is used.
* @param bg
* The background color of the text. If this is <code>null</code>,
* the default background color is used.
* @param underline
* Whether the text should be underlined.
* @see #appendNewline()
*/
public void appendToDoc(final String text, final Font f, final Color fg, final Color bg, final boolean underline) {
this.appendToDoc(text, f, fg, bg, underline, true);
}
/**
* Appends styled text to the RTF document being generated.
*
* @param text
* The text to append.
* @param f
* The font of the text. If this is <code>null</code>, the default
* font is used.
* @param fg
* The foreground of the text. If this is <code>null</code>, the
* default foreground color is used.
* @param bg
* The background color of the text. If this is <code>null</code>,
* the default background color is used.
* @param underline
* Whether the text should be underlined.
* @param setFG
* Whether the foreground specified by <code>fg</code> should be
* honored (if it is non-<code>null</code>).
* @see #appendNewline()
*/
public void appendToDoc(final String text, final Font f, final Color fg, final Color bg, final boolean underline,
final boolean setFG) {
if (text != null) {
// Set font to use, if different from last addition.
final int fontIndex = f == null ? 0 : RtfGenerator.getFontIndex(this.fontList, f) + 1;
if (fontIndex != this.lastFontIndex) {
this.document.append("\\f").append(fontIndex);
this.lastFontIndex = fontIndex;
this.lastWasControlWord = true;
}
// Set styles to use.
if (f != null) {
final int fontSize = this.fixFontSize(f.getSize2D() * 2); // Half points!
if (fontSize != this.lastFontSize) {
this.document.append("\\fs").append(fontSize);
this.lastFontSize = fontSize;
this.lastWasControlWord = true;
}
if (f.isBold() != this.lastBold) {
this.document.append(this.lastBold ? "\\b0" : "\\b");
this.lastBold = !this.lastBold;
this.lastWasControlWord = true;
}
if (f.isItalic() != this.lastItalic) {
this.document.append(this.lastItalic ? "\\i0" : "\\i");
this.lastItalic = !this.lastItalic;
this.lastWasControlWord = true;
}
} else { // No font specified - assume neither bold nor italic.
if (this.lastFontSize != RtfGenerator.DEFAULT_FONT_SIZE) {
this.document.append("\\fs").append(RtfGenerator.DEFAULT_FONT_SIZE);
this.lastFontSize = RtfGenerator.DEFAULT_FONT_SIZE;
this.lastWasControlWord = true;
}
if (this.lastBold) {
this.document.append("\\b0");
this.lastBold = false;
this.lastWasControlWord = true;
}
if (this.lastItalic) {
this.document.append("\\i0");
this.lastItalic = false;
this.lastWasControlWord = true;
}
}
if (underline) {
this.document.append("\\ul");
this.lastWasControlWord = true;
}
// Set the foreground color.
if (setFG) {
int fgIndex = 0;
if (fg != null)
fgIndex = RtfGenerator.getColorIndex(this.colorList, fg) + 1;
if (fgIndex != this.lastFGIndex) {
this.document.append("\\cf").append(fgIndex);
this.lastFGIndex = fgIndex;
this.lastWasControlWord = true;
}
}
// Set the background color.
if (bg != null) {
final int pos = RtfGenerator.getColorIndex(this.colorList, bg);
this.document.append("\\highlight").append(pos + 1);
this.lastWasControlWord = true;
}
if (this.lastWasControlWord) {
this.document.append(' '); // Delimiter
this.lastWasControlWord = false;
}
this.escapeAndAdd(this.document, text);
// Reset everything that was set for this text fragment.
if (bg != null) {
this.document.append("\\highlight0");
this.lastWasControlWord = true;
}
if (underline) {
this.document.append("\\ul0");
this.lastWasControlWord = true;
}
}
}
/**
* Appends styled text to the RTF document being generated.
*
* @param text
* The text to append.
* @param f
* The font of the text. If this is <code>null</code>, the default
* font is used.
* @param bg
* The background color of the text. If this is <code>null</code>,
* the default background color is used.
* @param underline
* Whether the text should be underlined.
* @see #appendNewline()
*/
public void appendToDocNoFG(final String text, final Font f, final Color bg, final boolean underline) {
this.appendToDoc(text, f, null, bg, underline, false);
}
/**
* Appends some text to a buffer, with special care taken for special characters
* as defined by the RTF spec.
*
* <ul>
* <li>All tab characters are replaced with the string "<code>\tab</code>"
* <li>'\', '{' and '}' are changed to "\\", "\{" and "\}"
* </ul>
*
* @param text
* The text to append (with tab chars substituted).
* @param sb
* The buffer to append to.
*/
private void escapeAndAdd(final StringBuilder sb, final String text) {
final int count = text.length();
for (int i = 0; i < count; i++) {
final char ch = text.charAt(i);
switch (ch) {
case '\t':
// Micro-optimization: for syntax highlighting with
// tab indentation, there are often multiple tabs
// back-to-back at the start of lines, so don't put
// spaces between each "\tab".
sb.append("\\tab");
while (++i < count && text.charAt(i) == '\t')
sb.append("\\tab");
sb.append(' ');
i--; // We read one too far.
break;
case '\\':
case '{':
case '}':
sb.append('\\').append(ch);
break;
default:
if (ch <= 127)
sb.append(ch);
else
sb.append("\\u").append((int) ch);
break;
}
}
}
/**
* Returns a font point size, adjusted for the current screen resolution.
* <p>
*
* Java2D assumes 72 dpi. On systems with larger dpi (Windows, GTK, etc.), font
* rendering will appear too small if we simply return a Java "Font" object's
* getSize() value. We need to adjust it for the screen resolution.
*
* @param pointSize
* A Java Font's point size, as returned from
* <code>getSize2D()</code>.
* @return The font point size, adjusted for the current screen resolution. This
* will allow other applications to render fonts the same size as they
* appear in the Java application.
*/
private int fixFontSize(float pointSize) {
if (this.screenRes != 72)
pointSize = Math.round(pointSize * 72f / this.screenRes);
return (int) pointSize;
}
private String getColorTableRtf() {
// Example:
// "{\\colortbl ;\\red255\\green0\\blue0;\\red0\\green0\\blue255; }"
final StringBuilder sb = new StringBuilder();
sb.append("{\\colortbl ;");
for (final Color c : this.colorList) {
sb.append("\\red").append(c.getRed());
sb.append("\\green").append(c.getGreen());
sb.append("\\blue").append(c.getBlue());
sb.append(';');
}
sb.append("}");
return sb.toString();
}
private String getFontTableRtf() {
// Example:
// "{\\fonttbl{\\f0\\fmodern\\fcharset0 Courier;}}"
final StringBuilder sb = new StringBuilder();
// Workaround for text areas using the Java logical font "Monospaced"
// by default. There's no way to know what it's mapped to, so we
// just search for a monospaced font on the system.
final String monoFamilyName = RtfGenerator.getMonospacedFontFamily();
sb.append("{\\fonttbl{\\f0\\fnil\\fcharset0 " + monoFamilyName + ";}");
for (int i = 0; i < this.fontList.size(); i++) {
final Font f = this.fontList.get(i);
String familyName = f.getFamily();
if (familyName.equals("Monospaced"))
familyName = monoFamilyName;
sb.append("{\\f").append(i + 1).append("\\fnil\\fcharset0 ");
sb.append(familyName).append(";}");
}
sb.append('}');
return sb.toString();
}
/**
* Returns the RTF document created by this generator.
*
* @return The RTF document, as a <code>String</code>.
*/
public String getRtf() {
final StringBuilder sb = new StringBuilder();
sb.append("{");
// Header
sb.append("\\rtf1\\ansi\\ansicpg1252");
sb.append("\\deff0"); // First font in font table is the default
sb.append("\\deflang1033");
sb.append("\\viewkind4"); // "Normal" view
sb.append("\\uc\\pard\\f0");
sb.append("\\fs20"); // Font size in half-points (default 24)
sb.append(this.getFontTableRtf()).append('\n');
sb.append(this.getColorTableRtf()).append('\n');
// Content
sb.append(this.document);
sb.append("}");
// System.err.println("*** " + sb.length());
return sb.toString();
}
/**
* Resets this generator. All document information and content is cleared.
*/
public void reset() {
this.fontList.clear();
this.colorList.clear();
this.document.setLength(0);
this.lastWasControlWord = false;
this.lastFontIndex = 0;
this.lastFGIndex = 0;
this.lastBold = false;
this.lastItalic = false;
this.lastFontSize = RtfGenerator.DEFAULT_FONT_SIZE;
this.screenRes = Toolkit.getDefaultToolkit().getScreenResolution();
}
} | 29.576763 | 116 | 0.637065 |
b77ab72ca3453ae445c4a38171100a5b044e69f7 | 555 | package com.jeecms.cms.dao.assist;
import java.util.List;
import com.jeecms.cms.entity.assist.CmsWebservice;
import com.jeecms.common.hibernate4.Updater;
import com.jeecms.common.page.Pagination;
public interface CmsWebserviceDao {
public Pagination getPage(int pageNo, int pageSize);
public List<CmsWebservice> getList(String type);
public CmsWebservice findById(Integer id);
public CmsWebservice save(CmsWebservice bean);
public CmsWebservice updateByUpdater(Updater<CmsWebservice> updater);
public CmsWebservice deleteById(Integer id);
} | 26.428571 | 70 | 0.812613 |
4be73495d97a3f99d4a17085681e988714552bc4 | 5,184 | // ============================================================================
//
// Copyright (C) 2006-2018 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.repository.ui.wizards.metadata.connection.files.xml;
import org.eclipse.jface.dialogs.IDialogPage;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.widgets.Composite;
import org.talend.core.model.metadata.builder.connection.MetadataTable;
import org.talend.core.model.metadata.builder.connection.XmlFileConnection;
import org.talend.core.model.properties.ConnectionItem;
import org.talend.core.model.xml.XmlArray;
import org.talend.cwm.helper.ConnectionHelper;
import org.talend.cwm.helper.TableHelper;
import org.talend.metadata.managment.ui.wizard.AbstractForm;
import org.talend.repository.metadata.ui.wizards.form.AbstractXmlFileStepForm;
/**
* Use to create a new connection to a File. Page allows setting a file.
*/
public class XmlFileWizardPage extends WizardPage {
protected ConnectionItem connectionItem;
protected int step;
protected boolean creation;
protected AbstractXmlFileStepForm currentComposite;
protected final String[] existingNames;
protected boolean isRepositoryObjectEditable;
/**
* DOC ocarbone XmlFileWizardPage constructor comment.
*
* @param step
* @param connection
* @param isRepositoryObjectEditable
* @param existingNames
*/
public XmlFileWizardPage(int step, ConnectionItem connectionItem, boolean isRepositoryObjectEditable, String[] existingNames) {
super("wizardPage"); //$NON-NLS-1$
this.step = step;
this.connectionItem = connectionItem;
this.existingNames = existingNames;
this.isRepositoryObjectEditable = isRepositoryObjectEditable;
}
public XmlFileWizardPage(boolean creation, ConnectionItem connectionItem, boolean isRepositoryObjectEditable,
String[] existingNames) {
super("wizardPage"); //$NON-NLS-1$
this.creation = creation;
this.connectionItem = connectionItem;
this.existingNames = existingNames;
this.isRepositoryObjectEditable = isRepositoryObjectEditable;
}
public XmlFileWizardPage(boolean creation, int step, ConnectionItem connectionItem, boolean isRepositoryObjectEditable,
String[] existingNames) {
this(step, connectionItem, isRepositoryObjectEditable, existingNames);
this.creation = creation;
}
/**
*
* @see IDialogPage#createControl(Composite)
*/
public void createControl(final Composite parent) {
currentComposite = null;
if (step == 1) {
currentComposite = new XmlFileStep1Form(creation, parent, connectionItem, existingNames);
} else if (step == 2) {
currentComposite = new XmlFileStep2Form(parent, connectionItem);
} else if (step == 3) {
MetadataTable metadataTable = ConnectionHelper.getTables(connectionItem.getConnection())
.toArray(new MetadataTable[0])[0];
currentComposite = new XmlFileStep3Form(parent, connectionItem, metadataTable, TableHelper.getTableNames(
((XmlFileConnection) connectionItem.getConnection()), metadataTable.getLabel()));
}
currentComposite.setReadOnly(!isRepositoryObjectEditable);
currentComposite.setPage(this);
AbstractForm.ICheckListener listener = new AbstractForm.ICheckListener() {
public void checkPerformed(final AbstractForm source) {
if (source.isStatusOnError()) {
XmlFileWizardPage.this.setPageComplete(false);
setErrorMessage(source.getStatus());
} else {
XmlFileWizardPage.this.setPageComplete(isRepositoryObjectEditable);
setErrorMessage(null);
setMessage(source.getStatus());
}
}
};
currentComposite.setListener(listener);
setControl((Composite) currentComposite);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.dialogs.DialogPage#dispose()
*/
@Override
public void dispose() {
XmlArray.setLimitToDefault();
super.dispose();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.dialogs.DialogPage#setVisible(boolean)
*/
@Override
public void setVisible(boolean visible) {
super.setVisible(visible);
if (visible) {
((XmlFileWizard) getWizard()).setCurrentPage(this);
}
}
@Override
public IWizardPage getPreviousPage() {
if (step == 1) {
return null;
}
return super.getPreviousPage();
}
}
| 34.791946 | 131 | 0.656443 |
192f88ac5b39fd44f57620f4d9c4b680ef7e1b77 | 671 | package com.taoswork.tallycheck.descriptor.service.impl;
import com.taoswork.tallycheck.descriptor.metadata.processor.GeneralClassProcessor;
import com.taoswork.tallycheck.descriptor.metadata.processor.GeneralFieldProcessor;
import com.taoswork.tallycheck.descriptor.metadata.processor.IFieldProcessor;
/**
* Created by Gao Yuan on 2016/3/30.
*/
public class GeneralMetaServiceImpl extends BaseMetaServiceImpl{
public GeneralMetaServiceImpl() {
super(new GeneralClassProcessor() {
@Override
protected IFieldProcessor createTopFieldProcessor() {
return new GeneralFieldProcessor();
}
});
}
}
| 33.55 | 83 | 0.736215 |
3a04343bce40caa648f311bdcced69f9ebf4192d | 3,355 | package io.github.ealenxie.dingtalk;
import io.github.ealenxie.dingtalk.message.DingRobotMessage;
import org.apache.commons.codec.binary.Base64;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestClientResponseException;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
/**
* Created by EalenXie on 2021/12/1 14:43
* https://open.dingtalk.com/document/robots/custom-robot-access
* 钉钉机器人 API
*/
public class DingRobotClient {
private static final String DEFAULT_API_URL = "https://oapi.dingtalk.com/robot/send";
private final RestOperations restOperations;
private final HttpHeaders jsonHeader;
public DingRobotClient() {
this(new RestTemplate());
}
public DingRobotClient(RestOperations restOperations) {
this.restOperations = restOperations;
// 钉钉请求头为 application/json
jsonHeader = new HttpHeaders();
jsonHeader.setContentType(MediaType.APPLICATION_JSON);
}
/**
* 钉钉接口签名
*
* @param timestamp 时间戳
* @param secret 签名密钥
* @return 签名
*/
public static String sign(long timestamp, String secret) {
String stringToSign = timestamp + "\n" + secret;
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
return URLEncoder.encode(new String(Base64.encodeBase64(signData)), StandardCharsets.UTF_8.name());
} catch (NoSuchAlgorithmException | UnsupportedEncodingException | InvalidKeyException e) {
throw new UnsupportedOperationException(e);
}
}
/**
* 调用钉钉机器人接口
*
* @param message 钉钉机器人消息
* @param accessToken accessToken
* @param signKey signKey
*/
public ResponseEntity<String> sendMessage(DingRobotMessage message, String accessToken, String signKey) {
return sendMessage(DEFAULT_API_URL, message, accessToken, signKey);
}
/**
* 调用钉钉机器人接口
*
* @param url 接口URL
* @param message 钉钉机器人消息
* @param accessToken accessToken
* @param signKey signKey
*/
public ResponseEntity<String> sendMessage(String url, DingRobotMessage message, String accessToken, String signKey) {
try {
HttpEntity<DingRobotMessage> entity = new HttpEntity<>(message, jsonHeader);
long timeStamp = System.currentTimeMillis();
return restOperations.postForEntity(String.format("%s?access_token=%s×tamp=%s&sign=%s", url, accessToken, timeStamp, sign(timeStamp, signKey)), entity, String.class);
} catch (RestClientResponseException e) {
return ResponseEntity.status(e.getRawStatusCode()).body(e.getResponseBodyAsString());
}
}
}
| 36.467391 | 183 | 0.705812 |
cc8bfd4e683787aeda79555b21d40e950658f9e4 | 1,763 | /*
* Copyright 2016-present Open Networking Laboratory
*
* 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.onosproject.isis.controller.impl;
import org.onosproject.isis.controller.IsisInterface;
import org.onosproject.isis.controller.IsisProcess;
import java.util.List;
/**
* Represents of an ISIS process.
*/
public class DefaultIsisProcess implements IsisProcess {
private String processId;
private List<IsisInterface> isisInterfaceList;
/**
* Gets process ID.
*
* @return process ID
*/
public String processId() {
return processId;
}
/**
* Sets process ID.
*
* @param processId process ID
*/
public void setProcessId(String processId) {
this.processId = processId;
}
/**
* Gets list of ISIS interface details.
*
* @return list of ISIS interface details
*/
public List<IsisInterface> isisInterfaceList() {
return isisInterfaceList;
}
/**
* Sets list of ISIS interface details.
*
* @param isisInterfaceList list of ISIS interface details
*/
public void setIsisInterfaceList(List<IsisInterface> isisInterfaceList) {
this.isisInterfaceList = isisInterfaceList;
}
} | 27.123077 | 77 | 0.686897 |
40a85f85168a693542b5b70db0552887f18ed03d | 23,723 | package com.siberiadante.androidutil.util;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.content.FileProvider;
import com.siberiadante.androidutil.R;
import com.siberiadante.androidutil.SDAndroidLib;
import com.siberiadante.androidutil.bean.SDAppInfoBean;
import com.siberiadante.androidutil.bean.SDInstallAppInfoBean;
import com.siberiadante.androidutil.util.encrypt.SDSHA1Util;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/**
* Created: SiberiaDante
* Email: [email protected]
* GitHub: https://github.com/SiberiaDante
* 博客园:http://www.cnblogs.com/shen-hua/
* CreateTime: 2017/5/4.
* UpDateTime:
* Describe:获取应用/手机信息、判断应用是否安装,卸载/安装APP,手机网络面板设置等
*/
public class SDAppUtil {
public static final String TAG = SDAppUtil.class.getSimpleName();
private static final String CHECK_OP_NO_THROW = "checkOpNoThrow";
private static final String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";
public SDAppUtil() {
throw new UnsupportedOperationException("not init " + SDAppUtil.class.getName());
}
/**
* 获取App名称
*
* @return App名称
*/
public static String getAppName() {
return getAppName(SDAndroidLib.getContext().getPackageName());
}
/**
* 获取App名称
*
* @param packageName 包名
* @return App名称
*/
public static String getAppName(String packageName) {
if (isSpace(packageName)) return null;
try {
PackageManager pm = SDAndroidLib.getContext().getPackageManager();
PackageInfo pi = pm.getPackageInfo(packageName, 0);
return pi == null ? null : pi.applicationInfo.loadLabel(pm).toString();
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return null;
}
}
/**
* @param packageName
* @return
*/
private static boolean isSpace(String packageName) {
if (packageName == null) {
return true;
}
for (int i = 0, len = packageName.length(); i < len; ++i) {
if (!Character.isWhitespace(packageName.charAt(i))) {
return false;
}
}
return true;
}
/**
* 获取App版本名
*
* @return App版本名
*/
public static String getAppVersionName() {
return getAppVersionName(SDAndroidLib.getContext());
}
public static String getAppVersionName(Context context) {
return getAppVersionName(context.getPackageName());
}
/**
* 获取App版本名
*
* @param packageName 应用包名
* @return App版本名
*/
public static String getAppVersionName(String packageName) {
if (isSpace(packageName)) {
return SDAndroidLib.getContext().getString(R.string.can_not_find_package_name);
}
try {
PackageInfo pi = getPackageManager().getPackageInfo(packageName, 0);
return pi == null ? null : pi.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return SDAndroidLib.getContext().getString(R.string.can_not_find_version_name);
}
}
private static PackageManager getPackageManager() {
return SDAndroidLib.getContext().getPackageManager();
}
/**
* 获取App版本号
*
* @return App版本号
*/
public static int getAppVersionCode() {
return getAppVersionCode(SDAndroidLib.getContext().getPackageName());
}
/**
* 获取App版本号
*
* @param packageName 包名
* @return App版本码
*/
public static int getAppVersionCode(String packageName) {
if (isSpace(packageName)) return -1;
try {
PackageInfo pi = getPackageManager().getPackageInfo(packageName, 0);
return pi == null ? -1 : pi.versionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return -1;
}
}
public static int getAppVersionCode(Context context) {
return getAppVersionCode(context.getPackageName());
}
/**
* 获取App图标
*
* @return App图标
*/
public static Drawable getAppIcon() {
return getAppIcon(SDAndroidLib.getContext().getPackageName());
}
/**
* 获取App图标
*
* @param packageName 包名
* @return App图标
*/
public static Drawable getAppIcon(String packageName) {
if (isSpace(packageName)) return null;
try {
PackageManager pm = SDAndroidLib.getContext().getPackageManager();
PackageInfo pi = pm.getPackageInfo(packageName, 0);
return pi == null ? null : pi.applicationInfo.loadIcon(pm);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return null;
}
}
/**
* 获取App信息
* <p>SDAppInfoBean(名称,图标,包名,版本号,版本Code,是否系统应用)</p>
*
* @return 当前应用的AppInfo
*/
public static SDAppInfoBean getAppInfo() {
return getAppInfo(SDAndroidLib.getContext().getPackageName());
}
/**
* 获取App信息
* <p>SDAppInfoBean(名称,图标,包名,版本号,版本Code,是否系统应用)</p>
*
* @param packageName 包名
* @return 当前应用的AppInfo
*/
public static SDAppInfoBean getAppInfo(String packageName) {
try {
PackageManager pm = SDAndroidLib.getContext().getPackageManager();
PackageInfo pi = pm.getPackageInfo(packageName, 0);
return getBean(pm, pi);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return null;
}
}
/**
* 得到AppInfo的Bean
*
* @param pm 包的管理
* @param pi 包的信息
* @return AppInfo类
*/
private static SDAppInfoBean getBean(PackageManager pm, PackageInfo pi) {
if (pm == null || pi == null) {
return null;
}
ApplicationInfo ai = pi.applicationInfo;
String packageName = pi.packageName;
String name = ai.loadLabel(pm).toString();
Drawable icon = ai.loadIcon(pm);
String packagePath = ai.sourceDir;
String versionName = pi.versionName;
int versionCode = pi.versionCode;
boolean isSystem = (ApplicationInfo.FLAG_SYSTEM & ai.flags) != 0;
return new SDAppInfoBean(packageName, name, icon, packagePath, versionName, versionCode, isSystem);
}
/**
* 判断该应用是否安装
*
* @return
*/
public static boolean isInstalledApp() {
return !isSpace(getPackageName()) && getPackageManager().getLaunchIntentForPackage(getPackageName()) != null;
}
/**
* 获取APP包名
*
* @return
*/
public static String getPackageName() {
return SDAndroidLib.getContext().getPackageName();
}
/**
* 判断App是否安装
*
* @param packageName 包名
* @return {@code true}: 已安装<br>{@code false}: 未安装
*/
public static boolean isInstalledApp(String packageName) {
return !isSpace(packageName) && getPackageManager().getLaunchIntentForPackage(packageName) != null;
}
/**
* 获取当前App的路径
*
* @return App路径
*/
public static String getAppPath() {
return getAppPath(SDAndroidLib.getContext().getPackageName());
}
/**
* 获取App路径
*
* @param packageName 包名
* @return App路径
*/
public static String getAppPath(String packageName) {
if (isSpace(packageName)) return null;
try {
PackageManager pm = SDAndroidLib.getContext().getPackageManager();
PackageInfo pi = pm.getPackageInfo(packageName, 0);
return pi == null ? null : pi.applicationInfo.sourceDir;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return null;
}
}
/**
* 判断App是否是Debug版本
*
* @return {@code true}: 是<br>{@code false}: 否
*/
public static boolean isAppDebug() {
return isAppDebug(SDAndroidLib.getContext().getPackageName());
}
/**
* 判断App是否是Debug版本
*
* @param packageName 包名
* @return {@code true}: 是<br>{@code false}: 否
*/
public static boolean isAppDebug(String packageName) {
if (isSpace(packageName)) return false;
try {
PackageManager pm = SDAndroidLib.getContext().getPackageManager();
ApplicationInfo ai = pm.getApplicationInfo(packageName, 0);
return ai != null && (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return false;
}
}
/**
* 判断App是否有root权限
*
* @return {@code true}: 是<br>{@code false}: 否
*/
public static boolean isAppRoot() {
SDShellUtil.CommandResult result = SDShellUtil.execCmd("echo root", true);
if (result.result == 0) {
return true;
}
if (result.errorMsg != null) {
SDToastUtil.toast("isAppRoot?---" + result.errorMsg);
}
return false;
}
/**
* 获取App签名
*
* @return App签名
*/
public static Signature[] getAppSignature() {
return getAppSignature(SDAndroidLib.getContext().getPackageName());
}
/**
* 获取App签名
*
* @param packageName 包名
* @return App签名
*/
public static Signature[] getAppSignature(String packageName) {
if (isSpace(packageName)) {
return null;
}
try {
@SuppressLint("PackageManagerGetSignatures")
PackageInfo pi = getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
return pi == null ? null : pi.signatures;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return null;
}
}
/**
* 获取应用签名的的SHA1值
* <p>可据此判断高德,百度地图key是否正确</p>
*
* @return 应用签名的SHA1字符串, 比如:53:FD:54:DC:19:0F:11:AC:B5:22:9E:F1:1A:68:88:1B:8B:E8:54:42
*/
public static String getAppSignatureSHA1() {
return getAppSignatureSHA1(SDAndroidLib.getContext().getPackageName());
}
/**
* 获取应用签名的的SHA1值
*
* @param packageName 包名
* @return 应用签名的SHA1字符串, 比如:53:FD:54:DC:19:0F:11:AC:B5:22:9E:F1:1A:68:88:1B:8B:E8:54:42
*/
public static String getAppSignatureSHA1(String packageName) {
Signature[] signature = getAppSignature(packageName);
if (signature == null) return null;
return SDSHA1Util.encrypt(signature[0].toByteArray()).replaceAll("(?<=[0-9A-F]{2})[0-9A-F]{2}", ":$0");
// return SDEncryptUtil.encryptSHA1ToString(signature[0].toByteArray()).
// replaceAll("(?<=[0-9A-F]{2})[0-9A-F]{2}", ":$0");
}
/**
* 判断手机通知权限是否打开
*
* @return
*/
public static boolean isNotificationEnable() {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
return true;
}
AppOpsManager mAppOps = (AppOpsManager) SDAndroidLib.getContext().getSystemService(Context.APP_OPS_SERVICE);
ApplicationInfo appInfo = SDAndroidLib.getContext().getApplicationInfo();
String pkg = SDAndroidLib.getContext().getApplicationContext().getPackageName();
int uid = appInfo.uid;
Class appOpsClass = null;
/* Context.APP_OPS_MANAGER */
try {
appOpsClass = Class.forName(AppOpsManager.class.getName());
Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE,
String.class);
Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);
int value = (Integer) opPostNotificationValue.get(Integer.class);
return ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return false;
}
/**
* 判断手机通知权限是否打开
*
* @return
*/
public static boolean isNotificationEnable(Context context) {
return NotificationManagerCompat.from(context).areNotificationsEnabled();
}
/**
* 判断App是否处于前台
*
* @return {@code true}: 是<br>{@code false}: 否
*/
public static boolean isAppInForeground() {
ActivityManager manager = (ActivityManager) SDAndroidLib.getContext().getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> infos = null;
if (manager != null) {
infos = manager.getRunningAppProcesses();
}
if (infos == null || infos.size() == 0) return false;
for (ActivityManager.RunningAppProcessInfo info : infos) {
if (info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
return info.processName.equals(SDAndroidLib.getContext().getPackageName());
}
}
return false;
}
/**
* 判断App是否处于前台
* <p>当不是查看当前App,且SDK大于21时,
* 需添加权限 {@code <uses-permission android:name="android.permission.PACKAGE_USAGE_STATS"/>}</p>
*
* @param packageName 包名
* @return {@code true}: 是<br>{@code false}: 否
*/
public static boolean isAppInForeground(String packageName) {
return !isSpace(packageName) && packageName.equals(SDProcessUtil.getForegroundProcessName());
}
/**
* 打开App
*/
public static void launchApp() {
launchApp(getPackageName());
}
/**
* 打开App
*
* @param packageName 包名
*/
public static void launchApp(String packageName) {
if (isSpace(packageName)) return;
SDAndroidLib.getContext().startActivity(SDIntentUtil.getLaunchAppIntent(packageName));
}
/**
* 打开App
*
* @param activity activity
* @param packageName 包名
* @param requestCode 请求值
*/
public static void launchApp(Activity activity, String packageName, int requestCode) {
if (isSpace(packageName)) return;
activity.startActivityForResult(SDIntentUtil.getLaunchAppIntent(packageName), requestCode);
}
/**
* 调用系统安装应用,支持7.0
*
* @param context
* @param filePath apk路径
* @param authority 7.0authority属性,参考sample
* @return
*/
public static boolean installApp(Context context, String filePath, String authority) {
final File file = SDFileUtil.getFileByPath(filePath);
return installApp(context, file, authority);
}
/**
* 调用系统安装应用,支持7.0
*
* @param context
* @param file apk文件
* @param authority 7.0authority属性,参考sample
* @return
*/
public static boolean installApp(Context context, File file, String authority) {
if (file == null || !file.exists() || !file.isFile()) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri apkUri;
// Android 7.0 以上不支持 file://协议 需要通过 FileProvider 访问 sd卡 下面的文件,所以 Uri 需要通过 FileProvider 构造,协议为 content://
if (Build.VERSION.SDK_INT >= 24) {
// content:// 协议
apkUri = FileProvider.getUriForFile(context, authority, file);
//Granting Temporary Permissions to a URI
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
// file:// 协议
apkUri = Uri.fromFile(file);
}
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
context.startActivity(intent);
return true;
}
/**
* 卸载APP
*
* @param packageName APP包名
*/
public static void unInstallApp(String packageName) {
if (isSpace(packageName)) {
return;
}
Intent intent = new Intent(Intent.ACTION_DELETE);
intent.setData(Uri.parse("package:" + packageName));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
SDAndroidLib.getContext().startActivity(intent);
}
/**
* 卸载APP
*
* @param activity
* @param packageName app包名
* @param requestCode 卸载请求码
*/
public static void unInstallApp(Activity activity, String packageName, int requestCode) {
if (isSpace(packageName)) {
return;
}
Intent intent = new Intent(Intent.ACTION_DELETE);
intent.setData(Uri.parse("package:" + packageName));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivityForResult(intent, requestCode);
}
/**
* 获取已安装的所有应用的包名和启动logo
*
* @return
*/
public static List<SDInstallAppInfoBean> getInstallAppInfo() {
return getInstallAppInfo(SDAndroidLib.getContext());
}
/**
* 获取已安装的所有应用的包名和启动logo
*
* @param context
* @return
*/
public static List<SDInstallAppInfoBean> getInstallAppInfo(Context context) {
return getInstallAppInfo(context, true);
}
public static List<SDInstallAppInfoBean> getInstallAppInfo(Context context, boolean showSystemApp) {
List<SDInstallAppInfoBean> appInfos = new ArrayList<>();
PackageManager packageManager = context.getPackageManager();
try {
List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
for (int i = 0; i < packageInfos.size(); i++) {
PackageInfo packageInfo = packageInfos.get(i);
//过滤掉系统app
if (!showSystemApp && (ApplicationInfo.FLAG_SYSTEM & packageInfo.applicationInfo.flags) != 0) {
continue;
}
SDInstallAppInfoBean appInfoBean = new SDInstallAppInfoBean();
appInfoBean.setAppPackageName(packageInfo.packageName);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
appInfoBean.setMinSdkVersion(packageInfo.applicationInfo.minSdkVersion);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
appInfoBean.setInstallLocation(packageInfo.installLocation);
}
appInfoBean.setVersionCode(packageInfo.versionCode);
appInfoBean.setUid(packageInfo.applicationInfo.uid);
if (packageInfo.applicationInfo.loadIcon(packageManager) == null) {
continue;
}
appInfoBean.setAppName(packageInfo.applicationInfo.loadLabel(getPackageManager()).toString());
appInfoBean.setImage(packageInfo.applicationInfo.loadIcon(packageManager));
appInfos.add(appInfoBean);
}
} catch (Exception e) {
SDLogUtil.i(TAG, "--------------------获取应用包信息失败---------------------");
}
return appInfos;
}
/**
* 静默安装App
* <p>非root需添加权限 {@code <uses-permission android:name="android.permission.INSTALL_PACKAGES" />}</p>
*
* @param filePath 文件路径
* @return {@code true}: 安装成功<br>{@code false}: 安装失败
*/
public static boolean installAppSilent(String filePath) {
File file = SDFileUtil.getFileByPath(filePath);
if (!SDFileUtil.isFileExists(file)) return false;
String command = "LD_LIBRARY_PATH=/vendor/lib:/system/lib pm install " + filePath;
SDShellUtil.CommandResult commandResult = SDShellUtil.execCmd(command, !isSystemApp(), true);
return commandResult.successMsg != null && commandResult.successMsg.toLowerCase().contains("success");
}
/**
* 判断App是否是系统应用
*
* @return {@code true}: 是<br>{@code false}: 否
*/
public static boolean isSystemApp() {
return isSystemApp(SDAndroidLib.getContext().getPackageName());
}
//TODO 以下-待测试~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
* 判断App是否是系统应用
*
* @param packageName 包名
* @return {@code true}: 是<br>{@code false}: 否
*/
public static boolean isSystemApp(String packageName) {
if (isSpace(packageName)) return false;
try {
PackageManager pm = SDAndroidLib.getContext().getPackageManager();
ApplicationInfo ai = pm.getApplicationInfo(packageName, 0);
return ai != null && (ai.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return false;
}
}
/**
* 后台卸载App
* <p>非root需添加权限 {@code <uses-permission android:name="android.permission.DELETE_PACKAGES" />}</p>
*
* @param packageName 包名
* @param isKeepData 是否保留数据
* @return {@code true}: 卸载成功<br>{@code false}: 卸载失败
*/
public static boolean uninstallAppSilent(String packageName, boolean isKeepData) {
if (isSpace(packageName)) return false;
String command = "LD_LIBRARY_PATH=/vendor/lib:/system/lib pm uninstall " + (isKeepData ? "-k " : "") + packageName;
SDShellUtil.CommandResult commandResult = SDShellUtil.execCmd(command, !isSystemApp(), true);
return commandResult.successMsg != null && commandResult.successMsg.toLowerCase().contains("success");
}
/**
* 清除App所有数据
*
* @param dirPaths 目录路径
* @return {@code true}: 成功<br>{@code false}: 失败
*/
public static boolean cleanAppData(String... dirPaths) {
File[] dirs = new File[dirPaths.length];
int i = 0;
for (String dirPath : dirPaths) {
dirs[i++] = new File(dirPath);
}
return cleanAppData(dirs);
}
/**
* 清除App所有数据
*
* @param dirs 目录
* @return {@code true}: 成功<br>{@code false}: 失败
*/
public static boolean cleanAppData(File... dirs) {
boolean isSuccess = SDCleanUtil.cleanInternalCache();
isSuccess &= SDCleanUtil.cleanInternalDbs();
isSuccess &= SDCleanUtil.cleanInternalSP();
isSuccess &= SDCleanUtil.cleanInternalFiles();
isSuccess &= SDCleanUtil.cleanExternalCache();
for (File dir : dirs) {
isSuccess &= SDCleanUtil.cleanCustomCache(dir);
}
return isSuccess;
}
/**
* 根据路径获取PackageName
*
* @param apkPath
* @return
*/
public String getPackageName(String apkPath) {
PackageManager pm = getPackageManager();
PackageInfo info = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
if (info != null) {
//既然获取了ApplicationInfo,那么和应用相关的一些信息就都可以获取了,具体可以获取什么大家可以看看ApplicationInfo这个类
ApplicationInfo appInfo = info.applicationInfo;
return appInfo.packageName;
}
return "";
}
}
| 32.058108 | 123 | 0.612149 |
69a59e65d27667ce9c1f9b6c58d4cb4e6d0ce244 | 327 | package com.north.base.service;
import java.io.Serializable;
/**
* 接口的描述
*
* @Author zhengxiangnan
* @Date 2018/6/25 14:40
*/
public interface RedisService {
void set(Serializable key, Object value);
void set(Serializable key, Object value, Long expireTime);
<T> T get(Serializable key,Class<T> clazz);
}
| 17.210526 | 62 | 0.69419 |
40e63d3f424a23e838b0ea3955e2d53c8e09554d | 506 | package com.lanshu.common.core.exceptions;
/**
* 公共异常
*
* @author Uncle Lan
* @date 2019/3/16 20:28
*/
public class CommonException extends RuntimeException {
private static final long serialVersionUID = 1L;
public CommonException() {
}
public CommonException(String msg) {
super(msg);
}
public CommonException(Throwable throwable) {
super(throwable);
}
public CommonException(Throwable throwable, String msg) {
super(throwable);
}
}
| 17.448276 | 61 | 0.656126 |
955be0c9cab5880734eae4e7873940ab1209676c | 751 | package es.upm.oeg.camel.oaipmh.component;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.ISODateTimeFormat;
public class TimeUtils {
/**
* Current time (UTC)
* @return
*/
public static String current(){
String timezone = "Zulu";//UTC
return toISO(DateTime.now(DateTimeZone.forID(timezone)).getMillis(), timezone);
}
public static String toISO(Long time, String timeZone){
DateTimeZone timezone = DateTimeZone.forID(timeZone);
return ISODateTimeFormat.dateTimeNoMillis().withZone(timezone).print(time);
}
public static Long fromISO(String time){
return ISODateTimeFormat.dateTimeNoMillis().parseMillis(time);
}
}
| 25.033333 | 87 | 0.69241 |
871f03da52a0b001358e299f0775af2763c52e0c | 423 | package com.wissen.e_commerce.pojo;
import java.util.List;
public class AddProductsBo extends BaseInventoryBo{
private List<ProductBo> products;
public List<ProductBo> getProducts() {
return products;
}
public void setProducts(List<ProductBo> products) {
this.products = products;
}
@Override
public String toString() {
return "AddProductsBo [products=" + products + "]";
}
}
| 17.625 | 54 | 0.687943 |
5d58f5147fc86e0110ab56afa13478854b4e7010 | 6,179 | /*
* Copyright (C) 2005 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com.
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jaspersoft.jasperserver.api.engine.jasperreports.common;
import java.io.Serializable;
import java.util.Map;
/**
* @author sanda zaharia
* @version $Id: XlsExportParametersBean.java 47331 2014-07-18 09:13:06Z kklein $
*/
public class XlsExportParametersBean extends AbstractExportParameters {
public static final String PROPERTY_XLS_PAGINATED = "com.jaspersoft.jrs.export.xls.paginated";
private Boolean detectCellType;
private Boolean onePagePerSheet;
private Boolean removeEmptySpaceBetweenRows;
private Boolean removeEmptySpaceBetweenColumns;
private Boolean whitePageBackground;
private Boolean ignoreGraphics;
private Boolean collapseRowSpan;
private Boolean ignoreCellBorder;
private Boolean fontSizeFixEnabled;
private Integer maximumRowsPerSheet;
private Map xlsFormatPatternsMap;
/**
* @return Returns the detectCellType.
*/
public Boolean getDetectCellType() {
return detectCellType;
}
/**
* @param detectCellType The detectCellType to set.
*/
public void setDetectCellType(Boolean detectCellType) {
this.detectCellType = detectCellType;
}
/**
* @return Returns the onePagePerSheet.
*/
public Boolean getOnePagePerSheet() {
return onePagePerSheet;
}
/**
* @param onePagePerSheet The onePagePerSheet to set.
*/
public void setOnePagePerSheet(Boolean onePagePerSheet) {
this.onePagePerSheet = onePagePerSheet;
}
/**
* @return Returns the removeEmptySpaceBetweenRows.
*/
public Boolean getRemoveEmptySpaceBetweenRows() {
return removeEmptySpaceBetweenRows;
}
/**
* @param removeEmptySpaceBetweenRows The removeEmptySpaceBetweenRows to set.
*/
public void setRemoveEmptySpaceBetweenRows(Boolean removeEmptySpaceBetweenRows) {
this.removeEmptySpaceBetweenRows = removeEmptySpaceBetweenRows;
}
/**
* @return Returns the removeEmptySpaceBetweenColumns.
*/
public Boolean getRemoveEmptySpaceBetweenColumns() {
return removeEmptySpaceBetweenColumns;
}
/**
* @param removeEmptySpaceBetweenColumns The removeEmptySpaceBetweenColumns to set.
*/
public void setRemoveEmptySpaceBetweenColumns(Boolean removeEmptySpaceBetweenColumns) {
this.removeEmptySpaceBetweenColumns = removeEmptySpaceBetweenColumns;
}
/**
* @return Returns the whitePageBackground.
*/
public Boolean getWhitePageBackground() {
return whitePageBackground;
}
/**
* @param whitePageBackground The whitePageBackground to set.
*/
public void setWhitePageBackground(Boolean whitePageBackground) {
this.whitePageBackground = whitePageBackground;
}
public Object getObject(){
return this;
}
public void setPropertyValues(Object object){
if(object instanceof XlsExportParametersBean){
XlsExportParametersBean bean =(XlsExportParametersBean)object;
this.setDetectCellType(bean.getDetectCellType());
this.setOnePagePerSheet(bean.getOnePagePerSheet());
this.setRemoveEmptySpaceBetweenRows(bean.getRemoveEmptySpaceBetweenRows());
this.setRemoveEmptySpaceBetweenColumns(bean.getRemoveEmptySpaceBetweenColumns());
this.setWhitePageBackground(bean.getWhitePageBackground());
this.setIgnoreGraphics(bean.getIgnoreGraphics());
this.setCollapseRowSpan(bean.getCollapseRowSpan());
this.setIgnoreCellBorder(bean.getIgnoreCellBorder());
this.setFontSizeFixEnabled(bean.getFontSizeFixEnabled());
this.setMaximumRowsPerSheet(bean.getMaximumRowsPerSheet());
this.setXlsFormatPatternsMap(bean.getXlsFormatPatternsMap());
}
}
/**
* @return Returns the ignoreGraphics.
*/
public Boolean getIgnoreGraphics() {
return ignoreGraphics;
}
/**
* @param ignoreGraphics The ignoreGraphics to set.
*/
public void setIgnoreGraphics(Boolean ignoreGraphics) {
this.ignoreGraphics = ignoreGraphics;
}
/**
* @return Returns the collapseRowSpan.
*/
public Boolean getCollapseRowSpan() {
return collapseRowSpan;
}
/**
* @param collapseRowSpan The collapseRowSpan to set.
*/
public void setCollapseRowSpan(Boolean collapseRowSpan) {
this.collapseRowSpan = collapseRowSpan;
}
/**
* @return Returns the ignoreCellBorder.
*/
public Boolean getIgnoreCellBorder() {
return ignoreCellBorder;
}
/**
* @param ignoreCellBorder The ignoreCellBorder to set.
*/
public void setIgnoreCellBorder(Boolean ignoreCellBorder) {
this.ignoreCellBorder = ignoreCellBorder;
}
/**
* @return Returns the maximumRowsPerSheet.
*/
public Integer getMaximumRowsPerSheet() {
return maximumRowsPerSheet;
}
/**
* @param maximumRowsPerSheet The maximumRowsPerSheet to set.
*/
public void setMaximumRowsPerSheet(Integer maximumRowsPerSheet) {
this.maximumRowsPerSheet = maximumRowsPerSheet;
}
/**
* @return Returns the fontSizeFixEnabled.
*/
public Boolean getFontSizeFixEnabled() {
return fontSizeFixEnabled;
}
/**
* @param fontSizeFixEnabled The fontSizeFixEnabled to set.
*/
public void setFontSizeFixEnabled(Boolean fontSizeFixEnabled) {
this.fontSizeFixEnabled = fontSizeFixEnabled;
}
/**
* @return Returns the xlsFormatPatternsMap.
*/
public Map getXlsFormatPatternsMap() {
return xlsFormatPatternsMap;
}
/**
* @param xlsFormatPatternsMap The xlsFormatPatternsMap to set.
*/
public void setXlsFormatPatternsMap(Map xlsFormatPatternsMap) {
this.xlsFormatPatternsMap = xlsFormatPatternsMap;
}
}
| 30.141463 | 95 | 0.770999 |
e39dd0abd01d917b3e40d254d49b6f89bd8415d1 | 277 | package io.gitlab.mkjeldsen.crontention;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
final class ContentionCacheKeyTest {
@Test
void equals_contract() {
EqualsVerifier.forClass(ContentionCacheKey.class).verify();
}
}
| 21.307692 | 67 | 0.754513 |
f8425a2af8ceef6f533f488ea349ea2819c1081e | 644 | package com.lx.hd.ui.activity;
import android.view.View;
import android.widget.LinearLayout;
import com.lx.hd.R;
import com.lx.hd.base.activity.BaseActivity;
/*
收费标准
*/
public class ChareStandardActivity extends BaseActivity {
private LinearLayout linear;
@Override
protected int getContentView() {
return R.layout.activity_charge_standard;
}
@Override
protected void initWidget() {
super.initWidget();
// setTitleIcon(R.mipmap.icon_car_home_samall);
// setTitleText("车辆租赁");
linear = (LinearLayout) findViewById(R.id.linear);
linear.setVisibility(View.GONE);
}
}
| 22.206897 | 58 | 0.690994 |
99589a3eb06aed53f255281e33aabdff0d597b84 | 1,579 | package com.my;
/**
* 两两交换链表中的节点
* @author shanghang
*/
public class SwapPairs {
public static class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public static ListNode swapPairs(ListNode head) {
//防止空节点或一个节点
if(head == null || head.next == null){
return head;
}
ListNode result = new ListNode(0);
result.next = head;
//交换节点head->p->q head->next = q q->next = p
ListNode first = result;
ListNode p = result.next;
ListNode q = result.next.next;
boolean isChange = true;
while (q !=null){
if(isChange){
ListNode tempList = q.next;
first.next = q;
p.next = tempList;
q.next = p;
//p = q ,q = p
ListNode tempNode = p;
p = q;
q = tempNode;
//然后右移两位
first = first.next;
p = p.next;
q = q.next;
isChange =false;
}else {
first = first.next;
p = p.next;
q = q.next;
isChange =true;
}
}
return result.next;
}
public static void main(String[] args) {
ListNode result = new ListNode(1);
result.next = new ListNode(2);
result.next.next = new ListNode(3);
result.next.next.next = new ListNode(4);
System.out.println(swapPairs(result).toString());
}
}
| 25.885246 | 57 | 0.457251 |
c65aeb93e1ec83989e32e76e1eca788688dbb22b | 1,759 | /**
*/
package context.tests;
import context.ContextFactory;
import context.Focus;
import junit.framework.TestCase;
import junit.textui.TestRunner;
/**
* <!-- begin-user-doc -->
* A test case for the model object '<em><b>Focus</b></em>'.
* <!-- end-user-doc -->
* @generated
*/
public class FocusTest extends TestCase {
/**
* The fixture for this Focus test case.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Focus fixture = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static void main(String[] args) {
TestRunner.run(FocusTest.class);
}
/**
* Constructs a new Focus test case with the given name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public FocusTest(String name) {
super(name);
}
/**
* Sets the fixture for this Focus test case.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void setFixture(Focus fixture) {
this.fixture = fixture;
}
/**
* Returns the fixture for this Focus test case.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Focus getFixture() {
return fixture;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see junit.framework.TestCase#setUp()
* @generated
*/
@Override
protected void setUp() throws Exception {
setFixture(ContextFactory.eINSTANCE.createFocus());
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see junit.framework.TestCase#tearDown()
* @generated
*/
@Override
protected void tearDown() throws Exception {
setFixture(null);
}
} //FocusTest
| 19.544444 | 61 | 0.570779 |
350d8d2fcdeeea6016ed716142340a58d6bd52a2 | 13,452 | /*******************************************************************************
* Copyright (c) 2008 SAP AG.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* SAP AG - initial API and implementation
*******************************************************************************/
package org.eclipse.mat.hprof;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.ref.PhantomReference;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.mat.SnapshotException;
import org.eclipse.mat.hprof.IHprofParserHandler.HeapObject;
import org.eclipse.mat.parser.io.PositionInputStream;
import org.eclipse.mat.parser.model.ClassImpl;
import org.eclipse.mat.parser.model.ObjectArrayImpl;
import org.eclipse.mat.parser.model.PrimitiveArrayImpl;
import org.eclipse.mat.snapshot.model.FieldDescriptor;
import org.eclipse.mat.snapshot.model.IClass;
import org.eclipse.mat.snapshot.model.IObject;
import org.eclipse.mat.snapshot.model.IPrimitiveArray;
import org.eclipse.mat.util.IProgressListener;
import org.eclipse.mat.util.MessageUtil;
import org.eclipse.mat.util.SimpleMonitor;
/**
* Parser used to read the hprof formatted heap dump
*/
public class Pass2Parser extends AbstractParser {
private IHprofParserHandler handler;
private SimpleMonitor.Listener monitor;
public Pass2Parser(IHprofParserHandler handler, SimpleMonitor.Listener monitor) {
this.handler = handler;
this.monitor = monitor;
}
public void read(File file) throws SnapshotException, IOException {
in = new PositionInputStream(new BufferedInputStream(new FileInputStream(file)));
final int dumpNrToRead = determineDumpNumber();
int currentDumpNr = 0;
try {
version = readVersion(in);
idSize = in.readInt();
if (idSize != 4 && idSize != 8)
throw new SnapshotException(Messages.Pass1Parser_Error_SupportedDumps);
in.skipBytes(8); // creation date
long fileSize = file.length();
long curPos = in.position();
while (curPos < fileSize) {
if (monitor.isProbablyCanceled())
throw new IProgressListener.OperationCanceledException();
monitor.totalWorkDone(curPos / 1000);
int record = in.readUnsignedByte();
in.skipBytes(4); // time stamp
long length = readUnsignedInt();
if (length < 0)
throw new SnapshotException(MessageUtil.format(Messages.Pass1Parser_Error_IllegalRecordLength, in
.position()));
switch (record) {
case Constants.Record.HEAP_DUMP:
case Constants.Record.HEAP_DUMP_SEGMENT:
if (dumpNrToRead == currentDumpNr)
readDumpSegments(length);
else
in.skipBytes(length);
if (record == Constants.Record.HEAP_DUMP)
currentDumpNr++;
break;
case Constants.Record.HEAP_DUMP_END:
currentDumpNr++;
default:
in.skipBytes(length);
break;
}
curPos = in.position();
}
} finally {
try {
in.close();
} catch (IOException ignore) {
}
}
}
private void readDumpSegments(long length) throws SnapshotException, IOException {
long segmentStartPos = in.position();
long segmentsEndPos = segmentStartPos + length;
while (segmentStartPos < segmentsEndPos) {
long workDone = segmentStartPos / 1000;
if (this.monitor.getWorkDone() < workDone) {
if (this.monitor.isProbablyCanceled())
throw new IProgressListener.OperationCanceledException();
this.monitor.totalWorkDone(workDone);
}
int segmentType = in.readUnsignedByte();
switch (segmentType) {
case Constants.DumpSegment.ROOT_UNKNOWN:
case Constants.DumpSegment.ROOT_STICKY_CLASS:
case Constants.DumpSegment.ROOT_MONITOR_USED:
in.skipBytes(idSize);
break;
case Constants.DumpSegment.ROOT_JNI_GLOBAL:
in.skipBytes(idSize * 2);
break;
case Constants.DumpSegment.ROOT_NATIVE_STACK:
case Constants.DumpSegment.ROOT_THREAD_BLOCK:
in.skipBytes(idSize + 4);
break;
case Constants.DumpSegment.ROOT_THREAD_OBJECT:
case Constants.DumpSegment.ROOT_JNI_LOCAL:
case Constants.DumpSegment.ROOT_JAVA_FRAME:
in.skipBytes(idSize + 8);
break;
case Constants.DumpSegment.CLASS_DUMP:
skipClassDump();
break;
case Constants.DumpSegment.INSTANCE_DUMP:
readInstanceDump(segmentStartPos);
break;
case Constants.DumpSegment.OBJECT_ARRAY_DUMP:
readObjectArrayDump(segmentStartPos);
break;
case Constants.DumpSegment.PRIMITIVE_ARRAY_DUMP:
readPrimitiveArrayDump(segmentStartPos);
break;
/* these were added for Android in 1.0.3 */
case Constants.DumpSegment.ANDROID_HEAP_DUMP_INFO:
in.skipBytes(idSize + 4);
break;
case Constants.DumpSegment.ANDROID_ROOT_INTERNED_STRING:
case Constants.DumpSegment.ANDROID_ROOT_FINALIZING:
case Constants.DumpSegment.ANDROID_ROOT_DEBUGGER:
case Constants.DumpSegment.ANDROID_ROOT_REFERENCE_CLEANUP:
case Constants.DumpSegment.ANDROID_ROOT_VM_INTERNAL:
case Constants.DumpSegment.ANDROID_UNREACHABLE:
in.skipBytes(idSize);
break;
case Constants.DumpSegment.ANDROID_ROOT_JNI_MONITOR:
in.skipBytes(idSize + 8);
break;
case Constants.DumpSegment.ANDROID_PRIMITIVE_ARRAY_NODATA_DUMP:
readPrimitiveArrayNoDataDump(segmentStartPos);
break;
default:
throw new SnapshotException(MessageUtil.format(Messages.Pass1Parser_Error_InvalidHeapDumpFile,
segmentType, segmentStartPos));
}
segmentStartPos = in.position();
}
}
private void skipClassDump() throws IOException {
in.skipBytes(7 * idSize + 8);
int constantPoolSize = in.readUnsignedShort();
for (int ii = 0; ii < constantPoolSize; ii++) {
in.skipBytes(2);
skipValue();
}
int numStaticFields = in.readUnsignedShort();
for (int i = 0; i < numStaticFields; i++) {
in.skipBytes(idSize);
skipValue();
}
int numInstanceFields = in.readUnsignedShort();
in.skipBytes((idSize + 1) * numInstanceFields);
}
static final Set<String> ignorableClasses = new HashSet<String>();
static {
ignorableClasses.add(WeakReference.class.getName());
ignorableClasses.add(SoftReference.class.getName());
ignorableClasses.add(PhantomReference.class.getName());
ignorableClasses.add("java.lang.ref.Finalizer");
}
private void readInstanceDump(long segmentStartPos) throws IOException {
long id = readID();
in.skipBytes(4);
long classID = readID();
int bytesFollowing = in.readInt();
long endPos = in.position() + bytesFollowing;
List<IClass> hierarchy = handler.resolveClassHierarchy(classID);
ClassImpl thisClazz = (ClassImpl) hierarchy.get(0);
HeapObject heapObject = new HeapObject(handler.mapAddressToId(id), id, thisClazz, thisClazz
.getHeapSizePerInstance());
heapObject.references.add(thisClazz.getObjectAddress());
// extract outgoing references
boolean isWeakReferenceClass = false;
for (IClass clazz : hierarchy) {
if (ignorableClasses.contains(clazz.getName())) {
isWeakReferenceClass = true;
break;
}
}
for (IClass clazz : hierarchy) {
for (FieldDescriptor field : clazz.getFieldDescriptors()) {
int type = field.getType();
if (type == IObject.Type.OBJECT) {
long refId = readID();
if (refId != 0 && !(isWeakReferenceClass && field.getName().equals("referent")))
heapObject.references.add(refId);
} else {
skipValue(type);
}
}
}
if (endPos != in.position())
throw new IOException(MessageUtil.format(Messages.Pass2Parser_Error_InsufficientBytesRead, segmentStartPos));
handler.addObject(heapObject, segmentStartPos);
}
private void readObjectArrayDump(long segmentStartPos) throws IOException {
long id = readID();
in.skipBytes(4);
int size = in.readInt();
long arrayClassObjectID = readID();
ClassImpl arrayType = (ClassImpl) handler.lookupClass(arrayClassObjectID);
if (arrayType == null)
throw new RuntimeException(MessageUtil.format(
Messages.Pass2Parser_Error_HandlerMustCreateFakeClassForAddress, Long
.toHexString(arrayClassObjectID)));
HeapObject heapObject = new HeapObject(handler.mapAddressToId(id), id, arrayType, ObjectArrayImpl
.doGetUsedHeapSize(arrayType, size));
heapObject.references.add(arrayType.getObjectAddress());
heapObject.isArray = true;
for (int ii = 0; ii < size; ii++) {
long refId = readID();
if (refId != 0)
heapObject.references.add(refId);
}
handler.addObject(heapObject, segmentStartPos);
}
private void readPrimitiveArrayDump(long segmentStartPost) throws SnapshotException, IOException {
long id = readID();
in.skipBytes(4);
int size = in.readInt();
byte elementType = in.readByte();
if ((elementType < IPrimitiveArray.Type.BOOLEAN) || (elementType > IPrimitiveArray.Type.LONG))
throw new SnapshotException(Messages.Pass1Parser_Error_IllegalType);
String name = IPrimitiveArray.TYPE[elementType];
ClassImpl clazz = (ClassImpl) handler.lookupClassByName(name, true);
if (clazz == null)
throw new RuntimeException(MessageUtil.format(Messages.Pass2Parser_Error_HandleMustCreateFakeClassForName,
name));
HeapObject heapObject = new HeapObject(handler.mapAddressToId(id), id, clazz, PrimitiveArrayImpl
.doGetUsedHeapSize(clazz, size, elementType));
heapObject.references.add(clazz.getObjectAddress());
heapObject.isArray = true;
handler.addObject(heapObject, segmentStartPost);
int elementSize = IPrimitiveArray.ELEMENT_SIZE[elementType];
in.skipBytes(elementSize * size);
}
/* Added for Android in 1.0.3 */
private void readPrimitiveArrayNoDataDump(long segmentStartPost)
throws SnapshotException, IOException {
long id = readID();
in.skipBytes(4);
int size = in.readInt();
byte elementType = in.readByte();
if ((elementType < IPrimitiveArray.Type.BOOLEAN)
|| (elementType > IPrimitiveArray.Type.LONG)) {
throw new SnapshotException(Messages.Pass1Parser_Error_IllegalType);
}
String name = IPrimitiveArray.TYPE[elementType];
ClassImpl clazz = (ClassImpl) handler.lookupClassByName(name, true);
if (clazz == null) {
throw new RuntimeException(MessageUtil.format(
Messages.Pass2Parser_Error_HandleMustCreateFakeClassForName,
name));
}
HeapObject heapObject = new HeapObject(handler.mapAddressToId(id), id, clazz,
PrimitiveArrayImpl.doGetUsedHeapSize(clazz, size, elementType));
heapObject.references.add(clazz.getObjectAddress());
heapObject.isArray = true;
handler.addObject(heapObject, segmentStartPost);
}
}
| 40.155224 | 122 | 0.5843 |
b012ddaccbabb2ad14ed9396b502a08ddfbfc61a | 8,280 | /*
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.osedu.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.kuali.coeus.common.impl.org;
import org.apache.commons.lang3.StringUtils;
import org.kuali.coeus.common.framework.org.Organization;
import org.kuali.coeus.common.framework.org.OrganizationYnq;
import org.kuali.coeus.common.framework.ynq.Ynq;
import org.kuali.coeus.common.framework.ynq.YnqService;
import org.kuali.coeus.propdev.impl.location.CongressionalDistrict;
import org.kuali.coeus.sys.framework.service.KcServiceLocator;
import org.kuali.kra.infrastructure.Constants;
import org.kuali.kra.maintenance.KraMaintainableImpl;
import org.kuali.rice.coreservice.framework.parameter.ParameterService;
import org.kuali.rice.kns.document.MaintenanceDocument;
import org.kuali.rice.kns.maintenance.Maintainable;
import org.kuali.rice.kns.web.ui.Field;
import org.kuali.rice.kns.web.ui.Row;
import org.kuali.rice.kns.web.ui.Section;
import org.kuali.rice.krad.service.SequenceAccessorService;
import java.util.List;
import java.util.Map;
public class OrganizationMaintenableImpl extends KraMaintainableImpl {
private static final long serialVersionUID = 7123853550462673935L;
public static final String ORGANIZATION_ID_SEQUENCE_NAME = "SEQ_ORGANIZATION_ID";
public static final String AUTO_GEN_ORGANIZATION_ID_PARM = "AUTO_GENERATE_ORGANIZATION_ID";
public static final String SECTION_ID = "Edit Organization";
public static final String ORGANIZATION_ID_NAME = "organizationId";
private transient ParameterService parameterService;
private transient SequenceAccessorService sequenceAccessorService;
/**
* This is a hook for initializing the BO from the maintenance framework.
* It initializes the {@link Explanation}s collection.
*
*/
@Override
public void setGenerateDefaultValues(String docTypeName) {
super.setGenerateDefaultValues(docTypeName);
if (getBusinessObject().getOrganizationYnqs() == null || getBusinessObject().getOrganizationYnqs().isEmpty()) {
initOrganizationYnq();
}
if (isAutoGenerateCode()) {
Organization organization = getBusinessObject();
organization.setOrganizationId(getSequenceAccessorService().getNextAvailableSequenceNumber(ORGANIZATION_ID_SEQUENCE_NAME, Organization.class).toString());
}
}
/**
* This is just trying to populate existing organization that has no ynq.
*/
@Override
public List<Section> getCoreSections(MaintenanceDocument document, Maintainable oldMaintainable) {
Organization organization = getBusinessObject();
if (organization.getOrganizationYnqs() == null || organization.getOrganizationYnqs().isEmpty()) {
initOrganizationYnq();
}
return super.getCoreSections(document, oldMaintainable);
}
/**
*
* This method generate organizationynqs list based on ynq type or 'organization'
*/
private void initOrganizationYnq() {
Organization organization = getBusinessObject();
List<OrganizationYnq> organizationYnqs = organization.getOrganizationYnqs();
if (!organizationYnqs.isEmpty()) {
throw new AssertionError();
}
List<Ynq> ynqs = getOrganizationTypeYnqs();
for (Ynq ynq : ynqs) {
OrganizationYnq organizationYnq = new OrganizationYnq();
organizationYnq.setYnq(ynq);
organizationYnq.setQuestionId(ynq.getQuestionId());
if (StringUtils.isNotBlank(organization.getOrganizationId())) {
organizationYnq.setOrganizationId(organization.getOrganizationId());
}
organizationYnqs.add(organizationYnq);
}
}
/**
*
* This method calls ynqservice to get ynq list of organization type.
* @return
*/
private List<Ynq> getOrganizationTypeYnqs() {
return KcServiceLocator.getService(YnqService.class).getYnq("O");
}
@Override
@SuppressWarnings("unchecked")
public Map<String, String> populateBusinessObject(Map<String, String> fieldValues, MaintenanceDocument maintenanceDocument, String methodToCall) {
Map<String, String> map = super.populateBusinessObject(fieldValues, maintenanceDocument, methodToCall);
formatCongressionalDistrict(getBusinessObject());
return map;
}
/**
* This method pads the district number to CongressionalDistrict.DISTRICT_NUMBER_LENGTH
* characters (A congressional district consists of a state code, followed by a dash,
* followed by a district number).
* @param organization
*/
private void formatCongressionalDistrict(Organization organization) {
String district = organization.getCongressionalDistrict();
if (district != null) {
int dashPosition = district.indexOf('-');
if (dashPosition >= 0) {
// everything up to, and including, the dash
String stateCodePlusDash = district.substring(0, dashPosition + 1);
String paddedDistrictNumber = StringUtils.leftPad(district.substring(dashPosition + 1), CongressionalDistrict.DISTRICT_NUMBER_LENGTH, '0');
organization.setCongressionalDistrict(stateCodePlusDash + paddedDistrictNumber);
}
}
}
@Override
public Organization getBusinessObject() {
return (Organization) super.getBusinessObject();
}
@Override
@SuppressWarnings("unchecked")
public List<Section> getSections(MaintenanceDocument document, Maintainable oldMaintainable) {
List<Section> sections = super.getSections(document, oldMaintainable);
if (isAutoGenerateCode()) {
disableOrganizationId(sections);
}
return sections;
}
protected void disableOrganizationId(List<Section> sections) {
for (Section section : sections) {
if (StringUtils.equals(section.getSectionId(), SECTION_ID)) {
for (Row row : section.getRows()) {
for (Field field : row.getFields()) {
if (StringUtils.equals(field.getPropertyName(), ORGANIZATION_ID_NAME)) {
field.setReadOnly(true);
}
}
}
}
}
}
@Override
public void processAfterCopy(MaintenanceDocument document, Map<String, String[]> parameters) {
super.processAfterCopy(document, parameters);
setGenerateDefaultValues(document.getDocumentHeader().getWorkflowDocument().getDocumentTypeName());
}
protected boolean isAutoGenerateCode() {
return getParameterService().getParameterValueAsBoolean(Constants.KC_GENERIC_PARAMETER_NAMESPACE,
Constants.KC_ALL_PARAMETER_DETAIL_TYPE_CODE, AUTO_GEN_ORGANIZATION_ID_PARM);
}
protected ParameterService getParameterService() {
if (parameterService == null) {
parameterService = KcServiceLocator.getService(ParameterService.class);
}
return parameterService;
}
public void setParameterService(ParameterService parameterService) {
this.parameterService = parameterService;
}
protected SequenceAccessorService getSequenceAccessorService() {
if(sequenceAccessorService == null) {
sequenceAccessorService = KcServiceLocator.getService(SequenceAccessorService.class);
}
return sequenceAccessorService;
}
public void setSequenceAccessorService(SequenceAccessorService sequenceAccessorService) {
this.sequenceAccessorService = sequenceAccessorService;
}
}
| 40.788177 | 166 | 0.697947 |
e893f2b164b622abaaf7ea674c9999df3a1c8323 | 386 | package com.atguigu.gmall.ums.mapper;
import com.atguigu.gmall.ums.entity.UserLoginLogEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 用户登陆记录表
*
* @author Edmund
* @email [email protected]
* @date 2021-05-14 00:29:52
*/
@Mapper
public interface UserLoginLogMapper extends BaseMapper<UserLoginLogEntity> {
}
| 21.444444 | 76 | 0.772021 |
2d1210fc06fd845c1fb71e8324c2cedd7e9565c8 | 623 | package marchsoft.modules.system.entity.dto;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import marchsoft.base.BaseDTO;
import java.io.Serializable;
/**
* description:JobDTO
*
* @author RenShiWei
* Date: 2020/11/24 17:26
*/
@EqualsAndHashCode(callSuper = true)
@Data
@NoArgsConstructor
public class JobDTO extends BaseDTO implements Serializable {
private Long id;
private Integer jobSort;
private String name;
private Boolean enabled;
public JobDTO(String name, Boolean enabled) {
this.name = name;
this.enabled = enabled;
}
}
| 18.323529 | 61 | 0.725522 |
b0b3e1008ad9f4a72111e4c9f3ad377f74dd6f94 | 1,539 | package com.drugbox.DAO;
import com.drugbox.Entity.UserInfo;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.List;
/**
* Created by 44247 on 2016/2/4 0004.
*/
@Transactional
@Component
public class UserInfoDAO {
@Autowired
@Qualifier("sessionFactory")
private SessionFactory sessionFactory;
@Transactional(readOnly = false)
public void update(UserInfo entity) {
this.getSession().update(entity);
}
@Transactional(readOnly = false)
public void delete(Serializable id) {
this.getSession().delete(this.findById(id));
}
public Session getSession() {
return this.sessionFactory.getCurrentSession();
}
@Transactional(readOnly = false)
public void save(UserInfo entity) {
this.getSession().save(entity);
}
public UserInfo findById(Serializable id) {
return (UserInfo) this.getSession().get(UserInfo.class, id);
}
public List<UserInfo> findByHQL(String hql, Object... params) {
Query query = this.getSession().createQuery(hql);
for (int i = 0; params != null && i < params.length; i++) {
query.setParameter(i, params);
}
return query.list();
}
}
| 27 | 68 | 0.697206 |
b869c3c740cb1f64d475efca7c35596824edf6ab | 1,062 | package org.pcsoft.app.jimix.app.ui.dialog;
import de.saxsys.mvvmfx.FxmlView;
import de.saxsys.mvvmfx.InjectViewModel;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
import org.pcsoft.app.jimix.app.ui.component.BlenderComboBox;
import org.pcsoft.framework.jfex.ui.component.paint.PaintPane;
import java.net.URL;
import java.util.ResourceBundle;
public class LayerCreateSimpleDialogView implements FxmlView<LayerCreateSimpleDialogViewModel>, Initializable {
@FXML
private BlenderComboBox cmbBelnder;
@FXML
private TextField txtName;
@FXML
private PaintPane paintPane;
@InjectViewModel
private LayerCreateSimpleDialogViewModel viewModel;
@Override
public void initialize(URL location, ResourceBundle resources) {
paintPane.selectedPaintProperty().bindBidirectional(viewModel.paintProperty());
txtName.textProperty().bindBidirectional(viewModel.nameProperty());
cmbBelnder.valueProperty().bindBidirectional(viewModel.blenderProperty());
}
}
| 33.1875 | 111 | 0.788136 |
acde9125cba404f64fd6b07e87af17e6d1483125 | 1,382 | package stacks;
import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.*;
public class PriorityStackTest {
@Test
public void offerTest() {
PriorityStack<Integer> stack = new PriorityStack<>(Integer::compareTo);
stack.offer(1);
stack.offer(2);
Assert.assertThat(stack.peek(), Is.is(2));
}
@Test
public void peekTest() {
PriorityStack<Integer> stack = new PriorityStack<>(Integer::compareTo);
stack.offer(1);
Assert.assertThat(stack.peek(), Is.is(1));
}
@Test
public void pollTest() {
PriorityStack<Integer> stack = new PriorityStack<>(Integer::compareTo);
stack.offer(1);
Assert.assertThat(stack.poll(), Is.is(1));
}
@Test
public void maxTest() {
PriorityStack<Integer> stack = new PriorityStack<>(Integer::compareTo);
stack.offer(5);
stack.offer(4);
stack.offer(3);
stack.offer(2);
stack.offer(1);
Assert.assertThat(stack.max(), Is.is(5));
}
@Test
public void minTest() {
PriorityStack<Integer> stack = new PriorityStack<>(Integer::compareTo);
stack.offer(7);
stack.offer(2);
stack.offer(1);
stack.offer(4);
stack.offer(5);
Assert.assertThat(stack.min(), Is.is(1));
}
} | 25.592593 | 79 | 0.596237 |
524474c3c9e4a475f33ada206e09c824013237fe | 5,551 | package se.qxx.protodb.test;
import static org.junit.Assert.*;
import java.io.File;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import se.qxx.protodb.JoinResult;
import se.qxx.protodb.ProtoDB;
import se.qxx.protodb.ProtoDBFactory;
import se.qxx.protodb.ProtoDBScanner;
import se.qxx.protodb.SearchOptions;
import se.qxx.protodb.Searcher;
import se.qxx.protodb.exceptions.DatabaseNotSupportedException;
import se.qxx.protodb.exceptions.IDFieldNotFoundException;
import se.qxx.protodb.exceptions.ProtoDBParserException;
import se.qxx.protodb.exceptions.SearchFieldNotFoundException;
import se.qxx.protodb.exceptions.SearchOptionsNotInitializedException;
import se.qxx.protodb.model.ProtoDBSearchOperator;
import se.qxx.protodb.test.TestDomain.RepObjectOne;
import se.qxx.protodb.test.TestDomain.SimpleTwo;
@RunWith(Parameterized.class)
public class TestSearchRepeated extends TestBase {
ProtoDB db = null;
@Parameters
public static Collection<Object[]> data() {
return getParams("testParamsFile");
}
public TestSearchRepeated(String driver, String connectionString) throws DatabaseNotSupportedException, ClassNotFoundException, SQLException {
db = ProtoDBFactory.getInstance(driver, connectionString);
clearDatabase(db, connectionString);
}
@Before
public void Setup() throws ClassNotFoundException, SQLException, IDFieldNotFoundException {
db.setupDatabase(TestDomain.RepObjectOne.newBuilder());
RepObjectOne o1 = RepObjectOne.newBuilder()
.setID(10)
.setHappycamper(555)
.addListOfObjects(SimpleTwo.newBuilder()
.setID(1)
.setDirector("directThis")
.setTitle("thisisatitle")
.build())
.addListOfObjects(SimpleTwo.newBuilder()
.setID(2)
.setDirector("no_way")
.setTitle("who_said_that")
.build())
.build();
RepObjectOne o2 = RepObjectOne.newBuilder()
.setID(11)
.setHappycamper(444)
.addListOfObjects(SimpleTwo.newBuilder()
.setID(3)
.setDirector("direction")
.setTitle("up_side")
.build())
.build();
db.save(o1);
db.save(o2);
}
@Test
public void TestSearchExactByJoin() {
try {
List<TestDomain.RepObjectOne> result =
db.search(
SearchOptions.newBuilder(TestDomain.RepObjectOne.getDefaultInstance())
.addFieldName("list_of_objects.title")
.addSearchArgument("who_said_that")
.addOperator(ProtoDBSearchOperator.Equals));
// we should get one single result..
assertEquals(1, result.size());
// we should get three sub results
assertEquals(2, result.get(0).getListOfObjectsList().size());
} catch (SQLException | ClassNotFoundException | SearchFieldNotFoundException | ProtoDBParserException | SearchOptionsNotInitializedException e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void TestSearchJoinQuery() {
try {
RepObjectOne o1 = RepObjectOne.newBuilder()
.setID(10)
.setHappycamper(555)
.addListOfObjects(SimpleTwo.newBuilder()
.setID(1)
.setDirector("directThis")
.setTitle("thisisatitle")
.build())
.addListOfObjects(SimpleTwo.newBuilder()
.setID(2)
.setDirector("no_way")
.setTitle("who_said_that")
.build())
.build();
ProtoDBScanner scanner = new ProtoDBScanner(o1, db.getDatabaseBackend());
JoinResult result = Searcher.getJoinQuery(scanner, false, true);
// the query of the repeated subobjects need to be populated separately
String expected =
String.format(
"SELECT DISTINCT "
+ "A.%1$sID%2$s AS A_ID, "
+ "A.%1$shappycamper%2$s AS A_happycamper "
+ "FROM RepObjectOne AS A ",
db.getDatabaseBackend().getStartBracket(),
db.getDatabaseBackend().getEndBracket());
assertEquals(expected, result.getSql());
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void TestShallowCopy() {
try {
List<TestDomain.RepObjectOne> result =
db.search(
SearchOptions.newBuilder(TestDomain.RepObjectOne.getDefaultInstance())
.addSearchArgument("%")
.addOperator(ProtoDBSearchOperator.Like)
.setShallow(true));
assertNotNull(result);
// we should get one single result..
assertEquals(2, result.size());
// we should get three sub results
assertEquals(0, result.get(0).getListOfObjectsList().size());
} catch (SQLException | ClassNotFoundException | SearchFieldNotFoundException | ProtoDBParserException | SearchOptionsNotInitializedException e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void TestSearchNoDuplicates() {
try {
List<TestDomain.RepObjectOne> result =
db.search(
SearchOptions.newBuilder(TestDomain.RepObjectOne.getDefaultInstance())
.addSearchArgument("%")
.addOperator(ProtoDBSearchOperator.Like));
// we should get two single result and not three as the join will create duplicates
// of the parent item. This is not wanted.
assertEquals(2, result.size());
} catch (SQLException | ClassNotFoundException | SearchFieldNotFoundException | ProtoDBParserException | SearchOptionsNotInitializedException e) {
e.printStackTrace();
fail(e.getMessage());
}
}
}
| 29.37037 | 149 | 0.718249 |
c050b3858b34ba3cdb5cc2f873cfe1b43957d06b | 3,936 | package fi.riista.feature.permit.application;
import fi.riista.feature.account.user.UserRepository;
import fi.riista.feature.permit.application.archive.PermitApplicationArchiveDTO;
import fi.riista.feature.permit.application.archive.PermitApplicationArchiveService;
import fi.riista.feature.permit.application.email.HarvestPermitApplicationNotificationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
@Component
public class HarvestPermitApplicationAsyncFeature {
private static final Logger LOG = LoggerFactory.getLogger(HarvestPermitApplicationAsyncFeature.class);
@Resource
private HarvestPermitApplicationRepository harvestPermitApplicationRepository;
@Resource
private HarvestPermitApplicationModeratorNotificationService harvestPermitApplicationModeratorNotificationService;
@Resource
private HarvestPermitApplicationNotificationService harvestPermitApplicationNotificationService;
@Resource
private PermitApplicationArchiveService permitApplicationArchiveService;
@Resource
private UserRepository userRepository;
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_MODERATOR')")
@Transactional(rollbackFor = Exception.class)
public String createArchiveIfMissing(final long applicationId) throws Exception {
if (permitApplicationArchiveService.isArchiveMissing(applicationId)) {
doCreateArchive(applicationId);
return "created";
} else {
return "exists";
}
}
@Async
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void asyncSendModeratorNotification(final long applicationId) {
final HarvestPermitApplication application = harvestPermitApplicationRepository.getOne(applicationId);
harvestPermitApplicationModeratorNotificationService.sendModeratorNotification(application);
}
@Async
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void asyncSendEmailNotification(final long applicationId) {
final HarvestPermitApplication application = harvestPermitApplicationRepository.getOne(applicationId);
if (createdByModerator(application)) {
LOG.warn("Not sending notification email for application id={} created by moderator", applicationId);
} else {
harvestPermitApplicationNotificationService.sendNotification(application);
}
}
private boolean createdByModerator(final HarvestPermitApplication application) {
final Long createdByUserId = application.getAuditFields().getCreatedByUserId();
return createdByUserId != null && userRepository.isModeratorOrAdmin(createdByUserId);
}
@Async
public void asyncCreateArchive(final long applicationId) throws Exception {
doCreateArchive(applicationId);
}
private void doCreateArchive(final long applicationId) throws Exception {
final PermitApplicationArchiveDTO dto = permitApplicationArchiveService.getDataForArchive(applicationId);
Path archivePath = null;
try {
archivePath = permitApplicationArchiveService.createArchive(dto);
permitApplicationArchiveService.storeArchive(archivePath, applicationId);
} finally {
if (archivePath != null) {
try {
Files.deleteIfExists(archivePath);
} catch (IOException e) {
LOG.error("Could not delete temporary file", e);
}
}
}
}
}
| 38.970297 | 118 | 0.756098 |
520f42e0fcadc9623e63e31f122bcfbf48569bb2 | 4,567 | /*
* Copyright (c) 2011-2017, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* 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 boofcv.alg.feature.dense;
import boofcv.alg.feature.describe.DescribePointSift;
import boofcv.alg.misc.GImageMiscOps;
import boofcv.struct.feature.TupleDesc_F64;
import boofcv.struct.image.GrayF32;
import boofcv.testing.BoofTesting;
import georegression.metric.UtilAngle;
import georegression.struct.point.Point2D_I32;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import static org.junit.Assert.assertEquals;
/**
* @author Peter Abeles
*/
public class TestDescribeDenseSiftAlg {
Random rand = new Random(234);
int width = 50, height = 40;
/**
* Checks the adjustment done to the sample period and to see if the descriptions are computed
* at the correct coordinate
*/
@Test
public void process() {
GrayF32 derivX = new GrayF32(100,102);
GrayF32 derivY = new GrayF32(100,102);
GImageMiscOps.fillUniform(derivX,rand,0,200);
GImageMiscOps.fillUniform(derivY,rand,0,200);
process(derivX, derivY);
BoofTesting.checkSubImage(this,"process",true,derivX,derivY);
}
public void process(GrayF32 derivX, GrayF32 derivY) {
DescribeDenseSiftAlg<GrayF32> alg = new DescribeDenseSiftAlg<>(4,4,8,0.5,0.2,10,10,GrayF32.class);
alg.setImageGradient(derivX,derivY);
alg.process();
List<TupleDesc_F64> list = alg.getDescriptors().toList();
int r = alg.getCanonicalRadius();
int cols = (100-2*r)/10;
int rows = (102-2*r)/10;
assertEquals(cols*rows,list.size());
int w = derivX.width-2*r;
int h = derivX.height-2*r;
TupleDesc_F64 expected = new TupleDesc_F64(128);
int i = 0;
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++, i++) {
int x = col*w/(cols-1) + r;
int y = row*h/(rows-1) + r;
TupleDesc_F64 found = list.get(i);
alg.computeDescriptor(x,y,expected);
for (int j = 0; j < 128; j++) {
assertEquals(expected.value[j],found.value[j],1e-8);
}
}
}
}
@Test
public void precomputeAngles() {
GrayF32 derivX = new GrayF32(width,height);
GrayF32 derivY = new GrayF32(width,height);
GImageMiscOps.fillUniform(derivX,rand,0,200);
GImageMiscOps.fillUniform(derivY,rand,0,200);
DescribeDenseSiftAlg<GrayF32> alg = new DescribeDenseSiftAlg<>(4,4,8,0.5,0.2,10,10,GrayF32.class);
alg.setImageGradient(derivX,derivY);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
float dx = derivX.get(x,y);
float dy = derivY.get(x,y);
double expectedAngle = UtilAngle.domain2PI(Math.atan2(dy,dx));
float expectedMagnitude = (float)Math.sqrt(dx*dx + dy*dy);
assertEquals(expectedAngle,alg.savedAngle.get(x,y),1e-8);
assertEquals(expectedMagnitude,alg.savedMagnitude.get(x,y),1e-4f);
}
}
}
/**
* Compute to the general descriptor algorithm. They should produce the same results
*/
@Test
public void computeDescriptor() {
GrayF32 derivX = new GrayF32(100,102);
GrayF32 derivY = new GrayF32(100,102);
GImageMiscOps.fillUniform(derivX,rand,0,200);
GImageMiscOps.fillUniform(derivY,rand,0,200);
DescribeDenseSiftAlg<GrayF32> alg = new DescribeDenseSiftAlg<>(4,4,8,0.5,0.2,10,10,GrayF32.class);
DescribePointSift<GrayF32> algTest = new DescribePointSift<>(4,4,8,1,0.5,0.2,GrayF32.class);
alg.setImageGradient(derivX,derivY);
algTest.setImageGradient(derivX,derivY);
List<Point2D_I32> samplePoints = new ArrayList<>();
samplePoints.add( new Point2D_I32(30,35));
samplePoints.add( new Point2D_I32(45,10));
samplePoints.add( new Point2D_I32(60,12));
samplePoints.add( new Point2D_I32(50,50));
TupleDesc_F64 found = new TupleDesc_F64(128);
TupleDesc_F64 expected = new TupleDesc_F64(128);
for( Point2D_I32 p : samplePoints ) {
alg.computeDescriptor(p.x,p.y,found);
algTest.process(p.x,p.y,1,0,expected);
for (int i = 0; i < 128; i++) {
assertEquals(expected.value[i],found.value[i],1e-8);
}
}
}
} | 28.72327 | 100 | 0.706372 |
eb95de1ff42e42acfc0f9c3a7e02a5658d55b322 | 5,114 | package utils;
import models.es.Customer;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class ElasticSearchUtil {
String baseIndex = "mytest_user";
String baseType = "_doc";
RestHighLevelClient client;
private final int connectTimeoutMillis = 1000;
private final int socketTimeoutMillis = 30000;
private final int connectionRequestTimeoutMillis = 500;
private final int maxConnectPerRoute = 10;
private final int maxConnectTotal = 30;
public static void main(String[] arg) throws Exception {
ElasticSearchUtil elasticSearchUtil = new ElasticSearchUtil();
elasticSearchUtil.test();
elasticSearchUtil.search();
}
public void test() {
String[] ips = {"localhost:9200"};
HttpHost[] httpHosts = new HttpHost[ips.length];
for (int i = 0; i < ips.length; i++) {
httpHosts[i] = HttpHost.create(ips[i]);
}
RestClientBuilder builder = RestClient.builder(httpHosts);
builder.setRequestConfigCallback(requestConfigBuilder -> {
requestConfigBuilder.setConnectTimeout(connectTimeoutMillis);
requestConfigBuilder.setSocketTimeout(socketTimeoutMillis);
requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeoutMillis);
return requestConfigBuilder;
});
builder.setHttpClientConfigCallback(httpClientBuilder -> {
httpClientBuilder.setMaxConnTotal(maxConnectTotal);
httpClientBuilder.setMaxConnPerRoute(maxConnectPerRoute);
return httpClientBuilder;
});
client = new RestHighLevelClient(builder);
}
@SuppressWarnings("deprecation")
public void search() throws Exception {
SearchRequest request = new SearchRequest();
request.indices(baseIndex);
request.types(baseType);
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.termQuery("name", "c"));
sourceBuilder.from(0);
sourceBuilder.size(5);
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
HighlightBuilder highlightBuilder = new HighlightBuilder().field("name");
sourceBuilder.highlighter(highlightBuilder);
request.source(sourceBuilder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits searchHits = response.getHits();
long total = searchHits.getTotalHits();
SearchHit[] searchHitArray = searchHits.getHits();
List<Customer> data = new ArrayList<>();
for(SearchHit hit : searchHitArray){
Map<String, Object> source = hit.getSourceAsMap();
Customer customer = new Customer();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
customer.cTime = simpleDateFormat.parse(source.get("c_time").toString());
customer.name = source.get("name").toString();
customer.roleId = Long.valueOf(source.get("role_id").toString());
customer.roleName = source.get("role_name").toString();
customer.id = Long.valueOf(hit.getId());
Map<String, HighlightField> map = hit.getHighlightFields();
System.out.println(map.get("name").getFragments()[0].toString());
// qo.setHighlightFields(t,hit);
data.add(customer);
}
client.close();
// return new PageResult(data,Integer.parseInt(total+""),qo.getCurrentPage(),qo.getPageSize());
}
/*public void insertOrUpdate(Object o) throws Exception {
Map map = BeanUtil.bean2Map(o);
IndexRequest request = new IndexRequest(baseIndex, baseType, map.get("id")+"");
request.source(map);
client.index(request);
}
public void delete(Long id) throws Exception {
DeleteRequest request = new DeleteRequest(baseIndex, baseType, id + "");
client.delete(request);
}
public T get(Long id) throws Exception {
GetRequest request = new GetRequest(baseIndex, baseType, id+"");
GetResponse response = client.get(request);
Map<String, Object> source = response.getSource();
T t = BeanUtil.map2Bean(source, clazz);
return t;
}*/
}
| 42.97479 | 102 | 0.694955 |
978f4f8ae91c0c39c2f7c85a4c64ca10f125bd49 | 2,457 | package org.redquark.onlinejudges.leetcode.stack;
import java.util.Stack;
/**
* @author Anirudh Sharma
*/
public class DecodeString {
public String decodeString(String s) {
// StringBuilder to store the decoded string
StringBuilder decodedString = new StringBuilder();
// Special case
if (s == null || s.isEmpty()) {
return decodedString.toString();
}
// Stack to store the counts of substrings
Stack<Integer> counts = new Stack<>();
// Stack to store the substrings which need to be repeated
Stack<String> parts = new Stack<>();
// Loop through each character of the string
int index = 0;
while (index < s.length()) {
// Current character
char c = s.charAt(index);
// If the current character is a digit
if (Character.isDigit(c)) {
// We will calculate the number
int k = 0;
while (Character.isDigit(s.charAt(index))) {
k = k * 10 + s.charAt(index) - '0';
index++;
}
// Push this count in the count stack
counts.push(k);
}
// If the current character is an opening bracket
else if (c == '[') {
// We now have to push the already calculated
// string and push it to the stack
parts.push(decodedString.toString());
// Reset the decodedString
decodedString = new StringBuilder();
index++;
}
// If the current character is a closing bracket
else if (c == ']') {
// Now we will have to repeat the string count number
// of times.
// First get the string to be repeated
StringBuilder temp = new StringBuilder(parts.pop());
// Get the count
int k = counts.pop();
// Append the repeated strings
temp.append(String.valueOf(decodedString).repeat(Math.max(0, k)));
decodedString = temp;
index++;
}
// If the current character is a letter, simply append it
else {
decodedString.append(c);
index++;
}
}
return decodedString.toString();
}
}
| 36.132353 | 82 | 0.502646 |
331f5a9c4051d6d5a6a3a5aa993ffe472594cb71 | 1,146 | /*
* This file is generated by jOOQ.
*/
package com.github.mahjong.main.repo.jdbc.generated;
import com.github.mahjong.main.repo.jdbc.generated.tables.Game;
import com.github.mahjong.main.repo.jdbc.generated.tables.Player;
import com.github.mahjong.main.repo.jdbc.generated.tables.SchemaVersion;
import javax.annotation.Generated;
/**
* Convenience access to all tables in public
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.10.5"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class Tables {
/**
* The table <code>public.game</code>.
*/
public static final Game GAME = com.github.mahjong.main.repo.jdbc.generated.tables.Game.GAME;
/**
* The table <code>public.player</code>.
*/
public static final Player PLAYER = com.github.mahjong.main.repo.jdbc.generated.tables.Player.PLAYER;
/**
* The table <code>public.schema_version</code>.
*/
public static final SchemaVersion SCHEMA_VERSION = com.github.mahjong.main.repo.jdbc.generated.tables.SchemaVersion.SCHEMA_VERSION;
}
| 27.285714 | 135 | 0.697208 |
50f34ae3b75c57d6c50940767daf9e6026144f05 | 643 | package com.robert.kafka.kclient.boot;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation is used for a method which serve as an exception handler. It
* includes the metadata for an exception handler.
*
* @author Robert Lee
* @since Aug 21, 2015
*
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ErrorHandler {
Class<? extends Throwable> exception() default Throwable.class;
String topic() default "";
}
| 24.730769 | 79 | 0.768274 |
fea2f2c08ccd21525f0d97b7a06d74e9712a9db7 | 2,641 | package org.motechproject.tasks.repository;
import org.ektorp.CouchDbConnector;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.motechproject.tasks.domain.TaskStatusMessage;
import org.motechproject.testing.utils.SpringIntegrationTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.motechproject.tasks.domain.Level.ERROR;
import static org.motechproject.tasks.domain.Level.SUCCESS;
import static org.motechproject.tasks.domain.Level.WARNING;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:/META-INF/motech/*.xml"})
public class AllTaskStatusMessagesIT extends SpringIntegrationTest {
@Autowired
private AllTaskStatusMessages allTaskStatusMessages;
@Autowired
@Qualifier("taskDbConnector")
private CouchDbConnector couchDbConnector;
@Test
public void test_byTaskId() {
TaskStatusMessage errorMsg = new TaskStatusMessage(ERROR.getValue(), "12345", ERROR);
TaskStatusMessage successMsg = new TaskStatusMessage(SUCCESS.getValue(), "12345", SUCCESS);
TaskStatusMessage warningMsg = new TaskStatusMessage(WARNING.getValue(), "54321", WARNING);
allTaskStatusMessages.add(errorMsg);
allTaskStatusMessages.add(warningMsg);
allTaskStatusMessages.add(successMsg);
assertEquals(3, allTaskStatusMessages.getAll().size());
List<TaskStatusMessage> messages = allTaskStatusMessages.byTaskId("12345");
assertEquals(2, messages.size());
assertEquals(ERROR, messages.get(0).getLevel());
assertEquals("12345", messages.get(0).getTask());
assertEquals(ERROR.getValue(), messages.get(0).getMessage());
assertEquals(SUCCESS, messages.get(1).getLevel());
assertEquals("12345", messages.get(1).getTask());
assertEquals(SUCCESS.getValue(), messages.get(1).getMessage());
markForDeletion(messages);
messages = allTaskStatusMessages.byTaskId("54321");
assertEquals(1, messages.size());
assertEquals(WARNING, messages.get(0).getLevel());
assertEquals("54321", messages.get(0).getTask());
assertEquals(WARNING.getValue(), messages.get(0).getMessage());
markForDeletion(messages);
}
@Override
public CouchDbConnector getDBConnector() {
return couchDbConnector;
}
}
| 35.689189 | 99 | 0.741386 |
8cc274b63d063b215c13fe7ec5dc80f4943a1994 | 616 | package com.milaboratory.core.alignment.blast;
import com.milaboratory.core.Range;
import com.milaboratory.core.alignment.Alignment;
import com.milaboratory.core.sequence.Sequence;
public class BlastHitExt<S extends Sequence<S>> extends BlastHit<S, String> {
public BlastHitExt(Alignment<S> alignment, double score, double bitScore, double eValue, Range subjectRange, String subjectId, String subjectTitle) {
super(alignment, subjectTitle, score, bitScore, eValue,
subjectRange, subjectId, subjectTitle);
}
public String getTitle() {
return getRecordPayload();
}
}
| 36.235294 | 153 | 0.743506 |
df5738ce2a8c3b68be5c2cbdcd3ed21c618f6e54 | 849 | package com.rvprg.sumi.transport;
import com.google.inject.Inject;
import com.rvprg.sumi.protocol.MessageConsumer;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {
private final MessageConsumer messageConsumer;
private final ChannelPipelineInitializer pipelineInitializer;
@Inject
public ServerChannelInitializer(MessageConsumer messageConsumer, ChannelPipelineInitializer pipelineInitializer) {
this.messageConsumer = messageConsumer;
this.pipelineInitializer = pipelineInitializer;
}
@Override
protected void initChannel(SocketChannel ch) {
pipelineInitializer.initialize(ch.pipeline()).addLast(new MessageDispatcher(new ActiveMember(ch), messageConsumer));
}
}
| 33.96 | 124 | 0.797409 |
89c733803e5a1a128b31c643f353df09d20f35a7 | 1,360 | import java.util.*;
public class BusinessCenter {
public static void main(String[] args) {
new BusinessCenter().run();
}
class Node {
int min, max, x;
Node(int Min, int Max, int X) { min=Min; max=Max; x=X; }
}
Scanner scn;
int n, m;
int u, d;
void run() {
scn = new Scanner(System.in);
while (scn.hasNextInt()) {
n = scn.nextInt();
m = scn.nextInt();
int min = Integer.MAX_VALUE;
for (int i = 0; i < m; i++) {
u = scn.nextInt();
d = scn.nextInt();
int answer = search(new Node(0, n, n/2));
if (answer < min) min = answer;
}
System.out.println(min);
}
}
int search(Node initial) {
Queue<Node> q = new LinkedList<Node>();
q.add(initial);
while (!q.isEmpty()) {
Node nd = q.remove();
int f = fun(nd.x);
if (f <= 0) {
q.add(new Node(nd.x+1, nd.max, nd.x + 1 + (nd.max-nd.x)/2));
continue;
}
if (fun(nd.x-1) <= 0) {
return f;
}
q.add(new Node(nd.min, nd.x-1, nd.x - 1 - (nd.x-nd.min)/2));
}
return -1;
}
int fun(int x) {
return u*x - d*(n-x);
}
}
| 26.666667 | 76 | 0.416912 |
6a5a4efdce4ac6f437c8dd082e5e34f3e20b4209 | 1,883 | package shared.systems;
import java.util.List;
import org.joml.Vector3f;
import gameServer.components.ShipComponent;
import hecs.Entity;
import hecs.EntityManager;
import shared.components.AIBotComponent;
import shared.components.MovementComponent;
import shared.components.ObjectComponent;
public class AIBotSystem {
private EntityManager entityManager;
public AIBotSystem(EntityManager entityManager) {
this.entityManager = entityManager;
}
Vector3f tempVector = new Vector3f();
public void update(float dt) {
List<Entity> entities = entityManager.getEntitiesContainingComponent(AIBotComponent.class);
if (entities == null)
return;
if (entities.isEmpty())
return;
for (Entity entity : entities) {
AIBotComponent aiBot = (AIBotComponent) entityManager.getComponentInEntity(entity, AIBotComponent.class);
ShipComponent ship = (ShipComponent) entityManager.getComponentInEntity(entity, ShipComponent.class);
ObjectComponent unit = (ObjectComponent) entityManager.getComponentInEntity(entity, ObjectComponent.class);
MovementComponent movement = (MovementComponent) entityManager.getComponentInEntity(entity, MovementComponent.class);
Vector3f angularThrust = new Vector3f(0.01f, 0.02f, 0.03f);
movement.getAngularAcc().fma(dt, angularThrust);
int distance = 100;
if (unit.getPosition().z >= distance) {
aiBot.direction = 1;
} else if (unit.getPosition().z <= -distance) {
aiBot.direction = -1;
}
float speed = movement.getLinearVel().length();
if (speed < aiBot.maxSpeed || (movement.getLinearVel().z > 0 && aiBot.direction > 0) || (movement.getLinearVel().z < 0 && aiBot.direction < 0)) {
Vector3f linearThrust = unit.getForward().mul(aiBot.acceleration * aiBot.direction, tempVector);
ship.getLinearThrust().add(linearThrust);
}
}
}
}
| 33.625 | 149 | 0.729687 |
90c9e5f4c6bec4f05258d2bd06fd229ba91de26e | 1,287 | package vo;
//주식 정보 담는 vo객체
public class StockInfoVO {
private String JongCd;
private String gettime;
private String janggubun;
private String DungRakrate_str;
private int dailystock_length;
private String[] Stockinfo = new String[17];
private String[][] Dailystock = new String[10][9];
public String getJongCd() {
return JongCd;
}
public void setJongCd(String jongCd) {
JongCd = jongCd;
}
public String getGettime() {
return gettime;
}
public void setGettime(String gettime) {
this.gettime = gettime;
}
public String getJanggubun() {
return janggubun;
}
public void setJanggubun(String janggubun) {
this.janggubun = janggubun;
}
public String getDungRakrate_str() {
return DungRakrate_str;
}
public void setDungRakrate_str(String dungRakrate_str) {
DungRakrate_str = dungRakrate_str;
}
public int getDailystock_length() {
return dailystock_length;
}
public void setDailystock_length(int dailystock_length) {
this.dailystock_length = dailystock_length;
}
public String[] getStockinfo() {
return Stockinfo;
}
public void setStockinfo(String[] stockinfo) {
Stockinfo = stockinfo;
}
public String[][] getDailystock() {
return Dailystock;
}
public void setDailystock(String[][] dailystock) {
Dailystock = dailystock;
}
}
| 22.189655 | 58 | 0.737374 |
833c9ced79199eb067227bc56a18bcb2dbb51c9c | 5,603 | package PaDialogs;
import PaForms.PaImageTabModel;
import PaGlobal.*;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.HashSet;
import java.util.Iterator;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import PaGlobal.PaGuiTools;
import static PaGlobal.PaUtils.*;
/**
* <p>Find image dialog class</p>
* @author avd
*
*/
public class PaImageFindDialog extends JDialog {
private static final long serialVersionUID = 1L;
private JButton m_OkButton = new JButton(getGuiStrs("buttonFindCaption"));
private JButton m_CancelButton = new JButton(getGuiStrs("buttonCancelCaption"));
private JLabel m_infoLabel = new JLabel(" ");
/**
* here we have results of find operation in order to get possibility to move through them
*/
private HashSet<Integer> m_findResults = new HashSet<Integer>();
private PaImageTabModel m_refModel;
JTextField m_textF = new JTextField();
Iterator<Integer> m_findIterator;
private String m_oldValue = new String();
public PaImageFindDialog (JFrame jfrm, PaImageTabModel model) {
super (jfrm, getGuiStrs("findPhotoDialogCaption"), true);
m_refModel = model;
add(createGUI());
setBounds(250, 150, 225, 240);
pack();
setResizable(false);
}
/**
*
* @return main UI panel with all components constructed
*/
private JPanel createGUI () {
JPanel panel_MAIN = PaGuiTools.createVerticalPanel();
panel_MAIN.setBorder( BorderFactory.createEmptyBorder(PaUtils.VERT_STRUT,PaUtils.VERT_STRUT,
PaUtils.VERT_STRUT,PaUtils.VERT_STRUT));
JPanel panel_set = PaGuiTools.createHorizontalPanel();
JLabel jLabel = new JLabel(getGuiStrs("findComboLabelName")+" ");
panel_set.add(jLabel);
panel_set.add(m_textF);
m_textF.setBorder(BorderFactory.createLoweredBevelBorder());
m_textF.setSize(200, m_textF.getSize().height);
JPanel panel_Ok_Cancel = new JPanel( new GridLayout( 1,3,5,0) );
panel_Ok_Cancel.add(Box.createHorizontalStrut(100));
panel_Ok_Cancel.add(m_OkButton);
panel_Ok_Cancel.add(m_CancelButton);
JPanel panelInfo = PaGuiTools.createHorizontalPanel();
panelInfo.add(m_infoLabel);
panelInfo.add(Box.createHorizontalGlue());
panel_MAIN.add(Box.createVerticalStrut(PaUtils.VERT_STRUT));
panel_MAIN.add(panel_set);
panel_MAIN.add(Box.createVerticalStrut(PaUtils.VERT_STRUT));
panel_MAIN.add(panelInfo);
panel_MAIN.add(Box.createVerticalStrut(PaUtils.VERT_STRUT));
panel_MAIN.add(panel_Ok_Cancel);
setListeners();
return panel_MAIN;
}
/**
* <p>Sets all listeners in the dialog</p>
*/
private void setListeners() {
Forwarder forwarder = new Forwarder();
m_OkButton.addActionListener(forwarder);
m_CancelButton.addActionListener(forwarder);
EnterListener l = new EnterListener();
m_textF.addKeyListener(l);
m_OkButton.addKeyListener(l);
m_CancelButton.addKeyListener(l);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
dispose();
}
});
}
class Forwarder implements ActionListener {
public void actionPerformed(ActionEvent e){
if ( e.getSource() == m_OkButton ) onOK(e);
if ( e.getSource() == m_CancelButton ) onCancel(e);
}
}
public void onOK(ActionEvent e)
{
findOperation();
}
public void onCancel(ActionEvent e) {
dispose();
}
/**
* <p>Main find algorithm</p>
*/
private void findOperation()
{
boolean flag = false;
if ( ! m_oldValue.equals( m_textF.getText() ) ) {
m_oldValue = m_textF.getText();
m_findResults.clear();
m_refModel.findRows(m_oldValue,m_findResults);
Iterator<Integer> it = m_findResults.iterator();
m_findIterator = it;
if ( m_findIterator.hasNext() ) {
m_refModel.setRowSelected(m_findIterator.next());
flag = true;
}
}
else {
if ( m_findIterator.hasNext() ) {
m_refModel.setRowSelected(m_findIterator.next());
flag = true;
}
else {
Iterator<Integer> it1 = m_findResults.iterator();
m_findIterator = it1;
if ( m_findIterator.hasNext() ) {
m_refModel.setRowSelected(m_findIterator.next());
flag = true;
}
}
}
if(flag) {
m_infoLabel.setText(getMessagesStrs("subjectHasBeenFoudMessage"));
m_infoLabel.setForeground(Color.BLUE);
}
else {
m_infoLabel.setText(getMessagesStrs("subjectHasNotBeenFoudMessage"));
m_infoLabel.setForeground(Color.RED);
}
}
/**
* Catches the Enter button press event to start the find operation
* @author avd
*
*/
private class EnterListener implements KeyListener {
@Override
public void keyPressed(KeyEvent arg0) {
}
@Override
public void keyReleased(KeyEvent e) {
int key=e.getKeyCode();
if(key==KeyEvent.VK_ENTER)
{
if(e.getSource()== m_textF) { onOK(null); }
if ( e.getSource() == m_OkButton ) { onOK(null); }
if ( e.getSource() == m_CancelButton ) { onCancel(null); }
}
}
@Override
public void keyTyped(KeyEvent arg0) {
}
}
} | 20.374545 | 94 | 0.681956 |
ab81faf716112fffdc9d5e528b2babefaddda0e4 | 527 | package if_programs;
public class triangle_possornot_type
{
void main(int a,int b,int c )
{
if(a==b&&b==c&&a+b>c&&b+c>a&&a+c>b)
System.out.println("triangle is possible and is equilateral");
else if(a==b||b==c||c==a&&a+b>c&&b+c>a&&a+c>b)
System.out.println("triangle is possible and is isoceles");
else if(a!=b && b!=c && c!=a && a+b>c && b+c>a && a+c>b)
System.out.println("triangle is possible and is scalene");
else
System.out.println("triangle not possible");
}
}
| 32.9375 | 67 | 0.590133 |
9ab4545125aebf8a141899b431e3a4d0570179df | 189 | package pt.ulisboa.forward.ewp.api.client.utils;
public class HttpConstants {
private HttpConstants() {}
public static final String HEADER_X_HAS_DATA_OBJECT = "X-Has-Data-Object";
}
| 21 | 76 | 0.767196 |
bad451c113b577174430dc6cc1fd8c86fd141722 | 6,176 | package kr.pe.codda.impl.task.server;
import static kr.pe.codda.jooq.tables.SbMemberTb.SB_MEMBER_TB;
import java.sql.Timestamp;
import org.jooq.DSLContext;
import org.jooq.Record2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import kr.pe.codda.common.message.AbstractMessage;
import kr.pe.codda.impl.message.MemberUnBlockReq.MemberUnBlockReq;
import kr.pe.codda.impl.message.MessageResultRes.MessageResultRes;
import kr.pe.codda.server.LoginManagerIF;
import kr.pe.codda.server.lib.DBAutoCommitTaskIF;
import kr.pe.codda.server.lib.MemberRoleType;
import kr.pe.codda.server.lib.MemberStateType;
import kr.pe.codda.server.lib.ParameterServerTaskException;
import kr.pe.codda.server.lib.PermissionType;
import kr.pe.codda.server.lib.RollbackServerTaskException;
import kr.pe.codda.server.lib.ServerCommonStaticFinalVars;
import kr.pe.codda.server.lib.ServerDBUtil;
import kr.pe.codda.server.lib.ValueChecker;
import kr.pe.codda.server.task.AbstractServerTask;
import kr.pe.codda.server.task.ToLetterCarrier;
public class MemberUnBlockReqServerTask extends AbstractServerTask
implements DBAutoCommitTaskIF<MemberUnBlockReq, MessageResultRes> {
private Logger log = LoggerFactory.getLogger(MemberUnBlockReqServerTask.class);
@Override
public void doTask(String projectName, LoginManagerIF personalLoginManager, ToLetterCarrier toLetterCarrier,
AbstractMessage inputMessage) throws Exception {
AbstractMessage outputMessage = ServerDBUtil.execute(
ServerCommonStaticFinalVars.DEFAULT_DBCP_NAME, this, (MemberUnBlockReq) inputMessage);
toLetterCarrier.addSyncOutputMessage(outputMessage);
}
public MessageResultRes doWork(final String dbcpName, final MemberUnBlockReq memberUnBlockReq) throws Exception {
MessageResultRes outputMessage = ServerDBUtil.execute(dbcpName, this, memberUnBlockReq);
return outputMessage;
}
@Override
public MessageResultRes doWork(final DSLContext dsl, final MemberUnBlockReq memberUnBlockReq) throws Exception {
if (null == dsl) {
throw new ParameterServerTaskException("the parameter dsl is null");
}
if (null == memberUnBlockReq) {
throw new ParameterServerTaskException("the parameter memberUnBlockReq is null");
}
log.info(memberUnBlockReq.toString());
try {
ValueChecker.checkValidRequestedUserID(memberUnBlockReq.getRequestedUserID());
ValueChecker.checkValidIP(memberUnBlockReq.getIp());
ValueChecker.checkValidUnBlockUserID(memberUnBlockReq.getTargetUserID());
} catch (IllegalArgumentException e) {
String errorMessage = e.getMessage();
throw new ParameterServerTaskException(errorMessage);
}
if (memberUnBlockReq.getRequestedUserID().equals(memberUnBlockReq.getTargetUserID())) {
String errorMessage = "자기 자신을 차단 해제 할 수 없습니다";
throw new ParameterServerTaskException(errorMessage);
}
ServerDBUtil.checkUserAccessRights(dsl, "회원 차단 해제 서비스", PermissionType.ADMIN,
memberUnBlockReq.getRequestedUserID());
/** 차단 해제 대상 회원 레코드 락 */
Record2<Byte, Byte> memberRecordOfTargetUserID = dsl.select(SB_MEMBER_TB.STATE, SB_MEMBER_TB.ROLE)
.from(SB_MEMBER_TB).where(SB_MEMBER_TB.USER_ID.eq(memberUnBlockReq.getTargetUserID())).forUpdate()
.fetchOne();
if (null == memberRecordOfTargetUserID) {
String errorMessage = new StringBuilder("차단 해제 대상 사용자[").append(memberUnBlockReq.getTargetUserID())
.append("]가 회원 테이블에 존재하지 않습니다").toString();
throw new RollbackServerTaskException(errorMessage);
}
byte memberRoleOfTargetUserID = memberRecordOfTargetUserID.getValue(SB_MEMBER_TB.ROLE);
MemberRoleType memberRoleTypeOfTargetUserID = null;
try {
memberRoleTypeOfTargetUserID = MemberRoleType.valueOf(memberRoleOfTargetUserID);
} catch (IllegalArgumentException e) {
String errorMessage = new StringBuilder("알 수 없는 회원[").append(memberUnBlockReq.getTargetUserID())
.append("]의 역활[").append(memberRoleOfTargetUserID).append("] 값입니다").toString();
throw new RollbackServerTaskException(errorMessage);
}
if (!MemberRoleType.MEMBER.equals(memberRoleTypeOfTargetUserID)) {
String errorMessage = new StringBuilder().append("차단 해제 대상 회원[id=")
.append(memberUnBlockReq.getTargetUserID()).append(", 역활=")
.append(memberRoleTypeOfTargetUserID.name()).append("]이 일반 회원이 아닙니다").toString();
throw new RollbackServerTaskException(errorMessage);
}
byte memeberStateOfTargetUserID = memberRecordOfTargetUserID.getValue(SB_MEMBER_TB.STATE);
MemberStateType memberStateTypeOfTargetUserID = null;
try {
memberStateTypeOfTargetUserID = MemberStateType.valueOf(memeberStateOfTargetUserID);
} catch (IllegalArgumentException e) {
String errorMessage = new StringBuilder("알 수 없는 회원[").append(memberUnBlockReq.getTargetUserID())
.append("]의 상태[").append(memeberStateOfTargetUserID).append("] 값입니다").toString();
throw new RollbackServerTaskException(errorMessage);
}
if (!MemberStateType.BLOCK.equals(memberStateTypeOfTargetUserID)) {
String errorMessage = new StringBuilder("차단 해제 대상 사용자[사용자아이디=").append(memberUnBlockReq.getTargetUserID())
.append(", 상태=").append(memberStateTypeOfTargetUserID.getName()).append("]는 차단된 사용자가 아닙니다")
.toString();
throw new RollbackServerTaskException(errorMessage);
}
Timestamp lastStateModifiedDate = new java.sql.Timestamp(System.currentTimeMillis());
dsl.update(SB_MEMBER_TB).set(SB_MEMBER_TB.STATE, MemberStateType.OK.getValue())
.set(SB_MEMBER_TB.LAST_STATE_MOD_DT, lastStateModifiedDate)
.where(SB_MEMBER_TB.USER_ID.eq(memberUnBlockReq.getTargetUserID())).execute();
String logText = new StringBuilder().append("아이디 '").append(memberUnBlockReq.getTargetUserID())
.append("' 회원 차단").toString();
ServerDBUtil.insertSiteLog(dsl, memberUnBlockReq.getRequestedUserID(), logText, lastStateModifiedDate,
memberUnBlockReq.getIp());
MessageResultRes messageResultRes = new MessageResultRes();
messageResultRes.setTaskMessageID(memberUnBlockReq.getMessageID());
messageResultRes.setIsSuccess(true);
messageResultRes.setResultMessage(new StringBuilder().append("차단된 사용자[")
.append(memberUnBlockReq.getTargetUserID()).append("]에 대한 제제를 해제하였습니다").toString());
return messageResultRes;
}
}
| 42.888889 | 114 | 0.78967 |
a87b94fd15a76f5bf8d1ed584850f951125a7a6a | 33,898 | package com.ninchat.sdk.activities;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.OpenableColumns;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.RecyclerView;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.ninchat.sdk.NinchatSessionManager;
import com.ninchat.sdk.R;
import com.ninchat.sdk.adapters.NinchatMessageAdapter;
import com.ninchat.sdk.helper.glidewrapper.GlideWrapper;
import com.ninchat.sdk.managers.IOrientationManager;
import com.ninchat.sdk.managers.OrientationManager;
import com.ninchat.sdk.models.NinchatUser;
import com.ninchat.sdk.networkdispatchers.NinchatDeleteUser;
import com.ninchat.sdk.networkdispatchers.NinchatPartChannel;
import com.ninchat.sdk.networkdispatchers.NinchatSendFile;
import com.ninchat.sdk.networkdispatchers.NinchatSendMessage;
import com.ninchat.sdk.ninchatreview.model.NinchatReviewModel;
import com.ninchat.sdk.ninchatreview.presenter.NinchatReviewPresenter;
import com.ninchat.sdk.ninchattitlebar.view.NinchatTitlebarView;
import com.ninchat.sdk.states.NinchatState;
import com.ninchat.sdk.utils.misc.NinchatLinearLayoutManager;
import com.ninchat.sdk.utils.writingindicator.WritingIndicator;
import com.ninchat.sdk.utils.messagetype.NinchatMessageTypes;
import com.ninchat.sdk.utils.misc.Broadcast;
import com.ninchat.sdk.utils.misc.Misc;
import com.ninchat.sdk.utils.misc.Parameter;
import com.ninchat.sdk.utils.threadutils.NinchatScopeHandler;
import com.ninchat.sdk.views.NinchatWebRTCView;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.InputStream;
import java.util.List;
import static android.provider.Settings.System.ACCELEROMETER_ROTATION;
import static com.ninchat.sdk.ninchattitlebar.model.NinchatTitlebarKt.shouldShowTitlebar;
/**
* Created by Jussi Pekonen ([email protected]) on 22/08/2018.
*/
public final class NinchatChatActivity extends NinchatBaseActivity implements IOrientationManager {
public static int REQUEST_CODE = NinchatChatActivity.class.hashCode() & 0xffff;
protected static final int CAMERA_AND_AUDIO_PERMISSION_REQUEST_CODE = "WebRTCVideoAudio".hashCode() & 0xffff;
protected static final int PICK_PHOTO_VIDEO_REQUEST_CODE = "PickPhotoVideo".hashCode() & 0xffff;
private OrientationManager orientationManager;
private boolean historyLoaded = false;
private boolean toggleFullScreen = false;
private int rootViewHeight = 0;
private WritingIndicator writingIndicator = new WritingIndicator();
@Override
protected int getLayoutRes() {
return R.layout.activity_ninchat_chat;
}
protected void quit(Intent data) {
if (data == null) {
data = new Intent();
}
setResult(Activity.RESULT_OK, data);
finish();
}
private boolean shouldPartChannel(final NinchatState state) {
if (state == null) return false;
//1. there is no post audience questionnaire
//2. Or if user click skipped rating
return !state.hasQuestionnaire(false) || state.getSkippedReview();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
NinchatSessionManager sessionManager = NinchatSessionManager.getInstance();
if (requestCode == NinchatReviewModel.REQUEST_CODE) {
// coming from ninchat review
if (sessionManager != null && shouldPartChannel(sessionManager.ninchatState)) {
NinchatPartChannel.executeAsync(
NinchatScopeHandler.getIOScope(),
sessionManager.getSession(),
sessionManager.ninchatState.getChannelId(),
aLong -> null
);
// delete the user if current user is a guest
if (NinchatSessionManager.getInstance().isGuestMember()) {
NinchatDeleteUser.executeAsync(
NinchatScopeHandler.getIOScope(),
sessionManager.getSession(),
aLong -> null
);
}
}
quit(data);
} else if (requestCode == NinchatChatActivity.PICK_PHOTO_VIDEO_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
try {
final Uri uri = data.getData();
String fileName = getFileName(uri);
final InputStream inputStream = getContentResolver().openInputStream(uri);
final int size = inputStream.available();
final byte[] buffer = new byte[size];
inputStream.read(buffer);
inputStream.close();
NinchatSendFile.executeAsync(
NinchatScopeHandler.getIOScope(),
sessionManager.getSession(),
sessionManager.ninchatState.getChannelId(),
fileName,
buffer,
aLong -> null
);
} catch (final Exception e) {
sessionManager.sessionError(e);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public String getFileName(Uri uri) {
final Cursor cursor = getContentResolver()
.query(uri, null, null, null, null, null);
String displayName = "";
try {
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(
cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
return displayName;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == CAMERA_AND_AUDIO_PERMISSION_REQUEST_CODE) {
if (hasVideoCallPermissions()) {
sendPickUpAnswer(true);
} else {
sendPickUpAnswer(false);
showError(R.id.ninchat_chat_error, R.string.ninchat_chat_error_no_video_call_permissions);
}
} else if (requestCode == STORAGE_PERMISSION_REQUEST_CODE) {
if (hasFileAccessPermissions()) {
openImagePicker(null);
//findViewById(R.id.ninchat_chat_file_picker_dialog).setVisibility(View.VISIBLE);
} else {
showError(R.id.ninchat_chat_error, R.string.ninchat_chat_error_no_file_permissions);
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
protected boolean chatClosed = false;
protected BroadcastReceiver channelClosedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (Broadcast.CHANNEL_CLOSED.equals(action)) {
NinchatSessionManager sessionManager = NinchatSessionManager.getInstance();
if (!chatClosed && sessionManager != null)
sessionManager.getOnInitializeMessageAdapter(adapter -> adapter.close(NinchatChatActivity.this));
chatClosed = true;
hideKeyboard();
}
}
};
protected BroadcastReceiver transferReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (Broadcast.AUDIENCE_ENQUEUED.equals(action)) {
NinchatSessionManager sessionManager = NinchatSessionManager.getInstance();
NinchatPartChannel.executeAsync(
NinchatScopeHandler.getIOScope(),
sessionManager.getSession(),
sessionManager.ninchatState.getChannelId(),
aLong -> null
);
quit(intent);
}
}
};
public void onCloseChat(final View view) {
NinchatSessionManager sessionManager = NinchatSessionManager.getInstance();
final AlertDialog dialog = new AlertDialog.Builder(this, R.style.NinchatTheme_Dialog)
.setView(R.layout.dialog_close_chat)
.setCancelable(true)
.create();
dialog.show();
final TextView title = dialog.findViewById(R.id.ninchat_close_chat_dialog_title);
final String closeText = sessionManager.ninchatState.getSiteConfig().getChatCloseText();
title.setText(closeText);
final TextView description = dialog.findViewById(R.id.ninchat_close_chat_dialog_description);
description.setText(sessionManager.ninchatState.getSiteConfig().getChatCloseConfirmationText());
final Button confirm = dialog.findViewById(R.id.ninchat_close_chat_dialog_confirm);
confirm.setText(closeText);
confirm.setOnClickListener(v -> {
chatClosed();
dialog.dismiss();
});
final Button decline = dialog.findViewById(R.id.ninchat_close_chat_dialog_decline);
final String continueChatText = sessionManager.ninchatState.getSiteConfig().getContinueChatText();
decline.setText(continueChatText);
decline.setOnClickListener(v -> dialog.dismiss());
hideKeyboard();
if (chatClosed) {
dialog.dismiss();
chatClosed();
}
}
public void chatClosed() {
onVideoHangUp(null);
NinchatSessionManager sessionManager = NinchatSessionManager.getInstance();
final boolean showRatings = sessionManager.ninchatState.getSiteConfig().showRating();
// sessionManager.partChannel();
if (showRatings) {
startActivityForResult(NinchatReviewPresenter.getLaunchIntent(NinchatChatActivity.this), NinchatReviewModel.REQUEST_CODE);
} else {
quit(null);
}
}
private boolean hasVideoCallPermissions() {
return checkCallingOrSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED &&
checkCallingOrSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;
}
private void sendPickUpAnswer(final boolean answer) {
NinchatSessionManager sessionManager = NinchatSessionManager.getInstance();
try {
final JSONObject data = new JSONObject();
data.put("answer", answer);
NinchatSendMessage.executeAsync(
NinchatScopeHandler.getIOScope(),
sessionManager.getSession(),
sessionManager.ninchatState.getChannelId(),
NinchatMessageTypes.PICK_UP,
data.toString(),
aLong -> null
);
} catch (final JSONException e) {
sessionManager.sessionError(e);
}
final String metaMessage = answer ? sessionManager.ninchatState.getSiteConfig().getVideoCallAcceptedText() :
sessionManager.ninchatState.getSiteConfig().getVideoCallRejectedText();
sessionManager.getOnInitializeMessageAdapter(adapter -> {
adapter.addMetaMessage(adapter.getLastMessageId(true) + "answer", Misc.center(metaMessage));
});
}
private View videoContainer;
protected NinchatWebRTCView webRTCView;
protected BroadcastReceiver webRTCMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
NinchatSessionManager sessionManager = NinchatSessionManager.getInstance();
final String action = intent.getAction();
if (Broadcast.WEBRTC_MESSAGE.equals(action)) {
final String messageType = intent.getStringExtra(Broadcast.WEBRTC_MESSAGE_TYPE);
if (NinchatMessageTypes.CALL.equals(messageType)) {
final AlertDialog dialog = new AlertDialog.Builder(NinchatChatActivity.this, R.style.NinchatTheme_Dialog)
.setView(R.layout.dialog_video_call_consent)
.setCancelable(false)
.create();
dialog.show();
final TextView title = dialog.findViewById(R.id.ninchat_video_call_consent_dialog_title);
title.setText(sessionManager.ninchatState.getSiteConfig().getVideoChatTitleText());
final ImageView userImage = dialog.findViewById(R.id.ninchat_video_call_consent_dialog_user_avatar);
final NinchatUser user = sessionManager.getMember(intent.getStringExtra(Broadcast.WEBRTC_MESSAGE_SENDER));
String avatar = user.getAvatar();
if (TextUtils.isEmpty(avatar)) {
avatar = sessionManager.ninchatState.getSiteConfig().getAgentAvatar();
}
if (!TextUtils.isEmpty(avatar)) {
GlideWrapper.loadImageAsCircle(userImage.getContext(), avatar, userImage);
}
final TextView userName = dialog.findViewById(R.id.ninchat_video_call_consent_dialog_user_name);
userName.setText(user.getName());
final TextView description = dialog.findViewById(R.id.ninchat_video_call_consent_dialog_description);
description.setText(sessionManager.ninchatState.getSiteConfig().getVideoChatDescriptionText());
final Button accept = dialog.findViewById(R.id.ninchat_video_call_consent_dialog_accept);
accept.setText(sessionManager.ninchatState.getSiteConfig().getVideoCallAcceptText(
));
accept.setOnClickListener(v -> {
dialog.dismiss();
if (hasVideoCallPermissions()) {
sendPickUpAnswer(true);
} else {
requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO}, CAMERA_AND_AUDIO_PERMISSION_REQUEST_CODE);
}
});
final Button decline = dialog.findViewById(R.id.ninchat_video_call_consent_dialog_decline);
decline.setText(sessionManager.ninchatState.getSiteConfig().getVideoCallDeclineText());
decline.setOnClickListener(v -> {
sendPickUpAnswer(false);
dialog.dismiss();
});
hideKeyboard();
sessionManager.getOnInitializeMessageAdapter(adapter -> adapter.addMetaMessage(intent.getStringExtra(Broadcast.WEBRTC_MESSAGE_ID), sessionManager.ninchatState.getSiteConfig().getVideoCallMetaMessageText()));
} else if (webRTCView.handleWebRTCMessage(messageType, intent.getStringExtra(Broadcast.WEBRTC_MESSAGE_CONTENT))) {
if (NinchatMessageTypes.HANG_UP.equals(messageType)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);
}
}
}
}
};
private void hideKeyboard() {
final InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
try {
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
} catch (final Exception e) {
// Ignore
}
}
public void onVideoHangUp(final View view) {
hangUp();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);
}
public void onToggleFullScreen(final View view) {
toggleFullScreen = !toggleFullScreen;
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
handleTitlebarView();
}
public void onToggleAudio(final View view) {
webRTCView.toggleAudio();
}
public void onToggleMicrophone(final View view) {
webRTCView.toggleMicrophone();
}
public void onToggleVideo(final View view) {
webRTCView.toggleVideo();
}
public void onVideoCall(final View view) {
if (chatClosed) {
return;
}
webRTCView.call();
}
public void onAttachmentClick(final View view) {
if (chatClosed) {
return;
}
if (hasFileAccessPermissions()) {
openImagePicker(view);
/*final Intent photos = new Intent(Intent.ACTION_PICK).setType("image/*");
final Intent videos = new Intent(Intent.ACTION_PICK).setType("video/*");
final Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
final List<Intent> openIntents = new ArrayList<>();
addIntentToList(openIntents, photos);
addIntentToList(openIntents, camera);
if (openIntents.size() > 0) {
final Intent chooserIntent = Intent.createChooser(openIntents.remove(openIntents.size() -1), "foo");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, openIntents.toArray(new Parcelable[]{}));
startActivityForResult(chooserIntent, PICK_PHOTO_VIDEO_REQUEST_CODE);
}*/
//findViewById(R.id.ninchat_chat_file_picker_dialog).setVisibility(View.VISIBLE);
} else {
requestFileAccessPermissions();
}
}
private void addIntentToList(final List<Intent> intents, final Intent intent) {
for (final ResolveInfo resInfo : getPackageManager().queryIntentActivities(intent, 0)) {
String packageName = resInfo.activityInfo.packageName;
Intent targetedIntent = new Intent(intent);
targetedIntent.setPackage(packageName);
intents.add(targetedIntent);
}
}
public void openImagePicker(final View view) {
startActivityForResult(new Intent(Intent.ACTION_PICK).setType("image/*"), PICK_PHOTO_VIDEO_REQUEST_CODE);
}
public void onEditTextClick(final View view) {
final EditText editText = findViewById(R.id.message);
if (editText.requestFocus()) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
}
}
public void onSendClick(final View view) {
if (chatClosed) {
return;
}
final TextView messageView = findViewById(R.id.message);
final String message = messageView.getText().toString();
if (TextUtils.isEmpty(message)) {
return;
}
NinchatSessionManager sessionManager = NinchatSessionManager.getInstance();
try {
final JSONObject data = new JSONObject();
data.put("text", message);
NinchatSendMessage.executeAsync(
NinchatScopeHandler.getIOScope(),
sessionManager.getSession(),
sessionManager.ninchatState.getChannelId(),
NinchatMessageTypes.TEXT,
data.toString(),
aLong -> null
);
} catch (final JSONException e) {
sessionManager.sessionError(e);
}
writingIndicator.notifyBackend(false);
messageView.setText(null);
}
private TextWatcher textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
writingIndicator.updateLastWritingTime(s.length());
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
NinchatSessionManager sessionManager = NinchatSessionManager.getInstance();
// If the app is killed in the background sessionManager is not initialized the SDK must
// be exited and the NinchatSession needs to be initialzed again
if (sessionManager == null) {
setResult(Activity.RESULT_CANCELED, null);
finish();
this.overridePendingTransition(0, 0);
return;
}
if (getResources().getBoolean(R.bool.ninchat_chat_background_not_tiled)) {
findViewById(R.id.ninchat_chat_root).setBackgroundResource(sessionManager.getNinchatChatBackground());
} else {
Drawable background = Misc.getNinchatChatBackground(getApplicationContext(), sessionManager.getNinchatChatBackground());
if (background != null)
findViewById(R.id.ninchat_chat_root).setBackground(background);
}
// start with orientation toggled false
toggleFullScreen = false;
orientationManager = new OrientationManager(this, this, SensorManager.SENSOR_DELAY_UI);
orientationManager.enable();
videoContainer = findViewById(R.id.videoContainer);
webRTCView = new NinchatWebRTCView(videoContainer);
final LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
localBroadcastManager.registerReceiver(channelClosedReceiver, new IntentFilter(Broadcast.CHANNEL_CLOSED));
localBroadcastManager.registerReceiver(transferReceiver, new IntentFilter(Broadcast.AUDIENCE_ENQUEUED));
localBroadcastManager.registerReceiver(webRTCMessageReceiver, new IntentFilter(Broadcast.WEBRTC_MESSAGE));
final RecyclerView messages = findViewById(R.id.message_list);
final NinchatLinearLayoutManager linearLayoutManager = new NinchatLinearLayoutManager(getApplicationContext());
messages.setLayoutManager(linearLayoutManager);
sessionManager.getOnInitializeMessageAdapter(messages::setAdapter);
final EditText message = findViewById(R.id.message);
final String enterMessageText = sessionManager.ninchatState.getSiteConfig().getEnterMessageText();
message.setHint(enterMessageText);
message.addTextChangedListener(textWatcher);
writingIndicator.initiate();
final Button closeButton = findViewById(R.id.ninchat_chat_close);
final String closeText = sessionManager.ninchatState.getSiteConfig().getChatCloseText();
closeButton.setText(closeText);
if (!shouldShowTitlebar())
closeButton.setVisibility(View.VISIBLE);
final String sendButtonText = sessionManager.ninchatState.getSiteConfig().getSendButtonText();
final Button sendButton = findViewById(R.id.send_button);
final RelativeLayout sendIcon = findViewById(R.id.send_button_icon);
if (sendButtonText != null) {
sendButton.setText(sendButtonText);
} else {
sendButton.setVisibility(View.GONE);
sendIcon.setVisibility(View.VISIBLE);
}
if (sessionManager.ninchatSessionHolder.supportFiles()) {
findViewById(R.id.attachment).setVisibility(View.VISIBLE);
}
if (sessionManager.ninchatSessionHolder.supportVideos() && getResources().getBoolean(R.bool.ninchat_allow_user_initiated_video_calls)) {
findViewById(R.id.video_call).setVisibility(View.VISIBLE);
}
if (getIntent().getExtras() != null && getIntent().getExtras().getBoolean(Parameter.CHAT_IS_CLOSED)) {
initializeClosedChat(messages);
} else {
initializeChat(messages);
}
NinchatTitlebarView.Companion.showTitlebarForBacklog(
findViewById(R.id.ninchat_chat_root).findViewById(R.id.ninchat_titlebar),
() -> {
onCloseChat(null);
return null;
});
// Set up a soft keyboard visibility listener so video call container height can be adjusted
setRootViewHeightListener();
}
private void initializeClosedChat(RecyclerView messages) {
NinchatSessionManager sessionManager = NinchatSessionManager.getInstance();
// Wait for RecyclerView to be initialized
messages.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
// Close chat if it hasn't been closed yet
if (!chatClosed && historyLoaded) {
sessionManager.getOnInitializeMessageAdapter(adapter -> adapter.close(NinchatChatActivity.this));
chatClosed = true;
hideKeyboard();
}
// Initialize closed chat with recent messages only
if (!historyLoaded) {
sessionManager.loadChannelHistory(null);
historyLoaded = true;
}
});
}
private void initializeChat(RecyclerView messages) {
NinchatSessionManager sessionManager = NinchatSessionManager.getInstance();
// Wait for RecyclerView to be initialized
messages.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
if (!chatClosed) {
sessionManager.getOnInitializeMessageAdapter(adapter -> adapter.removeChatCloseMessage());
}
});
}
@Override
protected void onResume() {
super.onResume();
// Refresh the message list, just in case
NinchatSessionManager sessionManager = NinchatSessionManager.getInstance();
if (sessionManager == null) return;
sessionManager.getOnInitializeMessageAdapter(adapter -> adapter.notifyDataSetChanged());
if (webRTCView != null) {
webRTCView.onResume();
}
// Don't load first messages if chat is closed, we want to load the latest messages only
if (getIntent().getExtras() == null || !(getIntent().getExtras() != null && getIntent().getExtras().getBoolean(Parameter.CHAT_IS_CLOSED))) {
sessionManager.getOnInitializeMessageAdapter(adapter -> {
sessionManager.loadChannelHistory(adapter.getLastMessageId(false));
});
}
}
@Override
protected void onPause() {
super.onPause();
NinchatSessionManager sessionManager = NinchatSessionManager.getInstance();
if (webRTCView != null && sessionManager != null) {
webRTCView.onPause();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
hangUp();
final LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
localBroadcastManager.unregisterReceiver(channelClosedReceiver);
localBroadcastManager.unregisterReceiver(transferReceiver);
localBroadcastManager.unregisterReceiver(webRTCMessageReceiver);
if (writingIndicator != null) {
writingIndicator.dispose();
}
if (orientationManager != null) {
orientationManager.disable();
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (videoContainer == null) return;
if (webRTCView != null)
webRTCView.onPause();
final ViewGroup.LayoutParams layoutParams = videoContainer.getLayoutParams();
final ImageView image = findViewById(R.id.fullscreen_on_off);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
image.setImageResource(R.drawable.ninchat_icon_video_toggle_normal);
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
layoutParams.height = (int) getResources().getDimension(R.dimen.ninchat_chat_activity_video_view_height);
image.setImageResource(R.drawable.ninchat_icon_video_toggle_full);
}
videoContainer.setLayoutParams(layoutParams);
// Update pip video orientation
final View pip = videoContainer.findViewById(R.id.pip_video);
final ViewGroup.LayoutParams pipLayoutParams = pip.getLayoutParams();
pipLayoutParams.height = getResources().getDimensionPixelSize(R.dimen.ninchat_chat_activity_pip_video_height);
pipLayoutParams.width = getResources().getDimensionPixelSize(R.dimen.ninchat_chat_activity_pip_video_width);
pip.setLayoutParams(pipLayoutParams);
if (webRTCView != null)
webRTCView.onResume();
NinchatSessionManager sessionManager = NinchatSessionManager.getInstance();
if (sessionManager != null)
sessionManager.getOnInitializeMessageAdapter(adapter -> adapter.scrollToBottom(true));
}
// Reinitialize webRTC on hangup for possible new connection
private void hangUp() {
toggleFullScreen = false;
NinchatSessionManager sessionManager = NinchatSessionManager.getInstance();
if (sessionManager != null && webRTCView != null) {
webRTCView.hangUp();
}
}
// Listen for changes in root view height so we can determine when soft keyboard is visible
public void setRootViewHeightListener() {
final View activityRootView = getWindow().getDecorView().findViewById(android.R.id.content);
// Set initial rootViewHeight
if (rootViewHeight == 0) {
rootViewHeight = activityRootView.getHeight();
}
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
final ViewGroup.LayoutParams layoutParams = videoContainer.getLayoutParams();
// if new height differs from the cached one, keyboard visibility has changed
int heightDiff = activityRootView.getHeight() - rootViewHeight;
// Keyboard hidden
if (heightDiff > 0 && getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
layoutParams.height = (int) getResources().getDimension(R.dimen.ninchat_chat_activity_video_view_height);
// Update video height and cache current rootview height
videoContainer.setLayoutParams(layoutParams);
}
// Keyboard visible
else if (heightDiff < 0 && getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
layoutParams.height = (int) getResources().getDimension(R.dimen.ninchat_chat_activity_video_view_height_small);
// Update video height and cache current rootview height
videoContainer.setLayoutParams(layoutParams);
// push messages on top of soft keyboard
if (NinchatSessionManager.getInstance() != null) {
NinchatSessionManager.getInstance().getOnInitializeMessageAdapter(adapter -> adapter.scrollToBottom(true));
}
}
rootViewHeight = activityRootView.getHeight();
});
}
private void handleOrientationChange(int currentOrientation) {
if (toggleFullScreen) {
return;
}
try {
if (Settings.System.getInt(getApplicationContext().getContentResolver(), ACCELEROMETER_ROTATION, 0) != 1)
return;
} catch (Exception e) {
// pass
}
if (currentOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else if (currentOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
private void handleTitlebarView() {
if (webRTCView == null || !webRTCView.isInCall()) return;
if (!shouldShowTitlebar()) return;
int rotation = getWindowManager().getDefaultDisplay().getRotation();
switch (rotation) {
case Surface.ROTATION_0:
case Surface.ROTATION_180:
findViewById(R.id.ninchat_chat_root).findViewById(R.id.ninchat_titlebar).setVisibility(View.VISIBLE);
return;
case Surface.ROTATION_270:
case Surface.ROTATION_90:
findViewById(R.id.ninchat_chat_root).findViewById(R.id.ninchat_titlebar).setVisibility(View.GONE);
return;
}
}
@Override
public void onOrientationChange(int orientation) {
handleOrientationChange(orientation);
handleTitlebarView();
}
}
| 45.017264 | 227 | 0.656912 |
5763a76d84e32656acb0cf4241f294371ba8f891 | 1,811 | <#include "/macro.include">
<#assign className=table.className>
<#assign classNameLower=className?uncap_first>
package ${basepackage}.${modulepackage}.service.impl;
import org.springframework.stereotype.Service;
import ${basepackage}.${modulepackage}.dao.${className}Dao;
import ${basepackage}.${modulepackage}.model.${className};
import ${basepackage}.${modulepackage}.service.I${className}Service;
import javax.annotation.Resource;
import java.util.List;
/**
*
* @author ${author}
* @date ${now?string('yyyy-MM-dd HH:mm:ss')}
*/
@Service("${classNameLower}Service")
public class ${className}ServiceImpl implements I${className}Service{
@Resource
private ${className}Dao ${classNameLower}Dao;
@Override
public List<${className}> findList(${className} ${classNameLower}) {
return ${classNameLower}Dao.findList(${classNameLower});
}
@Override
public int insert(${className} ${classNameLower}) {
return ${classNameLower}Dao.insert(${classNameLower});
}
@Override
public int update(${className} ${classNameLower}) {
return ${classNameLower}Dao.update(${classNameLower});
}
@Override
public int updateIgnoreNull(${className} ${classNameLower}) {
return ${classNameLower}Dao.updateIgnoreNull(${classNameLower});
}
@Override
public ${className} findByColumn(String column, Object value) {
return ${classNameLower}Dao.findByColumn(column,value);
}
@Override
public int deleteByColumn(String column, Object value) {
return ${classNameLower}Dao.deleteByColumn(column,value);
}
@Override
public int batchDelete(${table.pkColumn.javaType}[] ${table.pkColumn.columnNameLower}s) {
return ${classNameLower}Dao.batchDelete(${table.pkColumn.columnNameLower}s);
}
} | 30.694915 | 93 | 0.699613 |
7dc82bc39e3f78307f25516788cfc6011c917b6a | 679 | package com.yudong80.java.ch07;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatExample {
public static void main(String[] args) {
//1. Date 클래스로 현재 시간 얻기
Date now = new Date();
//2. SimpleDateFormat 클래스로 형식 적용
SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy.MM.dd");
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat dateFormat3 = new SimpleDateFormat("yyyy/MM/dd");
System.out.println("다양한 날짜 형식:");
System.out.println("1: " + dateFormat1.format(now));
System.out.println("2: " + dateFormat2.format(now));
System.out.println("3: " + dateFormat3.format(now));
}
}
| 30.863636 | 68 | 0.718704 |
ce88b11727a3a9f2b7e1351684f3dfd88adedc19 | 5,814 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * 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. */
end_comment
begin_package
DECL|package|org.apache.hadoop.yarn.server.resourcemanager.metrics
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|resourcemanager
operator|.
name|metrics
package|;
end_package
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|resourcemanager
operator|.
name|rmapp
operator|.
name|RMApp
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|resourcemanager
operator|.
name|rmapp
operator|.
name|RMAppState
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|resourcemanager
operator|.
name|rmapp
operator|.
name|attempt
operator|.
name|RMAppAttempt
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|resourcemanager
operator|.
name|rmapp
operator|.
name|attempt
operator|.
name|RMAppAttemptState
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|resourcemanager
operator|.
name|rmcontainer
operator|.
name|RMContainer
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|YarnApplicationState
import|;
end_import
begin_comment
comment|/** * This class does nothing when any of the methods are invoked on * SystemMetricsPublisher. */
end_comment
begin_class
DECL|class|NoOpSystemMetricPublisher
specifier|public
class|class
name|NoOpSystemMetricPublisher
implements|implements
name|SystemMetricsPublisher
block|{
annotation|@
name|Override
DECL|method|appCreated (RMApp app, long createdTime)
specifier|public
name|void
name|appCreated
parameter_list|(
name|RMApp
name|app
parameter_list|,
name|long
name|createdTime
parameter_list|)
block|{ }
annotation|@
name|Override
DECL|method|appFinished (RMApp app, RMAppState state, long finishedTime)
specifier|public
name|void
name|appFinished
parameter_list|(
name|RMApp
name|app
parameter_list|,
name|RMAppState
name|state
parameter_list|,
name|long
name|finishedTime
parameter_list|)
block|{ }
annotation|@
name|Override
DECL|method|appACLsUpdated (RMApp app, String appViewACLs, long updatedTime)
specifier|public
name|void
name|appACLsUpdated
parameter_list|(
name|RMApp
name|app
parameter_list|,
name|String
name|appViewACLs
parameter_list|,
name|long
name|updatedTime
parameter_list|)
block|{ }
annotation|@
name|Override
DECL|method|appAttemptRegistered (RMAppAttempt appAttempt, long registeredTime)
specifier|public
name|void
name|appAttemptRegistered
parameter_list|(
name|RMAppAttempt
name|appAttempt
parameter_list|,
name|long
name|registeredTime
parameter_list|)
block|{ }
annotation|@
name|Override
DECL|method|appAttemptFinished (RMAppAttempt appAttempt, RMAppAttemptState appAttemtpState, RMApp app, long finishedTime)
specifier|public
name|void
name|appAttemptFinished
parameter_list|(
name|RMAppAttempt
name|appAttempt
parameter_list|,
name|RMAppAttemptState
name|appAttemtpState
parameter_list|,
name|RMApp
name|app
parameter_list|,
name|long
name|finishedTime
parameter_list|)
block|{ }
annotation|@
name|Override
DECL|method|containerCreated (RMContainer container, long createdTime)
specifier|public
name|void
name|containerCreated
parameter_list|(
name|RMContainer
name|container
parameter_list|,
name|long
name|createdTime
parameter_list|)
block|{ }
annotation|@
name|Override
DECL|method|containerFinished (RMContainer container, long finishedTime)
specifier|public
name|void
name|containerFinished
parameter_list|(
name|RMContainer
name|container
parameter_list|,
name|long
name|finishedTime
parameter_list|)
block|{ }
annotation|@
name|Override
DECL|method|appUpdated (RMApp app, long currentTimeMillis)
specifier|public
name|void
name|appUpdated
parameter_list|(
name|RMApp
name|app
parameter_list|,
name|long
name|currentTimeMillis
parameter_list|)
block|{ }
annotation|@
name|Override
DECL|method|appStateUpdated (RMApp app, YarnApplicationState appState, long updatedTime)
specifier|public
name|void
name|appStateUpdated
parameter_list|(
name|RMApp
name|app
parameter_list|,
name|YarnApplicationState
name|appState
parameter_list|,
name|long
name|updatedTime
parameter_list|)
block|{ }
annotation|@
name|Override
DECL|method|appLaunched (RMApp app, long launchTime)
specifier|public
name|void
name|appLaunched
parameter_list|(
name|RMApp
name|app
parameter_list|,
name|long
name|launchTime
parameter_list|)
block|{ }
block|}
end_class
end_unit
| 18.225705 | 814 | 0.81149 |
bd0dec1c8257911f74e1913eb534c8bbb9b0e1fb | 748 | package com.wangjiegulu.rapidooo.library.compiler.part.impl;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;
import com.wangjiegulu.rapidooo.library.compiler.oooentry.OOOEntry;
import com.wangjiegulu.rapidooo.library.compiler.part.PartBrew;
import javax.lang.model.element.Modifier;
/**
* Author: wangjie Email: [email protected] Date: 2019-06-13.
*/
public class DefaultConstructorMethodPartBrew implements PartBrew {
@Override
public void brew(OOOEntry oooEntry, TypeSpec.Builder result) {
MethodSpec.Builder defaultConstructorMethod = MethodSpec.constructorBuilder()
.addModifiers(Modifier.PUBLIC);
result.addMethod(defaultConstructorMethod.build());
}
}
| 35.619048 | 85 | 0.775401 |
b80a78669c750ca50b8c1cff6ae22afca9eeb3a7 | 23,955 | /*
* 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.sysml.runtime.matrix.data;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.Callable;
import org.apache.sysml.hops.OptimizerUtils;
import org.apache.sysml.runtime.DMLRuntimeException;
import org.apache.sysml.runtime.instructions.InstructionUtils;
import org.apache.sysml.runtime.util.ConvolutionUtils;
import org.apache.sysml.utils.NativeHelper;
public class LibMatrixDNNHelper {
// *********************************** low-level runtime operator selection ***********************************************
// *********************************** based on runtime properties (sparsity, native, etc) ********************************
// These methods help reduce branch miss predictions and instruction-cache misses.
// Also, they simplify the design of LibMatrixDNN and help in code-maintenance.
/**
* Factory method that returns list of callable tasks for performing maxpooling operation
*
* @param params convolution parameters
* @return list of callable tasks for performing maxpooling operation
* @throws DMLRuntimeException if error occurs
*/
public static ArrayList<Callable<Long>> getMaxPoolingWorkers(ConvolutionParameters params) throws DMLRuntimeException {
ArrayList<Callable<Long>> ret = new ArrayList<>();
int k = OptimizerUtils.getConstrainedNumThreads(params.numThreads);
int taskSize = (int)(Math.ceil((double)params.N / k));
for(int i = 0; i*taskSize < params.N; i++) {
if(params.input1.isInSparseFormat())
ret.add(new LibMatrixDNNPoolingHelper.SparseMaxPooling(i*taskSize, Math.min((i+1)*taskSize, params.N), params));
else
ret.add(new LibMatrixDNNPoolingHelper.DenseMaxPooling(i*taskSize, Math.min((i+1)*taskSize, params.N), params));
}
return ret;
}
/**
* Factory method that returns list of callable tasks for performing maxpooling backward operation
*
* @param params convolution parameters
* @param performReluBackward whether to perform ReLU backward
* @return list of callable tasks for performing maxpooling backward operation
* @throws DMLRuntimeException if error occurs
*/
public static ArrayList<Callable<Long>> getMaxPoolingBackwardWorkers(ConvolutionParameters params, boolean performReluBackward) throws DMLRuntimeException {
ArrayList<Callable<Long>> ret = new ArrayList<>();
int k = OptimizerUtils.getConstrainedNumThreads(params.numThreads);
int taskSize = (int)(Math.ceil((double)params.N / k));
for(int i = 0; i*taskSize < params.N; i++) {
if(!params.input1.isInSparseFormat()) {
if(!params.input2.isInSparseFormat())
ret.add(new LibMatrixDNNPoolingBackwardHelper.PoolingBackwardDenseDense(i*taskSize, Math.min((i+1)*taskSize, params.N), params, performReluBackward));
else
ret.add(new LibMatrixDNNPoolingBackwardHelper.PoolingBackwardDenseSparse(i*taskSize, Math.min((i+1)*taskSize, params.N), params, performReluBackward));
}
else {
if(!params.input2.isInSparseFormat())
ret.add(new LibMatrixDNNPoolingBackwardHelper.PoolingBackwardSparseDense(i*taskSize, Math.min((i+1)*taskSize, params.N), params, performReluBackward));
else
ret.add(new LibMatrixDNNPoolingBackwardHelper.PoolingBackwardSparseSparse(i*taskSize, Math.min((i+1)*taskSize, params.N), params, performReluBackward));
}
}
return ret;
}
/**
* Factory method that returns list of callable tasks for performing relu backward operation
*
* @param params convolution parameters
* @return list of callable tasks for performing relu backward operation
* @throws DMLRuntimeException if error occurs
*/
public static ArrayList<Callable<Long>> getReluBackwardWorkers(ConvolutionParameters params) throws DMLRuntimeException {
ArrayList<Callable<Long>> ret = new ArrayList<>();
int k = OptimizerUtils.getConstrainedNumThreads(params.numThreads);
int taskSize = (int)(Math.ceil((double)params.N / k));
for(int i = 0; i*taskSize < params.N; i++) {
ret.add(new ReluBackward(i*taskSize, Math.min((i+1)*taskSize, params.N), params));
}
return ret;
}
/**
* Factory method that returns list of callable tasks for performing conv2d
*
* @param params convolution parameters
* @return list of callable tasks for performing conv2d
* @throws DMLRuntimeException if error occurs
*/
public static ArrayList<Callable<Long>> getConv2dWorkers(ConvolutionParameters params) throws DMLRuntimeException {
ArrayList<Callable<Long>> ret = new ArrayList<>();
// Try to create as many tasks as threads.
// Creating more tasks will help in tail, but would have additional overhead of maintaining the intermediate
// data structures such as im2col blocks.
int k = OptimizerUtils.getConstrainedNumThreads(params.numThreads);
int taskSize = (int)(Math.ceil((double)params.N / k));
// TODO: Decide here based on params whether to use LoopedIm2ColConv2dAllChannels or LoopedIm2ColConv2dOneChannel
// For now, let's stick to the existing approach of converting [1, CHW] to [CRS, PQ] as it allows matrix multiplication large enough matrix.
boolean allChannels = true; ArrayList<MatrixBlock> filters = null;
if(!allChannels) {
filters = splitFilter(params);
}
MatrixBlock in1 = params.input1;
boolean isEmptyDenseInput = !in1.isInSparseFormat() && in1.denseBlock == null;
boolean isTransPref = in1.sparse && !params.input2.sparse &&
MatrixBlock.evalSparseFormatInMemory(in1.clen, in1.rlen, in1.nonZeros);
//transpose filter once for efficient sparse-dense multiplies in LoopedIm2ColConv2dTransAllChan
//in order to share the temporary object and its creation costs across threads
if( !LibMatrixDNN.isEligibleForConv2dSparse(params)
&& !isEmptyDenseInput && allChannels && isTransPref ) {
params.input2 = LibMatrixReorg.transpose(params.input2,
new MatrixBlock(params.input2.clen, params.input2.rlen, false), k);
}
for(int i = 0; i*taskSize < params.N; i++) {
if(LibMatrixDNN.isEligibleForConv2dSparse(params))
ret.add(new LibMatrixDNNConv2dHelper.SparseNativeConv2d(i*taskSize, Math.min((i+1)*taskSize, params.N), params));
else if(!isEmptyDenseInput && allChannels && isTransPref)
ret.add(new LibMatrixDNNConv2dHelper.LoopedIm2ColConv2dTransAllChan(i*taskSize, Math.min((i+1)*taskSize, params.N), params));
else if(!isEmptyDenseInput && allChannels)
ret.add(new LibMatrixDNNConv2dHelper.LoopedIm2ColConv2dAllChan(i*taskSize, Math.min((i+1)*taskSize, params.N), params));
else if(!isEmptyDenseInput && !allChannels)
ret.add(new LibMatrixDNNConv2dHelper.LoopedIm2ColConv2dOneChan(i*taskSize, Math.min((i+1)*taskSize, params.N), params, filters));
else
throw new DMLRuntimeException("Unsupported operator");
}
return ret;
}
/**
* Factory method that returns list of callable tasks for performing conv2d backward filter
*
* @param params convolution parameters
* @return list of callable tasks for performing conv2d backward filter
* @throws DMLRuntimeException if error occurs
*/
public static ArrayList<Callable<Long>> getConv2dBackwardFilterWorkers(ConvolutionParameters params) throws DMLRuntimeException {
ArrayList<Callable<Long>> ret = new ArrayList<>();
// Try to create as many tasks as threads.
// Creating more tasks will help in tail, but would have additional overhead of maintaining the intermediate
// data structures such as im2col blocks.
int k = OptimizerUtils.getConstrainedNumThreads(params.numThreads);
int taskSize = (int)(Math.ceil((double)params.N / k));
boolean isEmptyDenseInput = (!params.input1.isInSparseFormat() && params.input1.denseBlock == null) ||
(!params.input2.isInSparseFormat() && params.input2.denseBlock == null);
for(int i = 0; i*taskSize < params.N; i++) {
if(LibMatrixDNN.isEligibleForConv2dBackwardFilterSparseDense(params))
ret.add(new LibMatrixDNNConv2dBackwardFilterHelper.SparseNativeConv2dBackwardFilterDense(i*taskSize, Math.min((i+1)*taskSize, params.N), params));
else if(!isEmptyDenseInput)
ret.add(new LibMatrixDNNConv2dBackwardFilterHelper.Conv2dBackwardFilter(i*taskSize, Math.min((i+1)*taskSize, params.N), params));
else
throw new DMLRuntimeException("Unsupported operator");
}
return ret;
}
/**
* Factory method that returns list of callable tasks for performing conv2d backward data
*
* @param params convolution parameters
* @return list of callable tasks for performing conv2d backward data
* @throws DMLRuntimeException if error occurs
*/
public static ArrayList<Callable<Long>> getConv2dBackwardDataWorkers(ConvolutionParameters params) throws DMLRuntimeException {
ArrayList<Callable<Long>> ret = new ArrayList<>();
// Try to create as many tasks as threads.
// Creating more tasks will help in tail, but would have additional overhead of maintaining the intermediate
// data structures such as im2col blocks.
int k = OptimizerUtils.getConstrainedNumThreads(params.numThreads);
int taskSize = (int)(Math.ceil((double)params.N / k));
boolean isEmptyDenseInput = (!params.input1.isInSparseFormat() && params.input1.denseBlock == null) ||
(!params.input2.isInSparseFormat() && params.input2.denseBlock == null);
for(int i = 0; i*taskSize < params.N; i++) {
if(LibMatrixDNN.isEligibleForConv2dBackwardDataDense(params))
ret.add(new LibMatrixDNNConv2dBackwardDataHelper.SparseNativeConv2dBackwardDataDense(i*taskSize, Math.min((i+1)*taskSize, params.N), params));
else if(!isEmptyDenseInput)
ret.add(new LibMatrixDNNConv2dBackwardDataHelper.Conv2dBackwardData(i*taskSize, Math.min((i+1)*taskSize, params.N), params));
else
throw new DMLRuntimeException("Unsupported operator");
}
return ret;
}
// *********************************** relu backward operator ******************************************************
/**
* Performs the operation: (X gt 0) * dout
*/
public static class ReluBackward implements Callable<Long>
{
public int _rl; public int _ru;
private final ConvolutionParameters _params;
double [] outputArray; int numOutCols;
public ReluBackward(int rl, int ru, ConvolutionParameters params) {
_rl = rl; _ru = ru;
_params = params;
outputArray= params.output.getDenseBlock();
numOutCols = params.input1.getNumColumns();
}
@Override
public Long call() throws Exception {
if(!_params.input1.isInSparseFormat() && !_params.input2.isInSparseFormat()) {
double [] inputArr = _params.input1.getDenseBlock();
double [] doutArr = _params.input2.getDenseBlock();
for(int i = _rl*numOutCols; i < _ru*numOutCols; i++) {
outputArray[i] = inputArr[i] > 0 ? doutArr[i] : 0;
}
}
else {
// Perform (X > 0)
ConvolutionUtils.scalarOperations(_params.input1, outputArray, _rl*numOutCols, numOutCols, _rl, _ru,
InstructionUtils.parseScalarBinaryOperator(">", false, 0));
// Then perform (X > 0) * dout
ConvolutionUtils.binaryOperationInPlace(_params.input2, outputArray, _rl*numOutCols, numOutCols, _rl, _ru,
LibMatrixDNN._binaryElementWiseMultiplication);
}
return 0L;
}
}
// *********************************** utility methods ******************************************************
/**
* Computes tensor indexes from column index such that column index is equal to ret[0]*HW + ret[1]*W + ret[2]
*
* @param j column index
* @param ret tensor indexes
* @param H second last dimension
* @param W last dimension
*/
static void computeTensorIndexes(int j, int [] ret, int H, int W) {
ret[0] = j / (H*W);
ret[1] = (j - ret[0]*(H*W))/W;
ret[2] = j % W;
}
//Split a filter of size [K, CRS] into c filters of [K, RS]
private static ArrayList<MatrixBlock> splitFilter(ConvolutionParameters _params) {
ArrayList<MatrixBlock> ret = new ArrayList<>();
int RS = _params.R*_params.S; int CRS = _params.C*_params.R*_params.S;
double [] filter = _params.input2.getDenseBlock(); int S = _params.S;
for(int c = 0; c < _params.C; c++) {
MatrixBlock mb = new MatrixBlock(_params.K, RS, false);
mb.allocateDenseBlock(); long nnz = 0;
double [] outputArr = mb.getDenseBlock();
if(filter != null) {
for(int k = 0; k < _params.K; k++) {
int outOffset = k*RS;
int filterOffset = k*CRS + c*RS;
for(int rs = 0; rs < RS; rs++) {
int outIndex = outOffset + rs;
outputArr[outIndex] = filter[filterOffset + rs];
nnz += outputArr[outIndex] != 0 ? 1 : 0;
}
}
}
else {
for(int k = 0; k < _params.K; k++) {
if( !_params.input2.sparseBlock.isEmpty(k) ) {
int [] tensorIndexes = new int[3];
// Find maxIndex
int apos = _params.input2.sparseBlock.pos(k);
int alen = _params.input2.sparseBlock.size(k);
int[] aix = _params.input2.sparseBlock.indexes(k);
double[] avals = _params.input2.sparseBlock.values(k);
for(int j=apos; j<apos+alen; j++) {
computeTensorIndexes(aix[j], tensorIndexes, _params.R, _params.S);
if(c != tensorIndexes[0])
continue;
int r = tensorIndexes[1];
int s = tensorIndexes[2];
outputArr[k*RS + r*S + s] = avals[j];
nnz += outputArr[k*RS + r*S + s] != 0 ? 1 : 0;
}
}
}
}
mb.setNonZeros(nnz);
ret.add(mb);
}
return ret;
}
// Single-threaded matrix multiplication
static void singleThreadedMatMult(MatrixBlock m1, MatrixBlock m2, MatrixBlock ret,
boolean recomputeNNZM1, boolean recomputeNNZM2, ConvolutionParameters params) throws DMLRuntimeException {
if(!params.enableNative || m1.isInSparseFormat() || m2.isInSparseFormat()) {
prepNonZerosForMatrixMult(m1, recomputeNNZM1);
prepNonZerosForMatrixMult(m2, recomputeNNZM2);
LibMatrixMult.matrixMult(m1, m2, ret, false);
ret.setNonZeros((long)ret.rlen*ret.clen);
}
else {
ret.sparse = false;
if(ret.getDenseBlock() == null)
ret.allocateDenseBlock();
NativeHelper.matrixMultDenseDense(m1.denseBlock, m2.denseBlock,
ret.denseBlock, m1.getNumRows(), m1.getNumColumns(), m2.getNumColumns(), 1);
ret.recomputeNonZeros();
}
}
static void addBias(int r, double [] out, double [] bias, int K, int PQ) {
for(int k=0, cix=r*K*PQ; k<K; k++, cix+=PQ)
LibMatrixMult.vectAddInPlace(bias[k], out, cix, PQ);
}
/**
* Returns the index of cell with maximum value. This method is optimized for dense input
*
* @param p output feature map height
* @param q output feature map width
* @param inputOffset offset to be used for input index
* @param inputArray input array
* @param params convolution parameters
* @param performReluBackward perform ReLU backward
* @return index of cell with maximum value
*/
static int getMaxIndex(int p, int q, int inputOffset, double [] inputArray, ConvolutionParameters params, boolean performReluBackward) {
int start_index_h = params.start_indexes_h[p];
int end_index_h = params.end_indexes_h[p];
int start_index_w = params.start_indexes_w[q];
int end_index_w = params.end_indexes_w[q];
int maxIndex = -1;
double maxVal = -Double.MAX_VALUE;
// Note: We do not treat pad as zero and hence we don't do:
// maxVal = 0
// if start_index_h < 0 || start_index_w < 0 || end_index_h >= params.H || end_index_w >= params.W
// Find maxIndex
double currDoutVal = -1;
for (int h = start_index_h; h < end_index_h; h++) {
for (int w = start_index_w; w < end_index_w; w++) {
currDoutVal = inputArray[inputOffset + h*params.W + w];
currDoutVal = performReluBackward && currDoutVal < 0 ? 0 : currDoutVal;
if(maxVal < currDoutVal) {
maxIndex = inputOffset + h*params.W + w;
maxVal = currDoutVal;
}
}
}
return maxIndex;
}
/**
* Returns the index of cell with maximum value. This method is optimized for sparse input
*
* @param p output feature map height
* @param q output feature map width
* @param inputOffset offset to be used for input index
* @param n number of images
* @param c number of channels
* @param input input matrix
* @param params convolution parameters
* @param performReluBackward perform ReLU on input
* @return index of the cell with maximum value
* @throws DMLRuntimeException if error occurs
*/
static int getMaxIndexSparse(int p, int q, int inputOffset, int n, int c, MatrixBlock input, ConvolutionParameters params, boolean performReluBackward) throws DMLRuntimeException {
if(!input.isInSparseFormat())
throw new DMLRuntimeException("Incorrect usage: Only sparse format supported");
int [] tensorIndexes = new int[3];
int start_index_h = params.start_indexes_h[p];
int end_index_h = params.end_indexes_h[p];
int start_index_w = params.start_indexes_w[q];
int end_index_w = params.end_indexes_w[q];
int maxIndex = -1;
double maxVal = -Double.MAX_VALUE;
// Note: We do not treat pad as zero and hence we don't do:
// maxVal = 0
// if start_index_h < 0 || start_index_w < 0 || end_index_h >= params.H || end_index_w >= params.W
// input.isEmptyBlock() check is done by the caller
if( !input.sparseBlock.isEmpty(n) ) {
// Find maxIndex
int apos = input.sparseBlock.pos(n);
int alen = input.sparseBlock.size(n);
int[] aix = input.sparseBlock.indexes(n);
double[] avals = input.sparseBlock.values(n);
for(int j=apos; j<apos+alen; j++) {
computeTensorIndexes(aix[j], tensorIndexes, params.H, params.W);
if(c != tensorIndexes[0])
continue;
int h = tensorIndexes[1];
int w = tensorIndexes[2];
if(h >= start_index_h && h < end_index_h && w >= start_index_w && w < end_index_w) {
double val = performReluBackward && avals[j] < 0 ? 0 : avals[j];
if(maxVal < val) {
maxIndex = inputOffset + h*params.W + w;
maxVal = val;
}
}
}
}
else {
maxIndex = inputOffset;
}
return maxIndex;
}
// Returns the row of matrix in dense format
static void getRowInDenseFormat(MatrixBlock input, int n, double [] ret) throws DMLRuntimeException {
if(input.getNumColumns() != ret.length) {
throw new DMLRuntimeException("Invalid parameters");
}
// Use temporary array to avoid binary search
if(input.isInSparseFormat()) {
Arrays.fill(ret, 0);
if( !input.sparseBlock.isEmpty(n) ) {
int apos = input.sparseBlock.pos(n);
int alen = input.sparseBlock.size(n);
int[] aix = input.sparseBlock.indexes(n);
double[] avals = input.sparseBlock.values(n);
for(int j=apos; j<apos+alen; j++)
ret[ aix[j] ] = avals[j];
}
}
else {
System.arraycopy(input.getDenseBlock(), n*input.getNumColumns(), ret, 0, input.getNumColumns());
}
}
// ------------------------------------------------------------------------------------------------------
// Since col2im always operates on intermediate generated as part of matmult, it is not clear which operator to select apriori.
// Therefore, it is provided as utility function rather than an operator (like im2col or rotate180)
//Converts input: PQ X CRS matrix and writes to 1 X CHW
static void doCol2imOverSingleImage(int outputN, MatrixBlock input, ConvolutionParameters params) throws DMLRuntimeException {
if(input.rlen != params.P*params.Q || input.clen != params.C*params.R*params.S) {
throw new DMLRuntimeException("Incorrect input dimensions");
}
double [] outputArray = null;
if (!params.output.isInSparseFormat())
outputArray = params.output.getDenseBlock();
else {
throw new DMLRuntimeException("Only dense output is implemented");
}
if(!input.isInSparseFormat()) {
double [] inputArray = input.getDenseBlock();
doCol2IMDenseInput(0, outputN, inputArray, outputArray, params);
}
else {
if(!input.isEmptyBlock()) {
int outOffset = outputN*params.C*params.H*params.W;
int HW = params.H*params.W;
int [] tensorIndexes = new int[3];
for(int i = 0; i < input.getNumRows(); i++) {
if( !input.sparseBlock.isEmpty(i) ) {
computeTensorIndexes(i, tensorIndexes, params.P, params.Q);
int p = tensorIndexes[1];
int q = tensorIndexes[2];
int tmpP = p*params.stride_h - params.pad_h;
int tmpQ = q*params.stride_w - params.pad_w;
if(tensorIndexes[0] != 0)
throw new DMLRuntimeException("Incorrect tensor indexes: " + tensorIndexes[0] + " != 0 <" + p + " " + q + " " + tensorIndexes[0] + params.P + " " + params.Q + ">");
int apos = input.sparseBlock.pos(i);
int alen = input.sparseBlock.size(i);
int[] aix = input.sparseBlock.indexes(i);
double[] avals = input.sparseBlock.values(i);
for(int j = apos; j < apos+alen; j++) {
computeTensorIndexes(aix[j], tensorIndexes, params.R, params.S);
int c = tensorIndexes[0];
int r = tensorIndexes[1];
int s = tensorIndexes[2];
int h = tmpP + r;
int w = tmpQ + s;
if(h >= 0 && h < params.H && w >= 0 && w < params.W) {
int outIndex = outOffset + c*HW + h*params.W + w;
outputArray[outIndex] += avals[j];
}
}
}
}
}
}
}
// Converts input: PQ X CRS matrix and writes to 1 X CHW if inputN == 0
// Or converts input: NPQ X CRS matrix and writes to N X CHW
private static void doCol2IMDenseInput(int inputN, int outputN, double [] inputArray, double [] outputArray, ConvolutionParameters params) throws DMLRuntimeException {
final int outputNOffset = outputN*params.C*params.H*params.W;
final int HW = params.H*params.W;
final int inputNPQ = inputN*params.P*params.Q;
final int CRS = params.C*params.R*params.S;
final int RS = params.R*params.S;
for (int p = 0; p < params.P; p++) {
// h = p*params.stride_h + r - params.pad_h
// = r + hOffset
// Based on restrictions: h >= 0 and r >= 0 and h < params.H and r < params.R, we get
// max(0, - hOffset) <= r < min(params.R, params.H - hOffset)
final int hOffset = p*params.stride_h - params.pad_h;
final int rStart = Math.max(0, - hOffset);
final int rEnd = Math.min(params.R, params.H - hOffset);
for (int q = 0; q < params.Q; q++) {
// Using the same logic as above on following:
// w = q*params.stride_w + s - params.pad_w
final int wOffset = q*params.stride_w - params.pad_w;
final int sStart = Math.max(0, - wOffset);
final int sEnd = Math.min(params.S, params.W - wOffset);
final int tempOffset = (inputNPQ + p*params.Q + q)*CRS;
for (int c = 0; c < params.C; c++) {
final int outOffset = outputNOffset + c*HW;
final int inputOffset = tempOffset + c*RS;
for (int r = rStart; r < rEnd; r++) {
for (int s = sStart; s < sEnd; s++) {
int inputIndex = inputOffset + r*params.S + s;
int outIndex = outOffset + (hOffset + r)*params.W + wOffset + s;
outputArray[outIndex] += inputArray[inputIndex];
}
}
}
}
}
}
private static void prepNonZerosForMatrixMult(MatrixBlock mb, boolean update) {
if( !update )
return;
//non-zeros are not evaluated for dense matrix multiplies
//so we simply need to ensure the block is not marked empty
if( !mb.isInSparseFormat() )
mb.setNonZeros((long)mb.getNumRows() * mb.getNumColumns());
else
mb.recomputeNonZeros();
}
}
| 42.100176 | 181 | 0.686036 |
0415264e9e5a275f2ff16bd677453579d516c4ea | 226 | package server;
public class WebsocketException extends Exception{
public WebsocketException(String message){
super(message);
}
public WebsocketException(String message, Throwable cause) {
super(message, cause);
}
}
| 18.833333 | 61 | 0.774336 |
38b0c773a5e9fd37aa826528a582f2f1a58d0a4d | 477 | package com.dumas.pedestal.framework.springboot.web.apicontrol.annotation;
import org.springframework.web.bind.annotation.Mapping;
import java.lang.annotation.*;
/**
* API 版本控制注解
*
* @author andaren
* @version V1.0
* @since 2020-05-12 16:33
*/
@Mapping
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface ApiVersion {
/**
* version value
*
* @return version
*/
int value();
}
| 17.035714 | 74 | 0.691824 |
c32d0c01b9c1c767b90c1c0ed9031d79ef1c604e | 2,363 | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.workbench.services.verifier.api.client.index.select;
import org.drools.workbench.services.verifier.api.client.index.keys.Value;
import org.drools.workbench.services.verifier.api.client.index.matchers.Matcher;
import org.drools.workbench.services.verifier.api.client.maps.MultiMapChangeHandler;
class ChangeHelper<T> {
private final Select<T> addedSelector;
private final Select<T> removedSelector;
ChangeHelper( final MultiMapChangeHandler.ChangeSet<Value, T> changeSet,
final Matcher matcher ) {
addedSelector = new Select<T>( changeSet.getAdded(),
matcher );
removedSelector = new Select<T>( changeSet.getRemoved(),
matcher );
}
boolean firstChanged( final Select.Entry first ) {
if ( containsEntry( removedSelector,
first ) ) {
return true;
} else if ( addedSelector.exists() ) {
return first.getKey().compareTo( addedSelector.firstEntry().getKey() ) > 0;
} else {
return false;
}
}
private boolean containsEntry( final Select<T> select,
final Select.Entry entry ) {
return select.asMap().keySet().contains( entry.getKey() ) && select.all().contains( entry.getValue() );
}
boolean lastChanged( final Select.Entry last ) {
if ( containsEntry( removedSelector,
last ) ) {
return true;
} else if ( addedSelector.exists() ) {
return last.getKey().compareTo( addedSelector.lastEntry().getKey() ) < 0;
} else {
return false;
}
}
}
| 38.112903 | 111 | 0.626746 |
38fac81e2a20899ed645a477a57c32ba7187d648 | 883 | package org.ghxiao.rxjava.intro;
import io.reactivex.rxjava3.core.Flowable;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
public class RxMultiCast {
public static void main(String[] args) {
final Flowable<Long> feed = Flowable.interval(1, 1, TimeUnit.SECONDS).share();;
feed.subscribe(data -> process("S1: " + data));
sleep(5000);
feed.subscribe(data -> process("S2: " + data));
sleep(10000);
}
public static void process(String m){
//sleep(2000);
System.out.println("time " + LocalDateTime.now()
+ " thread: " + Thread.currentThread().getName()
+ " processing " + m);
}
private static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| 27.59375 | 87 | 0.584371 |
c9bf180900c8aab3ffab311af69733231934f639 | 3,321 | package com.ngengs.android.cekinote.detailgame;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.ViewGroup;
import com.ngengs.android.cekinote.data.model.Game;
import com.ngengs.android.cekinote.detailgame.history.HistoryGameFragment;
import com.ngengs.android.cekinote.detailgame.managescore.ManageScoreFragment;
import java.util.ArrayList;
import java.util.List;
/**
* Created by ngengs on 12/20/2016.
*/
class DetailGamePagerAdapter extends FragmentPagerAdapter {
private String[] tabTitles;
private ManageScoreFragment manageScoreFragment;
private HistoryGameFragment historyGameFragment;
DetailGamePagerAdapter(FragmentManager fm, String[] title, Game gameData, List<Integer> scorePlayer1, List<Integer> scorePlayer2, List<Integer> scorePlayer3, List<Integer> scorePlayer4) {
super(fm);
if (title.length == 2) {
manageScoreFragment = ManageScoreFragment.newInstance(gameData.getPlayer1().getName(), gameData.getPlayer2().getName(), gameData.getPlayer3().getName(), gameData.getPlayer4().getName());
}
List<Integer> scorePlayer11 = new ArrayList<>();
List<Integer> scorePlayer21 = new ArrayList<>();
List<Integer> scorePlayer31 = new ArrayList<>();
List<Integer> scorePlayer41 = new ArrayList<>();
scorePlayer11.addAll(scorePlayer1);
scorePlayer21.addAll(scorePlayer2);
scorePlayer31.addAll(scorePlayer3);
scorePlayer41.addAll(scorePlayer4);
this.tabTitles = title;
historyGameFragment = HistoryGameFragment.newInstance(gameData.getPlayer1().getName(), gameData.getPlayer2().getName(), gameData.getPlayer3().getName(), gameData.getPlayer4().getName(), scorePlayer11, scorePlayer21, scorePlayer31, scorePlayer41);
}
@Override
public Fragment getItem(int position) {
if (getCount() == 2) {
switch (position) {
case 0:
return manageScoreFragment;
case 1:
return historyGameFragment;
}
} else {
return historyGameFragment;
}
return null;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
if (getCount() == 2) {
switch (position) {
case 0:
manageScoreFragment = (ManageScoreFragment) fragment;
break;
case 1:
historyGameFragment = (HistoryGameFragment) fragment;
break;
}
} else {
historyGameFragment = (HistoryGameFragment) fragment;
}
return fragment;
}
@Override
public int getCount() {
return tabTitles.length;
}
@Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
void updateDataScore(int scorePlayer1, int scorePlayer2, int scorePlayer3, int scorePlayer4) {
if (historyGameFragment != null) {
historyGameFragment.updateScore(scorePlayer1, scorePlayer2, scorePlayer3, scorePlayer4);
}
}
}
| 36.9 | 254 | 0.661548 |
f4cc4abd9578ae6486e3e66cccb61112f55886a5 | 7,214 | package com.tomaskostadinov.openbeatz.fragment;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.tomaskostadinov.openbeatz.R;
import com.tomaskostadinov.openbeatz.helpers.ConnectRestClient;
import com.tomaskostadinov.openbeatz.model.Guide;
import com.tomaskostadinov.openbeatz.model.GuideSection;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import cz.msebera.android.httpclient.Header;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link GuideDetailTabFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link GuideDetailTabFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class GuideDetailTabFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public String guideUrl;
private FragmentTabHost mTabHost;
private OnFragmentInteractionListener mListener;
public GuideDetailTabFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment LineupDayFragment.
*/
// TODO: Rename and change types and number of parameters
public static GuideDetailTabFragment newInstance(String param1, String param2) {
GuideDetailTabFragment fragment = new GuideDetailTabFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_lineup_day, container, false);
mTabHost = (FragmentTabHost) rootView.findViewById(android.R.id.tabhost);
mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.realtabcontent);
Bundle bundle = this.getArguments();
if (bundle != null) {
guideUrl = bundle.getString("url", "2223");
} else {
guideUrl = "https://connect.nearstage.com/v1/openbeatz/guide/1033/";
}
getGuide();
return rootView;
}
private void setTabs(Guide guides) {
for (int i = 0; i < guides.getSections().size(); i++) {
GuideSection guide = guides.getSections().get(i);
Bundle b = new Bundle();
b.putString("text", guide.getContent());
mTabHost.addTab(mTabHost.newTabSpec(guide.getId().toString()).setIndicator(guide.getTitle()), GuideDetailFragment.class, b);
}
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
public void getGuide() {
ConnectRestClient.getUrl(GuideDetailTabFragment.this.guideUrl, null, new JsonHttpResponseHandler() {
@Override
public void onStart() {
// called before request is started
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject guide) {
// called when response HTTP status is "200 OK"
try {
JSONArray sections = guide.getJSONArray("sections");
List<GuideSection> sectionList = new ArrayList<>();
for (int a = 0; a < sections.length(); a++) {
try {
JSONObject section = sections.getJSONObject(a);
GuideSection s = new GuideSection(
section.getInt("id"),
section.getString("title"),
section.getString("content")
);
sectionList.add(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
GuideDetailTabFragment.this.setTabs(new Guide(
guide.getString("title"),
guide.getString("subtitle"),
guide.getString("icon"),
guide.getString("type"),
guide.getInt("id"),
sectionList
));
} catch (JSONException e) {
e.printStackTrace();
}
}
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
}
@Override
public void onRetry(int retryNo) {
// called when request is retried
}
});
}
}
| 34.682692 | 136 | 0.611173 |
f8a90de8e23e68485588bf630a5ca9eab370ea0a | 3,629 | package il.org.spartan;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Formatter;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import fluent.ly.Iterables;
import fluent.ly.idiomatic;
import il.org.spartan.Aggregator.Aggregation;
/** import static il.org.spartan.utils.Box.*; import java.util.*; import
* il.org.spartan.iteration.Iterables; import il.org.spartan.Aggregator.*; /**
*
* @author Yossi Gil
* @since Apr 5, 2012 */
public class LaTeXTableWriter extends CSVLineWriter {
private static <K, V> void ensure(final Map<K, V> m, final K k, final V v) {
m.putIfAbsent(k, v);
}
private final Map<String, CSVLine> inner = new LinkedHashMap<>();
/** Instantiate {@link LaTeXTableWriter}. */
public LaTeXTableWriter() {
super(Renderer.LaTeX);
}
/** Instantiate {@link LaTeXTableWriter}.
*
* @param fileName */
public LaTeXTableWriter(final String fileName) {
super(fileName, Renderer.LaTeX);
}
@Override public boolean aggregating() {
boolean $ = super.aggregating();
for (final CSVLine nested : inner.values())
$ |= nested.aggregating();
return $;
}
@Override public final Iterable<Aggregation> aggregations() {
final Set<Aggregation> $ = new LinkedHashSet<>();
Iterables.addAll($, super.aggregations());
for (final CSVLine nested : inner.values())
Iterables.addAll($, nested.aggregations());
return $;
}
@Override public String close() {
if (!aggregating())
return super.close();
writer.writeln(super.renderer.headerEnd());
for (final Aggregation ¢ : aggregations())
writer.writeln(makeLine(collect(¢).values()));
return super.close();
}
@Override public String header() {
return renderer.allTop() + wrappingHeader() + makeLine(keys()) + renderer.headerEnd();
}
public CSVLine in(final Object innerTableName) {
return in(innerTableName + "");
}
public CSVLine in(final String innerTableName) {
ensure(inner, innerTableName, new CSVLine.Ordered());
return inner.get(innerTableName);
}
@Override public Collection<String> keys() {
final List<String> $ = new ArrayList<>(super.keys());
for (final AbstractStringProperties nested : inner.values())
Iterables.addAll($, nested.keys());
return $;
}
@Override public Collection<String> values() {
final List<String> $ = new ArrayList<>(super.values());
for (final AbstractStringProperties nested : inner.values())
Iterables.addAll($, nested.values());
return $;
}
@Override protected String extension() {
return ".tex";
}
private AbstractStringProperties collect(final Aggregation a) {
final AbstractStringProperties $ = new ListProperties();
addAggregates($, a);
for (final CSVLine nested : inner.values())
nested.addAggregates($, a);
return $;
}
private String wrappingHeader() {
if (inner.isEmpty())
return "";
final List<String> $ = new ArrayList<>();
try (Formatter f = new Formatter()) {
int column = size();
$.add(String.format("\\multicolumn{%d}{c}{\\mbox{}}", idiomatic.box(column)));
for (final String nestedTableName : inner.keySet()) {
f.format("\\cmidrule(lr){%d-", idiomatic.box(column + 1));
final int size = inner.get(nestedTableName).size();
$.add(String.format("\\multicolumn{%d}{c}{%s}", idiomatic.box(size), nestedTableName));
f.format("%d} ", idiomatic.box(column += size));
}
return makeLine($) + "\n" + f + "\n";
}
}
}
| 30.241667 | 95 | 0.65941 |
a67da5254ddf34308d40a20b24d05fd940098c38 | 473 | package org.pinae.simba.aop;
import java.lang.reflect.Method;
/**
* 判断方法或者类是否满足做为切入点的条件
*
* @author Huiyugeng
*
*/
public interface Pointcut {
/**
* 判断指定的方法是否满足做为切入点的条件
*
* @param method 需要切入的方法
* @param arg 方法的参数
* @return 是否满足做为切入点
*/
public boolean matcher(Method method, Object arg[]);
/**
* 判断装入的类是否满足做为切入点的条件
*
* @param clazz 需要切入的类
* @return 是否满足做为切入点
*/
public boolean matcher(Class<?> clazz);
}
| 15.766667 | 54 | 0.617336 |
3d4a121c13bb54b7662245eaa68509d7c2cb3cf5 | 920 | package com.atexpose.api.data_types;
import io.schinzel.basicutils.FunnyChars;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
*
* @author Schinzel
*/
public class StringDTTest {
@Test
public void testSomeMethod() {
StringDT string = new StringDT();
assertFalse(string.verifyValue("null"));
assertFalse(string.verifyValue(null));
String longString = StringUtils.repeat(' ', StringDT.MAX_LENGTH + 1);
assertFalse(string.verifyValue(longString));
longString = StringUtils.repeat(' ', StringDT.MAX_LENGTH);
assertTrue(string.verifyValue(longString));
assertTrue(string.verifyValue("åäö"));
for (FunnyChars charset : FunnyChars.values()) {
assertTrue(string.verifyValue(charset.getString()));
}
}
}
| 27.058824 | 77 | 0.68587 |
11cff4a225649373e630e66f4b3a1c6fb1653ce9 | 11,482 | package com.company.moviesapp;
import android.app.Activity;
import android.app.ProgressDialog;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.company.moviesapp.MovieViewModel.MainViewModel;
import com.company.moviesapp.adapter.MoviesAdapter;
import com.company.moviesapp.api.RetrofitClient;
import com.company.moviesapp.api.Service;
import com.company.moviesapp.model.Movies;
import com.company.moviesapp.model.MoviesResponse;
import com.company.moviesapp.movieDatabase.MovieEntity;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
public static final String LOG_TAG = MoviesAdapter.class.getName ();
private static final String BUNDLE_RECYCLER_LAYOUT = "recycler_layout";
private static String LIST_STATE = "list_state";
private RecyclerView recyclerView;
private MoviesAdapter adapter;
private List <Movies> moviesList;
private AppCompatActivity appCompatActivity = MainActivity.this;
private Parcelable savedRecyclerLayoutState;
private ArrayList <Movies> moviesInstance = new ArrayList <> ();
private ProgressDialog pd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate ( savedInstanceState );
setContentView ( R.layout.activity_main );
if (savedInstanceState != null) {
moviesInstance = savedInstanceState.getParcelableArrayList ( LIST_STATE );
savedRecyclerLayoutState = savedInstanceState.getParcelable ( BUNDLE_RECYCLER_LAYOUT );
displayData ();
} else {
initViews ();
}
}
private void displayData() {
recyclerView = findViewById ( R.id.recycler_view );
adapter = new MoviesAdapter ( this, moviesInstance );
if (getActivity ().getResources ().getConfiguration ().orientation == Configuration.ORIENTATION_PORTRAIT) {
recyclerView.setLayoutManager ( new GridLayoutManager ( this, 3 ) );
} else {
recyclerView.setLayoutManager ( new GridLayoutManager ( this, 6 ) );
}
recyclerView.setItemAnimator ( new DefaultItemAnimator () );
recyclerView.setAdapter ( adapter );
restoreLayoutManagerPosition ();
adapter.notifyDataSetChanged ();
}
private void restoreLayoutManagerPosition() {
if (savedRecyclerLayoutState != null) {
recyclerView.getLayoutManager ().onRestoreInstanceState ( savedRecyclerLayoutState );
}
}
private void initViews() {
recyclerView = findViewById ( R.id.recycler_view );
adapter = new MoviesAdapter ( this, moviesList );
if (getActivity ().getResources ().getConfiguration ().orientation == Configuration.ORIENTATION_PORTRAIT) {
recyclerView.setLayoutManager ( new GridLayoutManager ( this, 3 ) );
} else {
recyclerView.setLayoutManager ( new GridLayoutManager ( this, 6 ) );
}
recyclerView.setItemAnimator ( new DefaultItemAnimator () );
recyclerView.setAdapter ( adapter );
loadJSON ();
}
private void initViews2() {
recyclerView = findViewById ( R.id.recycler_view );
recyclerView.setAdapter ( adapter );
getAllFavorite ();
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState ( savedInstanceState );
savedInstanceState.putParcelableArrayList ( LIST_STATE, moviesInstance );
savedInstanceState.putParcelable ( BUNDLE_RECYCLER_LAYOUT, recyclerView.getLayoutManager ().onSaveInstanceState () );
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
moviesInstance = savedInstanceState.getParcelableArrayList ( LIST_STATE );
savedRecyclerLayoutState = savedInstanceState.getParcelable ( BUNDLE_RECYCLER_LAYOUT );
super.onRestoreInstanceState ( savedInstanceState );
}
public Activity getActivity(){
Context context = this;
while (context instanceof ContextWrapper){
if (context instanceof Activity){
return (Activity) context;
}
context = ((ContextWrapper) context).getBaseContext ();
}
return null;
}
private void loadJSON() {
String sortOrder = checkSortOrder ();
if (sortOrder.equals ( this.getString ( R.string.most_popular ) )) {
try {
if (BuildConfig.THE_MOVIE_DB_API_KEY.isEmpty ()) {
Toast.makeText ( getApplicationContext (), "Please obtain API Key ...", Toast.LENGTH_SHORT ).show ();
pd.dismiss ();
return;
}
RetrofitClient RetrofitClient = new RetrofitClient ();
Service apiService = com.company.moviesapp.api.RetrofitClient.getRetrofit ().create ( Service.class );
Call <MoviesResponse> call = apiService.getPopularMovies ( BuildConfig.THE_MOVIE_DB_API_KEY );
call.enqueue ( new Callback <MoviesResponse> () {
@Override
public void onResponse(Call <MoviesResponse> call, Response <MoviesResponse> response) {
if (response.isSuccessful ()) {
if (response.body () != null) {
List <Movies> movies = response.body ().getResults ();
moviesInstance.addAll ( movies );
recyclerView.setAdapter ( new MoviesAdapter ( getApplicationContext (), movies ) );
recyclerView.smoothScrollToPosition ( 0 );
}
}
}
@Override
public void onFailure(Call <MoviesResponse> call, Throwable t) {
Log.d ( "Error", t.getMessage () );
Toast.makeText ( MainActivity.this, "Error fetching data.", Toast.LENGTH_SHORT ).show ();
}
} );
} catch (Exception e) {
Log.d ( "Error", e.getMessage () );
Toast.makeText ( this, e.toString (), Toast.LENGTH_SHORT ).show ();
}
} else if (sortOrder.equals ( this.getString ( R.string.favorite ) )) {
initViews2 ();
} else {
try {
if (BuildConfig.THE_MOVIE_DB_API_KEY.isEmpty ()) {
Toast.makeText ( getApplicationContext (), "Please obtain API Key ...", Toast.LENGTH_SHORT ).show ();
pd.dismiss ();
return;
}
RetrofitClient RetrofitClient = new RetrofitClient ();
Service apiService = com.company.moviesapp.api.RetrofitClient.getRetrofit ().create ( Service.class );
Call <MoviesResponse> call = apiService.getTopRatedMovies ( BuildConfig.THE_MOVIE_DB_API_KEY );
call.enqueue ( new Callback <MoviesResponse> () {
@Override
public void onResponse(Call <MoviesResponse> call, Response <MoviesResponse> response) {
if (response.isSuccessful ()) {
if (response.body () != null) {
List <Movies> movies = response.body ().getResults ();
moviesInstance.addAll ( movies );
recyclerView.setAdapter ( new MoviesAdapter ( getApplicationContext (), movies ) );
recyclerView.smoothScrollToPosition ( 0 );
}
}
}
@Override
public void onFailure(Call <MoviesResponse> call, Throwable t) {
Log.d ( "Error", t.getMessage () );
Toast.makeText ( MainActivity.this, "Error fetching data.", Toast.LENGTH_SHORT ).show ();
}
} );
} catch (Exception e) {
Log.d ( "Error", e.getMessage () );
Toast.makeText ( this, e.toString (), Toast.LENGTH_SHORT ).show ();
}
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService ( Context.CONNECTIVITY_SERVICE );
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo ();
return activeNetworkInfo != null && activeNetworkInfo.isConnected ();
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater ().inflate ( R.menu.menu_main, menu );
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId ()){
case R.id.menu_settings:
Intent intent = new Intent ( this, SettingsActivity.class );
startActivity ( intent );
return true;
default:
return super.onOptionsItemSelected ( item );
}
}
private String checkSortOrder() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences ( this );
String sortOrder = preferences.getString (
this.getString ( R.string.sort_order_key ),
this.getString ( R.string.most_popular )
);
return sortOrder;
}
private void getAllFavorite() {
MainViewModel mainViewModel = ViewModelProviders.of ( this ).get ( MainViewModel.class );
mainViewModel.getFavoriteMovie ().observe ( this, new Observer <List <MovieEntity>> () {
@Override
public void onChanged(@Nullable List <MovieEntity> movieEntities) {
if (movieEntities != null) {
List <Movies> movies = new ArrayList <> ();
for (MovieEntity movieEntity : movieEntities) {
Movies movie = new Movies ();
movie.setId ( movieEntity.getMovieId () );
movie.setOverview ( movieEntity.getOverview () );
movie.setOriginalTitle ( movieEntity.getTitle () );
movie.setPosterPath ( movieEntity.getPosterPath () );
movie.setVoteAverage ( movieEntity.getUserRating () );
movies.add ( movie );
}
adapter.setMovies ( movies );
}
}
} );
}
}
| 40.572438 | 125 | 0.606863 |
cd00d526785bd41a3f067e2fd44fa7f91f1c76f6 | 906 | package com.je_chen.collision;
import java.awt.*;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList objects = new ArrayList() ; //想要檢查碰撞的Object
QuadTree quad = new QuadTree(0, new Rectangle(0,0,600,600)); // 4 叉樹
quad.Clear();
ArrayList allObjects = new ArrayList();
//每frame都要重新插入
for (int i = 0; i < allObjects.size(); i++) {
quad.Insert((Rectangle) allObjects.get(i));
}
ArrayList returnObjects = new ArrayList();
for (int i = 0; i < allObjects.size(); i++) {
returnObjects.clear();
quad.Retrieve(returnObjects, (Rectangle) objects.get(i));
for (int x = 0; x < returnObjects.size(); x++) {
// Run collision detection algorithm between objects
}
}
}
}
| 28.3125 | 77 | 0.547461 |
c830e64c4cd2068c85bc53e3ba71812eb0ccb517 | 3,430 | /*
* Copyright 2011 CodeGist.org
*
* 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.
*
* ===================================================================
*
* More information at http://www.codegist.org.
*/
package org.codegist.crest.deserialization.common;
import org.codegist.crest.BaseCRestTest;
import org.codegist.crest.util.model.SomeData;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
/**
* @author [email protected]
*/
public class CommonComplexObjectDeserializationsTest<T extends IComplexObjectDeserializations> extends BaseCRestTest<T> {
public CommonComplexObjectDeserializationsTest(CRestHolder crest, Class<T> service) {
super(crest, service);
}
@Test
public void testSomeDataGuessed() throws IOException {
SomeData actual = toTest.someDataGuessed(getEffectiveDateFormat(), getEffectiveBooleanTrue(), getEffectiveBooleanFalse());
SomeData expected = expected();
assertSomeDataGuessed(expected, actual);
}
public void assertSomeDataGuessed(SomeData expected, SomeData actual){
assertEquals(expected, actual);
}
@Test
public void testSomeDataForced() throws IOException {
SomeData actual = toTest.someDataForced(getEffectiveDateFormat(), getEffectiveBooleanTrue(), getEffectiveBooleanFalse());
SomeData expected = expected();
assertSomeDataForced(expected, actual);
}
public void assertSomeDataForced(SomeData expected, SomeData actual){
assertEquals(expected, actual);
}
@Test
public void testSomeDatas() throws IOException {
SomeData[] actual = toTest.someDatas(getEffectiveDateFormat(), getEffectiveBooleanTrue(), getEffectiveBooleanFalse());
SomeData[] expected = {expected(),expected()};
assertSomeDatas(expected, actual);
}
public void assertSomeDatas(SomeData[] expected, SomeData[] actual){
assertArrayEquals(expected, actual);
}
@Test
public void testSomeDatas2() throws IOException {
List<? extends SomeData> actual = toTest.someDatas2(getEffectiveDateFormat(), getEffectiveBooleanTrue(), getEffectiveBooleanFalse());
List<? extends SomeData> expected = asList(expected(),expected());
assertSomeDatas2(expected, actual);
}
public void assertSomeDatas2(List<? extends SomeData> expected, List<? extends SomeData> actual){
assertEquals(expected, actual);
}
private static SomeData expected(){
SomeData expected = new SomeData() {
};
expected.setBool(true);
expected.setDate(date("1926-02-20T12:32:01+00:00", "yyyy-MM-dd'T'HH:mm:ss+00:00"));
expected.setNum(13);
return expected;
}
}
| 33.960396 | 141 | 0.693878 |
3f9a70d0088a10d58b32d45e62568bdf908b4511 | 435 | package iota.client.gui.presenter;
import iota.client.UpdateAbleView;
import iota.client.model.EspDevice;
import java.util.List;
public interface IoTaPresenter {
public EspDevice getSelectedEspDevice();
public void setSelectedEspDevice(EspDevice devIn);
public List<EspDevice> getDeviceList();
public void registerUpdateAbleView(UpdateAbleView view);
public void removeUpdateAbleView(UpdateAbleView view);
}
| 22.894737 | 60 | 0.790805 |
264bcfcd0028b166767f7cc02b01a801c67a15ea | 3,450 | package org.firstinspires.ftc.teamcode.RelicRecovery;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.util.ElapsedTime;
/**
* Created by MichaelL on 9/25/17.
*/
@TeleOp(name="mecanumTeleOp", group="mecanum")
@Disabled
public class mecanumOp extends OpMode{
private mecanumHardware robot = new mecanumHardware();
private ElapsedTime runtime = new ElapsedTime();
private boolean flipped = false;
@Override
public void init() {
runtime.reset();
robot.init(hardwareMap);
//robot.JewelServo.setPosition(0.5);
telemetry.addData("Status", "Initialized");
}
@Override
public void loop() {
runtime.reset();
telemetry.addData("Status", "Running: " + runtime.toString());
telemetry.update();
//robot.leftMotor.setPower(gamepad1.left_stick_y);
// robot.rightMotor.setPower(gamepad1.right_stick_y);
//if (gamepad1.left_stick_y) {
//robot.JewelServo.setPosition(0.1); //rest position unknown currently
if (gamepad1.dpad_left) { //strafe left
robot.frontleftMotor.setPower(-1);
robot.backleftMotor.setPower(1);
robot.frontrightMotor.setPower(1);
robot.backrightMotor.setPower(-1);
} else if (gamepad1.dpad_right) { //strafe right
robot.frontleftMotor.setPower(1);
robot.backleftMotor.setPower(-1);
robot.frontrightMotor.setPower(-1);
robot.backrightMotor.setPower(1);
} else if (gamepad1.dpad_up) { //full forwards
robot.frontleftMotor.setPower(1);
robot.backleftMotor.setPower(1);
robot.frontrightMotor.setPower(1);
robot.backrightMotor.setPower(1);
} else if (gamepad1.dpad_down) { //full backwards
robot.frontleftMotor.setPower(-1);
robot.backleftMotor.setPower(-1);
robot.frontrightMotor.setPower(-1);
robot.backrightMotor.setPower(-1);
} else if (gamepad1.left_bumper) { //left diagonal
robot.frontleftMotor.setPower(0);
robot.backrightMotor.setPower(0);
robot.backleftMotor.setPower(1);
robot.frontrightMotor.setPower(1);
} else if (gamepad1.right_bumper) { //right diagonal
robot.frontleftMotor.setPower(1);
robot.backrightMotor.setPower(1);
robot.backleftMotor.setPower(0);
robot.frontrightMotor.setPower(0);
}
else {
/*/robot.frontleftMotor.setPower(0);
robot.backleftMotor.setPower(0);
robot.frontrightMotor.setPower(0);
robot.backrightMotor.setPower(0);/*/
robot.move((flipped ? -gamepad1.right_stick_y : gamepad1.left_stick_y), //should be tank drive
(flipped ? gamepad1.left_stick_y : -gamepad1.right_stick_y));
}
/*/
if (gamepad1.a) {
robot.JewelServo.setPosition();
} else (gamepad1.b) {
robot.
}
/*/
}
@Override
public void stop() {
robot.frontleftMotor.setPower(0);
robot.frontrightMotor.setPower(0);
robot.backleftMotor.setPower(0);
robot.backrightMotor.setPower(0);
}
}
| 35.9375 | 107 | 0.614783 |
05d19e119e506823ce7d81bbe00192a8b52bc7b6 | 9,203 | /*******************************************************************************
* Copyright 2017 Anindya Bandopadhyay ([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 org.pojotester.pack.scan;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.DirectoryIteratorException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import org.pojotester.utils.ClassUtilities;
public abstract class PackageScan {
private static final char PATH_SEPARATOR_CHAR = File.separatorChar;
private static final char WILDCARD_CHAR = '*';
private static final String WILDCARD_REGX = "**";
private static final String PATH_SEPARATOR = File.separator;
private static final String DOT = "\\.";
private static final String CLASS_FILE_SUFFIX = ".class";
private static final String CLASS_SUFFIX = "class";
private static final String ILLEGAL_PACKAGE = "Package cannot start with " + WILDCARD_REGX ;
public Set<Class<?>> getClasses(final String... packagesToScan) {
Set<Class<?>> classSet = Collections.emptySet();
if (packagesToScan != null) {
classSet = new HashSet<Class<?>>();
for (String location : packagesToScan) {
if (location.startsWith(WILDCARD_REGX)) {
throw new IllegalArgumentException(ILLEGAL_PACKAGE + " [ " + location + " ]");
}
String startPackage = location.split(DOT)[0];
location = processLocations(location);
String rootDirectory = determineRootDirectory(location);
String patternString = "";
if (!location.equals(rootDirectory)) {
patternString = location.substring(rootDirectory.length() + 1);
}
if (patternString.isEmpty()) {
// When exact path is given [e.g. mypack.MyClass.class]
String binaryClassName = getQualifiedClassName(startPackage, rootDirectory);
Class<?> clazz = loadClass(binaryClassName);
if (isClass(clazz)) {
classSet.add(clazz);
}
} else {
// Goto root directory and match pattern to search
// directories/files [e.g. mypack.**.My*.class,
// mypack.**.MyClass.class]
List<String> patterns = new LinkedList<String>();
String[] patternStringArray = patternString.split(Matcher.quoteReplacement(PATH_SEPARATOR));
String classFilePattern = WILDCARD_CHAR + CLASS_FILE_SUFFIX;
for (String pattern : patternStringArray) {
if (pattern.endsWith(CLASS_FILE_SUFFIX)) {
classFilePattern = pattern;
} else if (!WILDCARD_REGX.equals(pattern)) {
patterns.add(pattern);
}
}
Set<String> classFiles = Collections.emptySet();
// Check for class
Set<File> packageDirectories = findPackageDirectory(rootDirectory, patternStringArray);
for (File packageDirectory : packageDirectories) {
Path path = packageDirectory.toPath();
classFiles = findClassFiles(path, classFilePattern);
for (String className : classFiles) {
String binaryClassName = getQualifiedClassName(startPackage, className);
Class<?> clazz = loadClass(binaryClassName);
if (isClass(clazz)) {
classSet.add(clazz);
}
}
}
}
}
}
return classSet;
}
protected String determineRootDirectory(final String location){
char[] sources = location.toCharArray();
int endIndex = 0;
String rootDirectory = location;
int indexOfWildcard = indexofWildcardChar(sources);
if(indexOfWildcard < sources.length){
for(int index = indexOfWildcard ; index > -1 ; index--){
if(sources[index] == PATH_SEPARATOR_CHAR){
break;
}
endIndex++;
}
endIndex = indexOfWildcard - endIndex;
char[] rootDirChars = Arrays.copyOfRange(sources, 0, endIndex);
rootDirectory = new String(rootDirChars);
}
return rootDirectory;
}
private int indexofWildcardChar(char[] sources) {
int indexOfWildcard = 0;
for(char chr : sources){
if(chr == WILDCARD_CHAR){
break;
}
indexOfWildcard++;
}
return indexOfWildcard;
}
private String processLocations(String location) {
location = location.replaceAll(DOT, Matcher.quoteReplacement(PATH_SEPARATOR));
String pathSeparatorClassSuffix = PATH_SEPARATOR + CLASS_SUFFIX;
if(location.endsWith(pathSeparatorClassSuffix)){
int endIndex = location.length() - pathSeparatorClassSuffix.length();
location = location.substring(0, endIndex);
location += CLASS_FILE_SUFFIX;
}
if(!location.endsWith(CLASS_FILE_SUFFIX)){
// When path end with *.* instead of *.class
String pathSeparatorWildCard = PATH_SEPARATOR + WILDCARD_CHAR;
if(location.endsWith(pathSeparatorWildCard)){
int endIndex = location.length() - pathSeparatorWildCard.length();
location = location.substring(0, endIndex);
location += pathSeparatorClassSuffix;
} else {
// When only folder is given
location += (PATH_SEPARATOR + WILDCARD_CHAR + CLASS_FILE_SUFFIX);
}
}
return location;
}
private Set<File> findPackageDirectory(String rootDirectory, String[] patternStringArray) {
ClassLoader classLoader = ClassUtilities.getDefaultClassLoader();
URL url = classLoader.getResource(rootDirectory);
URI uri = null;
Set<File> packageDirectories = Collections.emptySet();
try {
uri = url.toURI();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
if (uri != null) {
if (patternStringArray.length > 0 && !patternStringArray[0].endsWith(CLASS_FILE_SUFFIX)) {
patternStringArray = Arrays.copyOfRange(patternStringArray, 0, (patternStringArray.length - 1));
packageDirectories = patternMaching(uri, patternStringArray);
} else {
packageDirectories = new TreeSet<>();
packageDirectories.add(new File(uri));
}
}
return packageDirectories;
}
private Set<File> patternMaching(URI uri, String[] patternStringArray) {
Set<File> packageDirectories = Collections.emptySet();
int index = 0;
int previousIndex = -1;
int lastIndex = patternStringArray.length - 1;
DirectoryFinder visitor = new DirectoryFinder();
Path startDirectory = Paths.get(uri);
for (String pattern : patternStringArray) {
if (!isWildCard(pattern) || index == lastIndex) {
visitor.createMatcher(pattern);
visitor.setFirstPattern((index == 0));
visitor.setAfterWildCard((previousIndex != -1 && (isWildCard(patternStringArray[previousIndex]))));
visitor.setLastPattern((index == lastIndex));
try {
Files.walkFileTree(startDirectory, visitor);
} catch (IOException e) {
e.printStackTrace();
}
Path path = visitor.getCurrentPath();
if (path != null) {
startDirectory = path;
}
}
index++;
previousIndex++;
if (!isWildCard(pattern) && visitor.getNumMatches() == 0) {
break;
}
}
packageDirectories = visitor.getDirectories();
return packageDirectories;
}
private Set<String> findClassFiles(Path dir, String patternString) {
Set<String> classFiles = Collections.emptySet();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, patternString)){
classFiles = new HashSet<String>();
for(Path path : stream){
File file = path.toFile();
if(file.isFile()){
classFiles.add(file.getAbsolutePath());
}
}
} catch (DirectoryIteratorException | IOException ex) {
ex.printStackTrace();
}
return classFiles;
}
private String getQualifiedClassName(String startPackage, String classNamePath) {
int endIndex = classNamePath.length() - CLASS_FILE_SUFFIX.length();
int startIndex = classNamePath.indexOf(startPackage);
classNamePath = classNamePath.substring(startIndex, endIndex);
if(classNamePath.contains(File.separator)){
String separator = File.separator + File.separator ;
classNamePath = classNamePath.replaceAll(separator, DOT);
} else {
classNamePath = classNamePath.replaceAll(PATH_SEPARATOR, DOT);
}
return classNamePath;
}
private boolean isClass(Class<?> clazz) {
return (clazz != null) && (!clazz.isAnnotation()) && (!clazz.isInterface()) && (!clazz.isEnum()) && (!Modifier.isAbstract(clazz.getModifiers()));
}
private boolean isWildCard(String pattern) {
return WILDCARD_REGX.equals(pattern) || Character.toString(WILDCARD_CHAR).equals(pattern);
}
protected abstract Class<?> loadClass(String className);
} | 34.339552 | 147 | 0.700315 |
537fd9975c3bbbc00cfe2fec46cfc904053039f0 | 1,112 | package chess;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import builder.ChessBuilderParts;
import debug.builder.DebugChessFactory;
import iterators.SquareIterator;
import layers.ColorBoard;
import layers.PosicionPiezaBoard;
import parsers.FENParser;
/**
* @author Mauricio Coria
*
*/
public class ColorBoardTest {
private ColorBoard colorBoard;
@Test
public void test01() {
int totalPiezas = 0;
PosicionPiezaBoard tablero = getTablero("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR");
colorBoard = new ColorBoard(tablero);
for (SquareIterator iterator = colorBoard.iteratorSquare(Color.BLANCO); iterator.hasNext();) {
Pieza pieza = tablero.getPieza(iterator.next());
assertEquals(Color.BLANCO, pieza.getColor());
totalPiezas++;
}
assertEquals(16, totalPiezas);
}
private PosicionPiezaBoard getTablero(String string) {
ChessBuilderParts builder = new ChessBuilderParts(new DebugChessFactory());
FENParser parser = new FENParser(builder);
parser.parsePiecePlacement(string);
return builder.getPosicionPiezaBoard();
}
}
| 21.384615 | 96 | 0.752698 |
b221f49d72dcd2d4c1be04ae80760ee12d980cb5 | 4,531 | /*******************************************************************************
* Copyright 2016 ContainX and OpenStack4j
*
* 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.huawei.openstack4j.openstack.networking.internal;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.List;
import java.util.Map;
import com.huawei.openstack4j.api.networking.NetFloatingIPService;
import com.huawei.openstack4j.core.transport.ExecutionOptions;
import com.huawei.openstack4j.core.transport.propagation.PropagateOnStatus;
import com.huawei.openstack4j.model.common.ActionResponse;
import com.huawei.openstack4j.model.network.NetFloatingIP;
import com.huawei.openstack4j.openstack.networking.domain.NeutronFloatingIP;
import com.huawei.openstack4j.openstack.networking.domain.NeutronFloatingIP.FloatingIPs;
/**
* FloatingIPService implementation that provides Neutron Floating-IP based Service Operations.
*
* @author Nathan Anderson
*/
public class FloatingIPServiceImpl extends BaseNetworkingServices implements NetFloatingIPService {
/**
* {@inheritDoc}
*/
@Override
public List<? extends NetFloatingIP> list() {
return get(FloatingIPs.class, uri("/floatingips")).execute().getList();
}
/**
* {@inheritDoc}
*/
@Override
public List<? extends NetFloatingIP> list(Map<String, String> filteringParams) {
Invocation<FloatingIPs> fIPsInvocation = get(FloatingIPs.class, "/floatingips");
if (filteringParams != null) {
for (Map.Entry<String, String> entry : filteringParams.entrySet()) {
fIPsInvocation = fIPsInvocation.param(entry.getKey(), entry.getValue());
}
}
return fIPsInvocation.execute().getList();
}
/**
* {@inheritDoc}
*/
@Override
public NetFloatingIP get(String id) {
checkNotNull(id);
return get(NeutronFloatingIP.class, uri("/floatingips/%s", id)).execute();
}
/**
* {@inheritDoc}
*/
@Override
public ActionResponse delete(String id) {
checkNotNull(id);
return deleteWithResponse(uri("/floatingips/%s", id)).execute();
}
/**
* {@inheritDoc}
*/
@Override
public NetFloatingIP create(NetFloatingIP floatingIp) {
checkNotNull(floatingIp);
checkNotNull(floatingIp.getFloatingNetworkId());
return post(NeutronFloatingIP.class, uri("/floatingips")).entity(floatingIp).execute();
}
/**
* {@inheritDoc}
*/
@Override
public NetFloatingIP associateToPort(String id, String portId) {
checkNotNull(id);
checkNotNull(portId);
String inner = String.format("{ \"port_id\":\"%s\" }", portId);
String json = String.format("{ \"%s\": %s }", "floatingip", inner);
return put(NeutronFloatingIP.class, uri("/floatingips/%s",id)).json(json)
.execute(ExecutionOptions.<NeutronFloatingIP>create(PropagateOnStatus.on(404)));
}
/**
* {@inheritDoc}
*/
@Override
public NetFloatingIP disassociateFromPort(String id) {
checkNotNull(id);
String json = String.format("{ \"%s\": %s }", "floatingip", "{ \"port_id\":null }");
return put(NeutronFloatingIP.class, uri("/floatingips/%s",id)).json(json)
.execute(ExecutionOptions.<NeutronFloatingIP>create(PropagateOnStatus.on(404)));
}
}
| 40.097345 | 99 | 0.577356 |
1ca4d580d07cddad6e25123f9f4a150d573aa606 | 611 | package org.example.demo.leetcode.twopointer;
import junit.framework.TestCase;
public class SolutionTest extends TestCase {
Solution solution;
@Override
protected void setUp() throws Exception {
super.setUp();
solution = new Solution();
}
public void testRemoveDuplicates() {
int[] nums = {1, 1, 2}; // 输入数组
int[] expectedNums = {1,2}; // 长度正确的期望答案
int k = solution.removeDuplicates(nums, 1); // 调用
assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
assert nums[i] == expectedNums[i];
}
}
} | 21.821429 | 57 | 0.582651 |
64e78c0627b7421d9176a99e220fc54baabe19b1 | 558 | package com.jptangchina.jxcel;
import com.jptangchina.jxcel.bean.Student;
import org.junit.Assert;
import org.junit.Test;
import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.util.List;
public class JxcelParserTest {
@Test
public void testParseFromFile() {
String desktop = FileSystemView.getFileSystemView().getHomeDirectory().getPath();
List<Student> result = JxcelParser.parser().parseFromFile(Student.class, new File(desktop + "/jxcel.xlsx"));
Assert.assertTrue(result.size() > 0);
}
}
| 26.571429 | 116 | 0.731183 |
1b6e6cd53b4bddd8ed3830c4c40fc8314f8c34ba | 2,186 | /*
* Copyright 2014 Groupon.com
*
* 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.arpnetworking.tsdcore.sinks;
import com.arpnetworking.tsdcore.model.PeriodicData;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests for the <code>BaseSink</code> class.
*
* @author Ville Koskela (ville dot koskela at inscopemetrics dot com)
*/
public class BaseSinkTest {
@Test
public void testName() {
final String expectedName = "TheSinkName";
final TestAggregatedDataSink sink = new TestAggregatedDataSink.Builder()
.setName(expectedName)
.build();
Assert.assertEquals(expectedName, sink.getName());
}
@Test
public void testMetricName() {
final TestAggregatedDataSink sink = new TestAggregatedDataSink.Builder()
.setName("The.Sink.Name")
.build();
Assert.assertEquals("The_Sink_Name", sink.getMetricSafeName());
}
private static final class TestAggregatedDataSink extends BaseSink {
@Override
public void recordAggregateData(final PeriodicData data) {
// Nothing to do
}
@Override
public void close() {
// Nothing to do
}
private TestAggregatedDataSink(final Builder builder) {
super(builder);
}
private static final class Builder extends BaseSink.Builder<Builder, TestAggregatedDataSink> {
private Builder() {
super(TestAggregatedDataSink::new);
}
@Override
protected Builder self() {
return this;
}
}
}
}
| 29.146667 | 102 | 0.642269 |
db4c8353d5c0006e404a0366de5b834585769b19 | 4,680 | package com.b2vnradarapi.b2vnradarapi.modules.radar.repository;
import com.b2vnradarapi.b2vnradarapi.modules.radar.dto.*;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import java.time.LocalDateTime;
import java.util.List;
import static com.b2vnradarapi.b2vnradarapi.modules.radar.model.QContagens.contagens;
@Repository
public class ContagensRepositoryImpl implements ContagensRepositoryCustom {
@Autowired
private EntityManager entityManager;
@Override
public RadarContagemResponse findFluxoVeiculosByCodigo(Integer codigo) {
return new JPAQuery<Void>(entityManager)
.select(Projections.constructor(
RadarContagemResponse.class,
contagens.contagem.sum(),
contagens.contagem.count()
))
.from(contagens)
.where(contagens.localidade.eq(codigo))
.fetchOne();
}
@Override
public RadarContagemResponse findFluxoVeiculosByCodigoAndDataHora(Integer codigo,
LocalDateTime dataHoraInicial,
LocalDateTime dataHoraFinal) {
return new JPAQuery<Void>(entityManager)
.select(Projections.constructor(
RadarContagemResponse.class,
contagens.contagem.sum(),
contagens.contagem.count()
))
.from(contagens)
.where(contagens.localidade.eq(codigo)
.and(contagens.dataHora.between(dataHoraFinal, dataHoraInicial)))
.fetchOne();
}
@Override
public List<TiposPorRadarResponse> findTiposPorRadar(Integer localidade) {
return new JPAQuery<Void>(entityManager)
.select(Projections.constructor(TiposPorRadarResponse.class,
contagens.localidade,
contagens.tipo,
contagens.tipo.count()))
.from(contagens)
.where(contagens.localidade.like("%" + localidade + "%"))
.groupBy(contagens.localidade, contagens.tipo)
.fetch();
}
@Override
public List<TiposRadarTotais> findTipos() {
return new JPAQuery<Void>(entityManager)
.select(Projections.constructor(TiposRadarTotais.class,
contagens.tipo,
contagens.tipo.count()))
.from(contagens)
.groupBy(contagens.tipo)
.fetch();
}
@Override
public List<ContagensInfracoesResponse> findAutuacoesRadares() {
return new JPAQuery<Void>(entityManager)
.select(Projections.constructor(ContagensInfracoesResponse.class,
contagens.localidade,
contagens.autuacoes.sum()))
.from(contagens)
.groupBy(contagens.localidade)
.orderBy(contagens.localidade.asc())
.fetch();
}
@Override
public ContagensInfracoesResponse findAutuacoesPorRadar(Integer codigoRadar) {
return new JPAQuery<Void>(entityManager)
.select(Projections.constructor(ContagensInfracoesResponse.class,
contagens.localidade,
contagens.autuacoes.sum()))
.from(contagens)
.where(contagens.localidade.like("%" + codigoRadar + "%"))
.groupBy(contagens.localidade)
.orderBy(contagens.localidade.asc())
.fetchOne();
}
@Override
public ContagensAcuraciaResponse findAcuraciaPorRadar(Integer codigoRadar) {
return new JPAQuery<Void>(entityManager)
.select(Projections.constructor(ContagensAcuraciaResponse.class,
contagens.localidade,
contagens.placas.sum(),
contagens.contagem.sum()))
.from(contagens)
.where(contagens.localidade.like("%" + codigoRadar + "%"))
.groupBy(contagens.localidade)
.orderBy(contagens.localidade.asc())
.fetchOne();
}
@Override
public List<ContagensAcuraciaResponse> findAcuraciaPorRadares() {
return new JPAQuery<Void>(entityManager)
.select(Projections.constructor(ContagensAcuraciaResponse.class,
contagens.localidade,
contagens.placas.sum(),
contagens.contagem.sum()))
.from(contagens)
.groupBy(contagens.localidade)
.orderBy(contagens.localidade.asc())
.fetch();
}
} | 37.44 | 89 | 0.62094 |
87cebfe6a1284c1c77f23ecb3153f1628c8c9310 | 637 | package com.poliplanner.controller;
import com.poliplanner.data.MateriaRepository;
import com.poliplanner.domain.model.Materia;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@CrossOrigin("*")
@RequestMapping(path = "/fpuna/materias", produces = "application/json")
public class MateriaController {
private MateriaRepository repo;
public MateriaController(MateriaRepository repo) {
this.repo = repo;
}
@GetMapping
public Iterable<Materia> listMaterias(@RequestParam("carrera") List<String> carreras){
return repo.findByCarreraCodigoIn(carreras);
}
}
| 26.541667 | 90 | 0.751962 |
4c6a2e75435a4d86f2be76837257821e75a78fce | 14,983 | /*
* 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.ranger.plugin.client;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.security.SecureClientLogin;
public class HadoopConfigHolder {
private static final Log LOG = LogFactory.getLog(HadoopConfigHolder.class);
public static final String GLOBAL_LOGIN_PARAM_PROP_FILE = "hadoop-login.properties";
public static final String DEFAULT_DATASOURCE_PARAM_PROP_FILE = "datasource.properties";
public static final String RESOURCEMAP_PROP_FILE = "resourcenamemap.properties";
public static final String DEFAULT_RESOURCE_NAME = "core-site.xml";
public static final String RANGER_SECTION_NAME = "xalogin.xml";
public static final String RANGER_LOGIN_USER_NAME_PROP = "username";
public static final String RANGER_LOGIN_KEYTAB_FILE_PROP = "keytabfile";
public static final String RANGER_LOGIN_PASSWORD = "password";
public static final String RANGER_LOOKUP_PRINCIPAL = "lookupprincipal";
public static final String RANGER_LOOKUP_KEYTAB = "lookupkeytab";
public static final String RANGER_PRINCIPAL = "rangerprincipal";
public static final String RANGER_KEYTAB = "rangerkeytab";
public static final String RANGER_NAME_RULES = "namerules";
public static final String RANGER_AUTH_TYPE = "authtype";
public static final String HADOOP_SECURITY_AUTHENTICATION = "hadoop.security.authentication";
public static final String HADOOP_NAME_RULES = "hadoop.security.auth_to_local";
public static final String HADOOP_SECURITY_AUTHENTICATION_METHOD = "kerberos";
public static final String HADOOP_RPC_PROTECTION = "hadoop.rpc.protection";
public static final String ENABLE_HIVE_METASTORE_LOOKUP = "enable.hive.metastore.lookup";
public static final String HIVE_SITE_FILE_PATH = "hive.site.file.path";
private static boolean initialized;
private static Map<String,HashMap<String,Properties>> dataSource2ResourceListMap = new HashMap<>();
private static Map<String,HadoopConfigHolder> dataSource2HadoopConfigHolder = new HashMap<>();
private static Properties globalLoginProp = new Properties();
private static Properties resourcemapProperties;
private String datasourceName;
private String defaultConfigFile;
private String userName;
private String keyTabFile;
private String password;
private String lookupPrincipal;
private String lookupKeytab;
private String nameRules;
private String authType;
private String hiveSiteFilePath;
private boolean isKerberosAuth;
private boolean enableHiveMetastoreLookup;
private Map<String,String> connectionProperties;
private static Set<String> rangerInternalPropertyKeys = new HashSet<>();
public static HadoopConfigHolder getInstance(String aDatasourceName) {
HadoopConfigHolder ret = dataSource2HadoopConfigHolder.get(aDatasourceName);
if (ret == null) {
synchronized (HadoopConfigHolder.class) {
HadoopConfigHolder temp = ret;
if (temp == null) {
ret = new HadoopConfigHolder(aDatasourceName);
dataSource2HadoopConfigHolder.put(aDatasourceName, ret);
}
}
}
return ret;
}
public static HadoopConfigHolder getInstance(String aDatasourceName, Map<String,String> connectionProperties,
String defaultConfigFile) {
HadoopConfigHolder ret = dataSource2HadoopConfigHolder.get(aDatasourceName);
if (ret == null) {
synchronized (HadoopConfigHolder.class) {
HadoopConfigHolder temp = ret;
if (temp == null) {
ret = new HadoopConfigHolder(aDatasourceName,connectionProperties, defaultConfigFile);
dataSource2HadoopConfigHolder.put(aDatasourceName, ret);
}
}
}
else {
if (connectionProperties !=null && !connectionProperties.equals(ret.connectionProperties)) {
ret = new HadoopConfigHolder(aDatasourceName,connectionProperties);
dataSource2HadoopConfigHolder.remove(aDatasourceName);
dataSource2HadoopConfigHolder.put(aDatasourceName, ret);
}
}
return ret;
}
private HadoopConfigHolder(String aDatasourceName) {
datasourceName = aDatasourceName;
if (!initialized) {
init();
}
initLoginInfo();
}
private HadoopConfigHolder(String aDatasourceName,
Map<String, String> connectionProperties) {
this(aDatasourceName, connectionProperties, null);
}
private HadoopConfigHolder(String aDatasourceName, Map<String,String> connectionProperties,
String defaultConfigFile) {
datasourceName = aDatasourceName;
this.connectionProperties = connectionProperties;
this.defaultConfigFile = defaultConfigFile;
initConnectionProp();
initLoginInfo();
}
private void initConnectionProp() {
if (!connectionProperties.containsKey(ENABLE_HIVE_METASTORE_LOOKUP)) {
connectionProperties.put(ENABLE_HIVE_METASTORE_LOOKUP, "false");
}
if (!connectionProperties.containsKey(HIVE_SITE_FILE_PATH)) {
connectionProperties.put(HIVE_SITE_FILE_PATH, "");
}
for (Map.Entry<String, String> entry : connectionProperties.entrySet()) {
String key = entry.getKey();
String resourceName = getResourceName(key);
if (resourceName == null) {
resourceName = RANGER_SECTION_NAME;
}
String val = entry.getValue();
addConfiguration(datasourceName, resourceName, key, val );
}
}
private String getResourceName(String key) {
if (resourcemapProperties == null) {
initResourceMap();
}
if (resourcemapProperties != null) {
String rn = resourcemapProperties.getProperty(key);
return ( rn != null) ? rn : defaultConfigFile;
} else {
return defaultConfigFile;
}
}
private static void initResourceMap() {
Properties props = new Properties();
InputStream in = HadoopConfigHolder.class.getClassLoader().getResourceAsStream(RESOURCEMAP_PROP_FILE);
if (in != null) {
try {
props.load(in);
for (Map.Entry<Object, Object> entry : props
.entrySet()) {
String value = (String) entry.getValue();
if (RANGER_SECTION_NAME.equals(value)) {
String key = (String) entry.getKey();
rangerInternalPropertyKeys.add(key);
}
}
resourcemapProperties = props;
} catch (IOException e) {
throw new HadoopException("Unable to load resource map properties from [" + RESOURCEMAP_PROP_FILE + "]", e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException ioe) {
// Ignore IOException during close of stream
}
}
}
} else {
throw new HadoopException("Unable to locate resource map properties from [" + RESOURCEMAP_PROP_FILE + "] in the class path.");
}
}
private static synchronized void init() {
if (initialized) {
return;
}
try {
InputStream in = HadoopConfigHolder.class.getClassLoader().getResourceAsStream(DEFAULT_DATASOURCE_PARAM_PROP_FILE);
if (in != null) {
Properties prop = new Properties();
try {
prop.load(in);
} catch (IOException e) {
throw new HadoopException("Unable to get configuration information for Hadoop environments", e);
}
finally {
try {
in.close();
} catch (IOException e) {
// Ignored exception when the stream is closed.
}
}
if (prop.isEmpty()) {
return;
}
for (Object keyobj : prop.keySet()) {
String key = (String)keyobj;
String val = prop.getProperty(key);
int dotLocatedAt = key.indexOf(".");
if (dotLocatedAt == -1) {
continue;
}
String dataSource = key.substring(0,dotLocatedAt);
String propKey = key.substring(dotLocatedAt+1);
int resourceFoundAt = propKey.indexOf(".");
if (resourceFoundAt > -1) {
String resourceName = propKey.substring(0, resourceFoundAt) + ".xml";
propKey = propKey.substring(resourceFoundAt+1);
addConfiguration(dataSource, resourceName, propKey, val);
}
}
}
in = HadoopConfigHolder.class.getClassLoader().getResourceAsStream(GLOBAL_LOGIN_PARAM_PROP_FILE);
if (in != null) {
Properties tempLoginProp = new Properties();
try {
tempLoginProp.load(in);
} catch (IOException e) {
throw new HadoopException("Unable to get login configuration information for Hadoop environments from file: [" + GLOBAL_LOGIN_PARAM_PROP_FILE + "]", e);
}
finally {
try {
in.close();
} catch (IOException e) {
// Ignored exception when the stream is closed.
}
}
globalLoginProp = tempLoginProp;
}
}
finally {
initialized = true;
}
}
private void initLoginInfo() {
Properties prop = this.getRangerSection();
if (prop != null) {
userName = prop.getProperty(RANGER_LOGIN_USER_NAME_PROP);
keyTabFile = prop.getProperty(RANGER_LOGIN_KEYTAB_FILE_PROP);
if (StringUtils.trimToNull(prop.getProperty(ENABLE_HIVE_METASTORE_LOOKUP)) != null) {
try {
enableHiveMetastoreLookup = Boolean.valueOf(prop.getProperty(ENABLE_HIVE_METASTORE_LOOKUP,"false").trim());
} catch (Exception e) {
enableHiveMetastoreLookup = false;
LOG.error("Error while getting " + ENABLE_HIVE_METASTORE_LOOKUP + " : " + e.getMessage());
}
}
if (StringUtils.trimToNull(prop.getProperty(HIVE_SITE_FILE_PATH)) != null) {
hiveSiteFilePath = prop.getProperty(HIVE_SITE_FILE_PATH).trim();
} else {
hiveSiteFilePath = null;
}
password = prop.getProperty(RANGER_LOGIN_PASSWORD);
lookupPrincipal = prop.getProperty(RANGER_LOOKUP_PRINCIPAL);
lookupKeytab = prop.getProperty(RANGER_LOOKUP_KEYTAB);
nameRules = prop.getProperty(RANGER_NAME_RULES);
authType = prop.getProperty(RANGER_AUTH_TYPE, "simple");
String hadoopSecurityAuthentication = getHadoopSecurityAuthentication();
if (hadoopSecurityAuthentication != null) {
isKerberosAuth = HADOOP_SECURITY_AUTHENTICATION_METHOD.equalsIgnoreCase(hadoopSecurityAuthentication);
} else {
isKerberosAuth = (userName != null && userName.indexOf("@") > -1) || SecureClientLogin.isKerberosCredentialExists(lookupPrincipal, lookupKeytab);
}
}
}
public Properties getRangerSection() {
Properties prop = this.getProperties(RANGER_SECTION_NAME);
if (prop == null) {
prop = globalLoginProp;
}
return prop;
}
private static void addConfiguration(String dataSource, String resourceName, String propertyName, String value) {
if (dataSource == null || dataSource.isEmpty()) {
return;
}
if (propertyName == null || propertyName.isEmpty()) {
return;
}
if (resourceName == null) {
resourceName = DEFAULT_RESOURCE_NAME;
}
HashMap<String,Properties> resourceName2PropertiesMap = dataSource2ResourceListMap.get(dataSource);
if (resourceName2PropertiesMap == null) {
resourceName2PropertiesMap = new HashMap<>();
dataSource2ResourceListMap.put(dataSource, resourceName2PropertiesMap);
}
Properties prop = resourceName2PropertiesMap.get(resourceName);
if (prop == null) {
prop = new Properties();
resourceName2PropertiesMap.put(resourceName, prop);
}
if (value == null) {
prop.remove(propertyName);
} else {
prop.put(propertyName, value);
}
}
public String getDatasourceName() {
return datasourceName;
}
public boolean hasResourceExists(String aResourceName) { // dilli
HashMap<String,Properties> resourceName2PropertiesMap = dataSource2ResourceListMap.get(datasourceName);
return (resourceName2PropertiesMap != null && resourceName2PropertiesMap.containsKey(aResourceName));
}
public Properties getProperties(String aResourceName) {
Properties ret = null;
HashMap<String,Properties> resourceName2PropertiesMap = dataSource2ResourceListMap.get(datasourceName);
if (resourceName2PropertiesMap != null) {
ret = resourceName2PropertiesMap.get(aResourceName);
}
return ret;
}
public String getHadoopSecurityAuthentication() {
String ret = null;
String sectionName = RANGER_SECTION_NAME;
if (defaultConfigFile != null) {
sectionName = defaultConfigFile;
}
if (LOG.isDebugEnabled()) {
LOG.debug("==> HadoopConfigHolder.getHadoopSecurityAuthentication( " + " DataSource : " + sectionName + " Property : " + HADOOP_SECURITY_AUTHENTICATION + ")" );
}
ret = getProperties(sectionName,HADOOP_SECURITY_AUTHENTICATION);
if (LOG.isDebugEnabled()) {
LOG.debug("<== HadoopConfigHolder.getHadoopSecurityAuthentication(" + " DataSource : " + sectionName + " Property : " + HADOOP_SECURITY_AUTHENTICATION + " Value : " + ret + ")" );
}
return ret;
}
public String getUserName() {
return userName;
}
public String getKeyTabFile() {
return keyTabFile;
}
public String getPassword() {
return password;
}
public boolean isKerberosAuthentication() {
return isKerberosAuth;
}
public String getLookupPrincipal() {
return lookupPrincipal;
}
public String getLookupKeytab() {
return lookupKeytab;
}
public String getNameRules() {
return nameRules;
}
public String getAuthType() {
return authType;
}
public boolean isEnableHiveMetastoreLookup() {
return enableHiveMetastoreLookup;
}
public String getHiveSiteFilePath() {
return hiveSiteFilePath;
}
public Set<String> getRangerInternalPropertyKeys() {
return rangerInternalPropertyKeys;
}
private String getProperties(String sectionName, String property) {
if (LOG.isDebugEnabled()) {
LOG.debug("==> HadoopConfigHolder.getProperties( " + " DataSource : " + sectionName + " Property : " + property + ")" );
}
Properties repoParam = null;
String ret = null;
HashMap<String,Properties> resourceName2PropertiesMap = dataSource2ResourceListMap.get(this.getDatasourceName());
if (resourceName2PropertiesMap != null) {
repoParam=resourceName2PropertiesMap.get(sectionName);
}
if (repoParam != null) {
ret = (String)repoParam.get(property);
}
if (LOG.isDebugEnabled()) {
LOG.debug("<== HadoopConfigHolder.getProperties( " + " DataSource : " + sectionName + " Property : " + property + " Value : " + ret);
}
return ret;
}
}
| 31.410901 | 184 | 0.724288 |
b7ade62794b1db510247fd9f1fe104bb88e8bfb7 | 916 | package org.fxmisc.richtext.model;
import javafx.beans.value.ObservableBooleanValue;
import org.fxmisc.undo.UndoManager;
import org.fxmisc.undo.UndoManagerFactory;
/**
* Undo/redo actions for {@link TextEditingArea}.
*/
public interface UndoActions {
/**
* Undo manager of this text area.
*/
UndoManager getUndoManager();
void setUndoManager(UndoManagerFactory undoManagerFactory);
default void undo() { getUndoManager().undo(); }
default void redo() { getUndoManager().redo(); }
default boolean isUndoAvailable() { return getUndoManager().isUndoAvailable(); }
default ObservableBooleanValue undoAvailableProperty() { return getUndoManager().undoAvailableProperty(); }
default boolean isRedoAvailable() { return getUndoManager().isRedoAvailable(); }
default ObservableBooleanValue redoAvailableProperty() { return getUndoManager().redoAvailableProperty(); }
}
| 31.586207 | 111 | 0.745633 |
addc3875b1cc759710c37b94b8cfdaf8a1ff7053 | 4,046 | /*
* Hydrogen Integration API
* The Hydrogen Integration API
*
* OpenAPI spec version: 1.2.1
* 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.hydrogen.integration.model;
import java.util.Objects;
import com.google.gson.annotations.SerializedName;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* BrokerageAccountCO
*/
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2020-06-11T07:03:53.789Z")
public class BrokerageAccountCO {
@SerializedName("electron_document_id")
private List<UUID> electronDocumentId = null;
@SerializedName("nucleus_account_id")
private UUID nucleusAccountId = null;
@SerializedName("nucleus_account_type_id")
private UUID nucleusAccountTypeId = null;
public BrokerageAccountCO electronDocumentId(List<UUID> electronDocumentId) {
this.electronDocumentId = electronDocumentId;
return this;
}
public BrokerageAccountCO addElectronDocumentIdItem(UUID electronDocumentIdItem) {
if (this.electronDocumentId == null) {
this.electronDocumentId = new ArrayList<UUID>();
}
this.electronDocumentId.add(electronDocumentIdItem);
return this;
}
/**
* Get electronDocumentId
* @return electronDocumentId
**/
@ApiModelProperty(value = "")
public List<UUID> getElectronDocumentId() {
return electronDocumentId;
}
public void setElectronDocumentId(List<UUID> electronDocumentId) {
this.electronDocumentId = electronDocumentId;
}
public BrokerageAccountCO nucleusAccountId(UUID nucleusAccountId) {
this.nucleusAccountId = nucleusAccountId;
return this;
}
/**
* Get nucleusAccountId
* @return nucleusAccountId
**/
@ApiModelProperty(value = "")
public UUID getNucleusAccountId() {
return nucleusAccountId;
}
public void setNucleusAccountId(UUID nucleusAccountId) {
this.nucleusAccountId = nucleusAccountId;
}
public BrokerageAccountCO nucleusAccountTypeId(UUID nucleusAccountTypeId) {
this.nucleusAccountTypeId = nucleusAccountTypeId;
return this;
}
/**
* Get nucleusAccountTypeId
* @return nucleusAccountTypeId
**/
@ApiModelProperty(value = "")
public UUID getNucleusAccountTypeId() {
return nucleusAccountTypeId;
}
public void setNucleusAccountTypeId(UUID nucleusAccountTypeId) {
this.nucleusAccountTypeId = nucleusAccountTypeId;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
BrokerageAccountCO brokerageAccountCO = (BrokerageAccountCO) o;
return Objects.equals(this.electronDocumentId, brokerageAccountCO.electronDocumentId) &&
Objects.equals(this.nucleusAccountId, brokerageAccountCO.nucleusAccountId) &&
Objects.equals(this.nucleusAccountTypeId, brokerageAccountCO.nucleusAccountTypeId);
}
@Override
public int hashCode() {
return Objects.hash(electronDocumentId, nucleusAccountId, nucleusAccountTypeId);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class BrokerageAccountCO {\n");
sb.append(" electronDocumentId: ").append(toIndentedString(electronDocumentId)).append("\n");
sb.append(" nucleusAccountId: ").append(toIndentedString(nucleusAccountId)).append("\n");
sb.append(" nucleusAccountTypeId: ").append(toIndentedString(nucleusAccountTypeId)).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 ");
}
}
| 27.52381 | 120 | 0.722689 |
0c7f2773d9dad32c1a0ce0e44c34dbd05604ce70 | 708 | import java.util.ArrayList;
import java.util.List;
public class Party extends Event{
private List<Event> eventList;
Party(String title, String date, String description) {
super(title, date, description);
this.eventList= new ArrayList<>();
}
public void addEvent(Event e){
List<Person> persons = e.getPersonList();
for(Person p : persons){
boolean foundPerson = false;
for(Person p1 : this.personList){
if(p.equals(p1)){
foundPerson = true;
break;
}
}
if(!foundPerson){
this.addPerson(p);
}
}
}
}
| 24.413793 | 58 | 0.515537 |
7fcaafedcd502dd1b2abe8384470af476e925aa7 | 5,458 | /*
* Copyright 1&1 Internet AG, https://github.com/1and1/
*
* 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 net.oneandone.incubator.neo.collect;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
/**
* Immutable utility class
*/
public class Immutables {
/**
* merges a new entry into a set
*
* @param set the set
* @param entryToAdd the entry to add
* @return the new merged immutable set
*/
public static <T> ImmutableSet<T> join(ImmutableSet<T> set, T entryToAdd) {
return ImmutableSet.<T>builder().addAll(set).add(entryToAdd).build();
}
/**
* merges 2 sets
*
* @param set1 the set1 to merge
* @param set2 the set2 to merge
* @return the new merged immutable set
*/
public static <T> ImmutableSet<T> join(ImmutableSet<T> set1, ImmutableSet<T> set2) {
return ImmutableSet.<T>builder().addAll(set1).addAll(set2).build();
}
/**
* merges a new entry into a list
*
* @param list the list to merge
* @param entryToAdd the entry to add
* @return the new merged immutable list
*/
public static <T> ImmutableList<T> join(ImmutableList<T> list, T entryToAdd) {
return ImmutableList.<T>builder().addAll(list).add(entryToAdd).build();
}
/**
* merges a new entry into a list
*
* @param entryToAdd the entry to add
* @param list the list to merge
* @return the new merged immutable list
*/
public static <T> ImmutableList<T> join(T entryToAdd, ImmutableList<T> list) {
return ImmutableList.<T>builder().add(entryToAdd).addAll(list).build();
}
/**
* merges 2 lists
*
* @param list1 the list1 to merge
* @param list2 the list2 to merge
* @return the new merged immutable list
*/
public static <T> ImmutableList<T> join(ImmutableList<T> list1, ImmutableList<T> list2) {
return ImmutableList.<T>builder().addAll(list1).addAll(list2).build();
}
/**
* merges a new entry into a map
*
* @param map the map to merge
* @param key the key of the new entry
* @param value the value of the new entry
* @return the new merged immutable map
*/
public static <K, V> ImmutableMap<K, V> join(ImmutableMap<K, V> map, K key, V value) {
Map<K, V> m = Maps.newHashMap(map);
m.put(key, value);
return ImmutableMap.copyOf(m);
}
/**
* merges 2 maps
*
* @param map1 the map1 to merge
* @param map2 the map2 to merge
* @return the new merged immutable map
*/
public static <K, V> ImmutableMap<K, V> join(ImmutableMap<K, V> map1, ImmutableMap<K, V> map2) {
return ImmutableMap.<K, V>builder().putAll(map1).putAll(map2).build();
}
public static <T> Collector<T, ?, ImmutableList<T>> toList() {
Supplier<ImmutableList.Builder<T>> supplier = ImmutableList.Builder::new;
BiConsumer<ImmutableList.Builder<T>, T> accumulator = (b, v) -> b.add(v);
BinaryOperator<ImmutableList.Builder<T>> combiner = (l, r) -> l.addAll(r.build());
Function<ImmutableList.Builder<T>, ImmutableList<T>> finisher = ImmutableList.Builder::build;
return Collector.of(supplier, accumulator, combiner, finisher);
}
public static <T> Collector<T, ?, ImmutableSet<T>> toSet() {
Supplier<ImmutableSet.Builder<T>> supplier = ImmutableSet.Builder::new;
BiConsumer<ImmutableSet.Builder<T>, T> accumulator = (b, v) -> b.add(v);
BinaryOperator<ImmutableSet.Builder<T>> combiner = (l, r) -> l.addAll(r.build());
Function<ImmutableSet.Builder<T>, ImmutableSet<T>> finisher = ImmutableSet.Builder::build;
return Collector.of(supplier, accumulator, combiner, finisher);
}
public static <T, K, V> Collector<T, ?, ImmutableMap<K, V>> toMap(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends V> valueMapper) {
Supplier<ImmutableMap.Builder<K, V>> supplier = ImmutableMap.Builder::new;
BiConsumer<ImmutableMap.Builder<K, V>, T> accumulator = (b, t) -> b.put(keyMapper.apply(t), valueMapper.apply(t));
BinaryOperator<ImmutableMap.Builder<K, V>> combiner = (l, r) -> l.putAll(r.build());
Function<ImmutableMap.Builder<K, V>, ImmutableMap<K, V>> finisher = ImmutableMap.Builder::build;
return Collector.of(supplier, accumulator, combiner, finisher);
}
} | 35.212903 | 122 | 0.639062 |
908c06e804f8a8f81f01dec4ce9b3ee92f5549bf | 222 | package com.example.paging.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.paging.entity.Commit;
public interface CommitRepository extends JpaRepository<Commit, Integer> {
}
| 24.666667 | 74 | 0.833333 |
7e9a5c410c8729169b6bc9f28ee4b184b508ed02 | 1,947 | package com.gl.jxt.service.impl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.gl.jxt.common.dto.ResultModel;
import com.gl.jxt.dao.ICategoryDao;
import com.gl.jxt.dao.IDepartmentDao;
import com.gl.jxt.dao.IMemberDao;
import com.gl.jxt.domain.Department;
import com.gl.jxt.service.IDepartmentService;
import javax.annotation.Resource;
import java.util.List;
@Service("departmentService")
public class DepartmentServiceImpl implements IDepartmentService {
@Resource
IDepartmentDao departmentDao;
@Resource
IMemberDao memberDao;
@Resource
ICategoryDao categoryDao;
@Override
@Transactional
public ResultModel save (Department department) {
if(departmentDao.findByName(department.getName()) != null){
return new ResultModel(-1,"系别以存在");
}
if(departmentDao.save(department) == 1){
return new ResultModel(1,"保存成功");
}
return new ResultModel(-1,"保存失败");
}
@Override
public ResultModel update (Department department) {
return null;
}
@Override
@Transactional
public ResultModel delete (int id) {
if(departmentDao.findById(id) == null){
return new ResultModel(-1,"系别不存在");
}
memberDao.changeDepartment(null,id);
categoryDao.changeDepartment(null,id);
if(departmentDao.delete(id) == 1){
return new ResultModel(1,"删除成功");
}
return new ResultModel(-1,"删除失败");
}
@Override
public Department findByid (int id) {
return departmentDao.findById(id);
}
@Override
public ResultModel departmentList () {
List<Department> departments = departmentDao.departmentList();
ResultModel<List<Department>> result = new ResultModel<List<Department>>(0);
result.setData(departments);
return result;
}
}
| 26.671233 | 84 | 0.672316 |
c5637a9586f494395bcafd32fd3863890cd514b4 | 2,869 | package jp.ac.kyushu_u.csce.modeltool.dictionary.dict.handler;
import java.io.File;
import java.text.MessageFormat;
import jp.ac.kyushu_u.csce.modeltool.dictionary.Messages;
import jp.ac.kyushu_u.csce.modeltool.dictionary.constant.DictionaryConstants;
import jp.ac.kyushu_u.csce.modeltool.dictionary.dict.DictionaryView;
import jp.ac.kyushu_u.csce.modeltool.dictionary.dict.TableTab;
import org.apache.commons.lang.StringUtils;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.handlers.HandlerUtil;
/**
* 辞書ファイル(JSON)のエクスポートを行うハンドラクラス
*
* @author KBK yoshimura
*/
public class ExportHandler extends AbstractHandler implements IHandler {
/** ファイル名(ワイルドカード) */
private static final String WILD_CARD = "*."; //$NON-NLS-1$
/**
* ファイルダイアログで最後に選択した拡張子のインデックス
*/
private int lastIndex = 0;
/**
* execute
* @see org.eclipse.core.commands.IHandler#execute(ExecutionEvent)
*/
public Object execute(ExecutionEvent event) throws ExecutionException {
IWorkbenchPage page = HandlerUtil.getActiveWorkbenchWindow(event).getActivePage();
// 辞書ビューの取得(開いていない場合処理なし)
DictionaryView view = (DictionaryView)page.findView(DictionaryConstants.PART_ID_DICTIONARY);
if (view == null) {
return null;
}
// アクティブなタブがなければ何もしない
TableTab tab = view.getActiveTableTab(false);
if (tab == null) {
return null;
}
// ファイルダイアログ
FileDialog dialog = new FileDialog(page.getWorkbenchWindow().getShell(), SWT.SAVE);
String[] extensions = new String[]{
WILD_CARD + DictionaryConstants.EXTENSION_JSON.toLowerCase(),
WILD_CARD + DictionaryConstants.EXTENSION_CSV.toLowerCase()};
dialog.setFilterExtensions(extensions);
dialog.setFilterIndex(lastIndex);
dialog.setFileName(tab.getDictionaryName());
dialog.setText(Messages.ExportHandler_3);
String fileNm = dialog.open();
if (StringUtils.isBlank(fileNm)) {
return null;
}
// 選択された拡張子のインデックスを退避
// 次回表示時に前回の拡張子を初期選択するため
lastIndex = dialog.getFilterIndex();
File file = new File(fileNm);
if (file.exists()) {
boolean overwrite = MessageDialog.openQuestion(
view.getSite().getShell(),
Messages.ExportHandler_0,
MessageFormat.format(Messages.ExportHandler_1, new Object[]{file.getName()}));
if (!overwrite) return null;
}
// 処理が完了した場合、メッセージを表示
if(view.exportDictionary(file, tab)) {
MessageDialog.openInformation(view.getSite().getShell(), Messages.ExportHandler_0, Messages.ExportHandler_2);
};
return null;
}
}
| 30.849462 | 113 | 0.735448 |
3e6364a9c5347147dbf56f764da3b433373f6094 | 1,342 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package lightsearch.server.timer;
import lightsearch.server.log.LoggerServer;
import lightsearch.server.thread.ThreadManager;
import lightsearch.server.time.CurrentDateTime;
/**
* Таймер сборщика мусора.
* <p>
* <b>Этот класс экспериментальный и не следует его использовать в релизе. Применяйте его для тестов и экспериментов.</b>
* <p>
* Вы
* @author ViiSE
*/
public class GarbageCollectorAbstractDefaultExt extends SuperGarbageCollectorTimer {
private final String ID;
public GarbageCollectorAbstractDefaultExt(LoggerServer loggerServer,
CurrentDateTime currentDateTime, ThreadManager threadManager, TimersIDEnum id) {
super(loggerServer, currentDateTime, threadManager, id);
ID = super.id().stringValue();
}
@Override
public void run() {
while(super.threadManager().holder().getThread(ID).isWorked()) {
while(true) {
try { Thread.sleep(1000); } catch(InterruptedException ignored) {}
System.gc();
}
}
super.threadManager().holder().getThread(ID).setIsDone(true);
}
}
| 31.952381 | 126 | 0.672131 |
0863a0a908aa8c80ef0e516c70947722fbaeb364 | 2,230 | package com.github.basking2.sdsai.net;
import org.junit.Test;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
/**
*/
public class TcpPoolTest {
@Test
public void testSend() throws Exception {
final List<ByteBuffer> msgs = new ArrayList<>();
String addr1 = "tcp://localhost:9865";
TcpPool pool1 = new TcpPool(addr1, new TcpPool.DefaultIdTranslator(), id -> new ReceiveToBuffer(msgs));
String addr2 = "tcp://localhost:9866";
TcpPool pool2 = new TcpPool(addr2, new TcpPool.DefaultIdTranslator(), id -> new ReceiveToBuffer(msgs));
TcpPool.UserKeyAttachment a = pool1.connect(addr2);
String text = "Hullo, world.";
a.write(ByteBuffer.allocate(4).putInt(0, text.getBytes().length));
a.write(ByteBuffer.wrap(text.getBytes()));
pool1.runOnceNow();
pool2.runOnceNow();
// Ownership changes.
pool1.runOnceNow();
pool2.runOnceNow();
pool1.runOnceNow();
pool2.runOnceNow();
pool1.close();
pool2.close();
assertEquals(text, new String(msgs.get(0).array()));
}
public static class ReceiveToBuffer implements TcpPool.DataHandler {
private ByteBuffer header;
private ByteBuffer body;
private List<ByteBuffer> msgs;
public ReceiveToBuffer(final List<ByteBuffer> msgs) {
this.msgs = msgs;
this.header = ByteBuffer.allocate(4);
this.body = null;
}
@Override
public void handleOpen(String id) throws IOException {
}
@Override
public void handleData(String id, SocketChannel chan) throws IOException {
chan.read(header);
if (header.position() == header.limit()) {
if (body == null) {
body = ByteBuffer.allocate(header.getInt(0));
msgs.add(body);
}
chan.read(body);
}
}
@Override
public void handleClose(String id) throws IOException {
}
};
}
| 27.195122 | 111 | 0.599552 |
08c8c3686fd7b655cb9aca0a92e61c4752447a9d | 6,672 | package gg.projecteden.nexus.features.events.y2020.halloween20;
import gg.projecteden.nexus.features.events.y2020.halloween20.models.ComboLockNumber;
import gg.projecteden.nexus.features.events.y2020.halloween20.models.Pumpkin;
import gg.projecteden.nexus.features.events.y2020.halloween20.models.QuestStage;
import gg.projecteden.nexus.features.events.y2020.halloween20.models.QuestStage.Combination;
import gg.projecteden.nexus.features.events.y2020.halloween20.models.SoundButton;
import gg.projecteden.nexus.features.events.y2020.halloween20.quest.Gate;
import gg.projecteden.nexus.features.events.y2020.halloween20.quest.menus.Halloween20Menus;
import gg.projecteden.nexus.framework.commands.models.CustomCommand;
import gg.projecteden.nexus.framework.commands.models.annotations.Aliases;
import gg.projecteden.nexus.framework.commands.models.annotations.Arg;
import gg.projecteden.nexus.framework.commands.models.annotations.Path;
import gg.projecteden.nexus.framework.commands.models.annotations.Permission;
import gg.projecteden.nexus.framework.commands.models.events.CommandEvent;
import gg.projecteden.nexus.models.halloween20.Halloween20Service;
import gg.projecteden.nexus.models.halloween20.Halloween20User;
import org.bukkit.OfflinePlayer;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Aliases("h20")
public class Halloween20Command extends CustomCommand {
public Halloween20Command(CommandEvent event) {
super(event);
}
@Path
void tp() {
player().resetPlayerTime();
Halloween20User user = new Halloween20Service().get(player());
if (user.getCombinationStage() == QuestStage.Combination.NOT_STARTED)
Halloween20.start(player());
else
new Gate(player()).teleportIn();
}
@Path("progress [player]")
void progress(@Arg("self") OfflinePlayer player) {
Halloween20Service service = new Halloween20Service();
Halloween20User user = service.get(player);
send(PREFIX + "Progress:");
if (user.getCombinationStage() == QuestStage.Combination.NOT_STARTED)
send("&3Combination numbers: &cNot started");
else if (user.getCombinationStage() == QuestStage.Combination.STARTED)
send("&3Combination numbers: &e" + user.getFoundComboLockNumbers().size() + "/" + ComboLockNumber.values().length);
else if (user.getCombinationStage() == QuestStage.Combination.COMPLETE)
send("&3Combination numbers: &aComplete");
if (user.getLostPumpkinsStage() == QuestStage.LostPumpkins.NOT_STARTED)
send("&3Pumpkins: &cNot started (Talk to Jeffery)");
else if (user.getLostPumpkinsStage() == QuestStage.LostPumpkins.STARTED)
send("&3Pumpkins: &e" + user.getFoundPumpkins().size() + "/" + Pumpkin.values().length);
else if (user.getLostPumpkinsStage() == QuestStage.LostPumpkins.FOUND_ALL)
send("&3Pumpkins: &eFound all (Talk to Jeffery)");
else if (user.getLostPumpkinsStage() == QuestStage.LostPumpkins.COMPLETE)
send("&3Pumpkins: &aComplete");
if (user.getFoundButtons().size() == SoundButton.values().length)
send("&3Spooky Buttons: &aComplete");
else
send("&3Spooky Buttons: &e" + user.getFoundButtons().size() + "/" + SoundButton.values().length);
}
@Path("stats")
@Permission("group.admin")
void stats(@Arg("self") OfflinePlayer player) {
Halloween20Service service = new Halloween20Service();
List<Halloween20User> users = service.getAll();
int foundButtons = 0;
int foundButtonsComplete = 0;
int foundPumpkins = 0;
int foundPumpkinsComplete = 0;
int foundComboNumbers = 0;
int foundComboNumbersComplete = 0;
long totalUsers = users.stream().filter(user ->
user.getFoundButtons().size() > 0 || user.getFoundPumpkins().size() > 0 || user.getFoundComboLockNumbers().size() > 0
).count();
for (Halloween20User user : users) {
foundButtons += user.getFoundButtons().size();
if (user.getFoundButtons().size() == SoundButton.values().length)
++foundButtonsComplete;
foundPumpkins += user.getFoundPumpkins().size();
if (user.getFoundPumpkins().size() == Pumpkin.values().length)
++foundPumpkinsComplete;
foundComboNumbers += user.getFoundComboLockNumbers().size();
if (user.getCombinationStage() == Combination.COMPLETE)
++foundComboNumbersComplete;
}
send("Total users: " + totalUsers);
send("Found Buttons: " + (foundButtons / totalUsers) + " avg, " + foundButtonsComplete + " complete");
send("Found Pumpkins: " + (foundPumpkins / totalUsers) + " avg, " + foundPumpkinsComplete + " complete");
send("Found Combo Numbers: " + (foundComboNumbers / totalUsers) + " avg, " + foundComboNumbersComplete + " complete");
}
@Path("reset [player]")
@Permission("group.admin")
void reset(@Arg("self") OfflinePlayer player) {
Halloween20Service service = new Halloween20Service();
Halloween20User user = service.get(player);
user.setLostPumpkinsStage(QuestStage.LostPumpkins.NOT_STARTED);
user.setFoundPumpkins(new ArrayList<>());
user.setCombinationStage(QuestStage.Combination.NOT_STARTED);
user.setFoundComboLockNumbers(new ArrayList<>());
service.save(user);
}
@Path("tp pumpkin original <number>")
@Permission("group.admin")
void teleportPumpkinOriginal(Pumpkin pumpkin) {
player().teleportAsync(pumpkin.getOriginal(), TeleportCause.COMMAND);
}
@Path("tp pumpkin end <number>")
@Permission("group.admin")
void teleportPumpkinEnd(Pumpkin pumpkin) {
player().teleportAsync(pumpkin.getEnd(), TeleportCause.COMMAND);
}
@Path("tp comboLockNumber <number>")
@Permission("group.admin")
void teleportComboLockNumber(ComboLockNumber number) {
player().teleportAsync(number.getLoc(), TeleportCause.COMMAND);
}
@Path("tp button <number>")
@Permission("group.admin")
void teleportButton(SoundButton number) {
player().teleportAsync(number.getLocation(), TeleportCause.COMMAND);
}
@Path("picture")
@Permission("group.admin")
void picture() {
Halloween20Menus.openPicturePuzzle(player(), null);
}
@Path("flashCard")
@Permission("group.admin")
void flash() {
Halloween20Menus.openFlashCardPuzzle(player(), null);
}
@Path("gate open")
@Permission("group.admin")
void openGate() {
new Gate(player()).open();
}
@Path("gate close")
@Permission("group.admin")
void closeGate() {
new Gate(player()).close();
}
@Path("test combo")
@Permission("group.admin")
void testCombo() {
Halloween20Service service = new Halloween20Service();
Halloween20User user = service.get(player());
user.getFoundComboLockNumbers().clear();
user.getFoundComboLockNumbers().addAll(Arrays.asList(ComboLockNumber.values()));
service.save(user);
Halloween20Menus.openComboLock(player());
}
}
| 36.861878 | 121 | 0.747302 |
d361f23f96f9a7c607227c5a939149b81d691d03 | 749 | package io.github.helvalius.fortune.client;
import io.github.helvalius.fortune.teller.IFortuneService;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient("randomservice")
public interface FeignFortune extends IFortuneService {
@RequestMapping(path = "/seed", method = RequestMethod.GET)
int seed();
@RequestMapping(path = "/subtractor", method = RequestMethod.POST, consumes = "application/json")
int subtractor(@RequestParam(value = "minuend") Integer minuend, @RequestParam(value = "subtrahend") Integer subtrahend);
}
| 41.611111 | 125 | 0.794393 |
7abf52f83138d83786d337d6a43a4e08f2c0304f | 4,534 | package com.ntk.ehcrawler.adapters;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.ntk.R;
import com.ntk.ehcrawler.EHConstants;
import com.ntk.ehcrawler.activities.FullscreenActivity;
import com.ntk.ehcrawler.model.BookConstants;
import com.ntk.ehcrawler.model.PageConstants;
import com.ntk.ehcrawler.services.DatabaseService;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
public class ThumbAdapter extends CursorRecyclerViewAdapter{
private static final String LOG_TAG = "LOG_" + ThumbAdapter.class.getName();
private final Context mContext;
private final int mSize;
public ThumbAdapter(Context context, int size) {
super(context, null);
this.mContext = context;
this.mSize = size;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, Cursor cursor) {
final int position = cursor.getPosition();
final int count = cursor.getCount();
final String id = cursor.getString(0);
final String url = cursor.getString(PageConstants.BOOK_URL_INDEX);
final String thumbSrc = cursor.getString(PageConstants.THUMB_SRC_INDEX);
final String src = cursor.getString(PageConstants.SRC_INDEX);
if (position + 1 == count && count < mSize) {
int pageIndex = (position / EHConstants.PAGES_PER_PAGE) + 1;
DatabaseService.startGetBookDetail(mContext, id, url, pageIndex);
}
final View view = viewHolder.itemView;
final ImageView mThumb = (ImageView) view.findViewById(R.id.thumb_iv);
final ImageView mIcSave = (ImageView) view.findViewById(R.id.save_iv);
final View mLoading = view.findViewById(R.id.loading);
if (!TextUtils.isEmpty(src) && src.startsWith("file://")){
/* offline file available */
mIcSave.setVisibility(View.VISIBLE);
Picasso.with(mContext).load(src).into(mThumb);
mLoading.setVisibility(View.GONE);
Log.d(LOG_TAG, "load thumb offline "+src);
}else {
mIcSave.setVisibility(View.GONE);
Log.d(LOG_TAG, "load thumb online "+thumbSrc);
final int offset = cursor.getPosition() % 20;
Target target = new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
final int width = 100;
final int height = bitmap.getHeight();
final int x = width * offset;
final int y = 0;
if (x + width <= bitmap.getWidth()) {
Bitmap image = Bitmap.createBitmap(bitmap, x, y, width, height);
mThumb.setImageBitmap(image);
mLoading.setVisibility(View.GONE);
}
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
mThumb.setImageDrawable(errorDrawable);
mLoading.setVisibility(View.GONE);
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
mThumb.setImageDrawable(placeHolderDrawable);
}
};
//keep target reference with imageView
mThumb.setTag(target);
Picasso.with(mContext).load(thumbSrc).into(target);
}
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(mContext, FullscreenActivity.class);
intent.putExtra(BookConstants.URL, url);
intent.putExtra(BookConstants.FILE_COUNT, mSize);
intent.putExtra(EHConstants.POSITION, position);
mContext.startActivity(intent);
}
});
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.thumb_view, null);
return new RecyclerView.ViewHolder(view) {};
}
}
| 40.482143 | 88 | 0.631672 |
d8eb96808188b2f483d36f5fa4e0301206736aca | 354 | package org.infinispan.server.core.configuration;
import org.infinispan.commons.configuration.Builder;
/**
* ProtocolServerConfigurationChildBuilder.
*
* @author Tristan Tarrant
* @since 5.3
*/
public interface SslConfigurationChildBuilder extends Builder<SslEngineConfiguration> {
SslEngineConfigurationBuilder sniHostName(String domain);
}
| 22.125 | 87 | 0.80791 |
242086aa85ace5ee77111970bce2e8d760f24013 | 5,501 | /**
* Copyright (c) 2010, Sebastian Sdorra 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. Neither the name of SCM-Manager;
* nor the names of its 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 REGENTS 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.
*
* http://bitbucket.org/sdorra/scm-manager
*
*/
package sonia.scm.plugin;
//~--- non-JDK imports --------------------------------------------------------
import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.collect.Iterables;
import com.google.common.io.Files;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sonia.scm.lifecycle.classloading.ClassLoaderLifeCycle;
import sonia.scm.util.IOUtil;
//~--- JDK imports ------------------------------------------------------------
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Set;
/**
*
* @author Sebastian Sdorra
*/
public final class PluginsInternal
{
/**
* the logger for PluginsInternal
*/
private static final Logger logger =
LoggerFactory.getLogger(PluginsInternal.class);
//~--- constructors ---------------------------------------------------------
/**
* Constructs ...
*
*/
private PluginsInternal() {}
//~--- methods --------------------------------------------------------------
/**
* Method description
*
*
* @param classLoader
* @param directory
*
* @return
*
* @throws IOException
*/
public static Set<InstalledPlugin> collectPlugins(ClassLoaderLifeCycle classLoaderLifeCycle,
Path directory)
throws IOException
{
PluginProcessor processor = new PluginProcessor(classLoaderLifeCycle, directory);
return processor.collectPlugins(classLoaderLifeCycle.getBootstrapClassLoader());
}
/**
* Method description
*
*
* @param parent
* @param plugin
*
* @return
*/
public static File createPluginDirectory(File parent, InstalledPluginDescriptor plugin)
{
PluginInformation info = plugin.getInformation();
return new File(parent, info.getName());
}
/**
* Method description
*
*
* @param archive
* @param checksum
* @param directory
* @param checksumFile
* @param core
*
* @throws IOException
*/
public static void extract(SmpArchive archive, String checksum,
File directory, File checksumFile, boolean core)
throws IOException
{
if (directory.exists())
{
logger.debug("delete directory {} for plugin extraction",
archive.getPlugin().getInformation().getName(false));
IOUtil.delete(directory);
}
IOUtil.mkdirs(directory);
logger.debug("extract plugin {}",
archive.getPlugin().getInformation().getName(false));
archive.extract(directory);
Files.write(checksum, checksumFile, Charsets.UTF_8);
if (core)
{
if (!new File(directory, PluginConstants.FILE_CORE).createNewFile())
{
throw new IOException("could not create core plugin marker");
}
}
}
/**
* Method description
*
*
* @param wrapped
*
* @return
*/
public static Iterable<InstalledPluginDescriptor> unwrap(Iterable<InstalledPlugin> wrapped)
{
return Iterables.transform(wrapped, new Unwrap());
}
//~--- get methods ----------------------------------------------------------
/**
* Method description
*
*
* @param pluginDirectory
*
* @return
*/
public static File getChecksumFile(File pluginDirectory)
{
return new File(pluginDirectory, PluginConstants.FILE_CHECKSUM);
}
//~--- inner classes --------------------------------------------------------
/**
* Class description
*
*
* @version Enter version here..., 14/06/05
* @author Enter your name here...
*/
private static class Unwrap implements Function<InstalledPlugin, InstalledPluginDescriptor>
{
/**
* Method description
*
*
* @param wrapper
*
* @return
*/
@Override
public InstalledPluginDescriptor apply(InstalledPlugin wrapper)
{
return wrapper.getDescriptor();
}
}
}
| 26.320574 | 94 | 0.64261 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.