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
|
---|---|---|---|---|---|
fec5752d02ae957e74ae0bee2753d7856d3ffd7e | 3,582 | /*
* Copyright 2017 Apereo
*
* 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.tle.web.searching.itemlist;
import com.tle.beans.item.Item;
import com.tle.beans.item.attachments.IAttachment;
import com.tle.core.guice.Bind;
import com.tle.core.plugins.PluginTracker;
import com.tle.web.itemlist.item.ListSettings;
import com.tle.web.itemlist.item.StandardItemListEntry;
import com.tle.web.searching.VideoPreviewRenderer;
import com.tle.web.sections.equella.annotation.PlugKey;
import com.tle.web.sections.events.RenderContext;
import com.tle.web.sections.result.util.CountLabel;
import com.tle.web.sections.result.util.IconLabel;
import com.tle.web.sections.result.util.IconLabel.Icon;
import com.tle.web.sections.result.util.PluralKeyLabel;
import com.tle.web.sections.standard.model.HtmlLinkState;
import com.tle.web.sections.standard.renderers.DivRenderer;
import com.tle.web.sections.standard.renderers.LinkRenderer;
import java.util.List;
import javax.inject.Inject;
@SuppressWarnings("nls")
@Bind
public class ItemListVideoCountDisplaySection extends ItemListFileCountDisplaySection {
@Inject private PluginTracker<VideoPreviewRenderer> previewRenderers;
@PlugKey("videos.count")
private static String COUNT_KEY;
@Override
public ProcessEntryCallback<Item, StandardItemListEntry> processEntries(
final RenderContext context,
List<StandardItemListEntry> entries,
ListSettings<StandardItemListEntry> listSettings) {
final boolean countDisabled = isFileCountDisabled();
final List<VideoPreviewRenderer> renderers = previewRenderers.getBeanList();
return new ProcessEntryCallback<Item, StandardItemListEntry>() {
@Override
public void processEntry(StandardItemListEntry entry) {
if (!countDisabled) {
final boolean canViewRestricted = canViewRestricted(entry.getItem());
// Optimised?
final long count =
entry.getViewableResources().stream()
.filter(
vr -> {
final IAttachment attachment = vr.getAttachment();
if ((!canViewRestricted
&& (attachment != null && attachment.isRestricted()))) {
return false;
}
final String mimeType = vr.getMimeType();
for (VideoPreviewRenderer renderer : renderers) {
if (renderer.supports(mimeType)) {
return true;
}
}
return false;
})
.count();
if (count > 1) {
HtmlLinkState link =
new HtmlLinkState(new IconLabel(Icon.VIDEO, new CountLabel(count), false));
link.setDisabled(true);
link.setTitle(new PluralKeyLabel(COUNT_KEY, count));
entry.setThumbnailCount(new DivRenderer("filecount", new LinkRenderer(link)));
}
}
}
};
}
}
| 38.934783 | 91 | 0.661921 |
583ab3c3aa6b88462fb5b677d348af9bb8a7136c | 991 | package org.randomcoder.midi.mac.corefoundation;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import java.util.Arrays;
import java.util.List;
public class CFRange extends Structure {
public long loc;
public long len;
@Override protected List<String> getFieldOrder() {
return Arrays.asList("loc", "len");
}
public CFRange() {
}
public CFRange(Pointer pointer, int offset) {
super();
useMemory(pointer, offset);
read();
}
public CFRange(long loc, long len) {
super();
this.loc = loc;
this.len = len;
write();
}
public static class ByReference extends CFRange
implements Structure.ByReference {
public ByReference() {
}
public ByReference(CFRange struct) {
super(struct.getPointer(), 0);
}
}
public static class ByValue extends CFRange implements Structure.ByValue {
public ByValue() {
}
public ByValue(CFRange struct) {
super(struct.getPointer(), 0);
}
}
}
| 18.351852 | 76 | 0.65893 |
96d37ec39d575d9e8529b08e145dd9dc168416a1 | 7,293 | // Copyright 2014 theaigames.com ([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.
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
package frontLineBot;
import java.util.ArrayList;
import java.util.LinkedList;
import main.Region;
import move.AttackTransferMove;
import move.PlaceArmiesMove;
public class BotVars implements Bot
{
public int minAttackNum = 5;
public int attackNumDivisor = 2;
public int minTransNum = 1;
public int[] startingRegions = new int[6];
public BotVars() {}
public BotVars (int minAttackNum, int attackNumDivisor, int minTransNum, int[] startingRegions){
this.minAttackNum = minAttackNum;
this.attackNumDivisor = attackNumDivisor;
this.minTransNum = minTransNum;
this.startingRegions = startingRegions;
}
// @Override
// public void setParams(int minAttackNum, int attackNumDivisor, int minTransNum) {
// System.out.println(super.getClass());
// }
@Override
/**
* A method used at the start of the game to decide which player start with what Regions. 6 Regions are required to be returned.
* This example randomly picks 6 regions from the pickable starting Regions given by the engine.
* @return : a list of m (m=6) Regions starting with the most preferred Region and ending with the least preferred Region to start with
*/
public ArrayList<Region> getPreferredStartingRegions(BotState state, Long timeOut)
{
int m = startingRegions.length;
ArrayList<Region> preferredStartingRegions = new ArrayList<Region>();
for(int i=0; i<m; i++)
{
int regionId = startingRegions[i];
Region region = state.getFullMap().getRegion(regionId);
if(!preferredStartingRegions.contains(region))
preferredStartingRegions.add(region);
else
i--;
}
return preferredStartingRegions;
}
@Override
/**
* This method is called for at first part of each round. This example puts two armies on random regions
* until he has no more armies left to place.
* @return The list of PlaceArmiesMoves for one round
*/
public ArrayList<PlaceArmiesMove> getPlaceArmiesMoves(BotState state, Long timeOut)
{
// ArrayList<PlaceArmiesMove> placeArmiesMoves = new ArrayList<PlaceArmiesMove>();
// String myName = state.getMyPlayerName();
// int armies = 2;
// int armiesLeft = state.getStartingArmies();
// LinkedList<Region> visibleRegions = state.getVisibleMap().getRegions();
// while(armiesLeft > 0)
// {
// double rand = Math.random();
// int r = (int) (rand*visibleRegions.size());
// Region region = visibleRegions.get(r);
// if(region.ownedByPlayer(myName))
// {
// placeArmiesMoves.add(new PlaceArmiesMove(myName, region, armies));
// armiesLeft -= armies;
// }
// }
ArrayList<PlaceArmiesMove> placeArmiesMoves = new ArrayList<PlaceArmiesMove>();
String myName = state.getMyPlayerName();
// number of armies left
int numArmies = state.getStartingArmies();
// find all regions held by player that is bordering other regions
LinkedList<Region> visibleRegions = state.getVisibleMap().getRegions();
LinkedList<Region> borderingRegions = new LinkedList<Region>();
// current region being checked
Region current;
for(int i = 0; i < visibleRegions.size(); i++){
if(visibleRegions.get(i).ownedByPlayer(myName)){
current = visibleRegions.get(i);
if(isBorder(current, myName)){
borderingRegions.add(current);
}
}
}
int numToPlace = (int)Math.ceil((double)numArmies/borderingRegions.size());
int i = 0;
while(numArmies > 0 && borderingRegions.size() > 0){
placeArmiesMoves.add(new PlaceArmiesMove(myName, borderingRegions.get(i), numToPlace));
numArmies -= numToPlace;
i++;
}
return placeArmiesMoves;
}
private boolean isBorder(Region region, String myName){
LinkedList<Region> neighbors = region.getNeighbors();
int numNeighborsChecked = 0;
while(numNeighborsChecked < neighbors.size()){
if(!neighbors.get(numNeighborsChecked).ownedByPlayer(myName)){
// add it to list then exit while loop
return true;
}
numNeighborsChecked++;
}
return false;
}
@Override
/**
* This method is called for at the second part of each round. This example attacks if a region has
* more than 6 armies on it, and transfers if it has less than 6 and a neighboring owned region.
* @return The list of PlaceArmiesMoves for one round
*/
public ArrayList<AttackTransferMove> getAttackTransferMoves(Bot bot, BotState state, Long timeOut)
{
ArrayList<AttackTransferMove> attackTransferMoves = new ArrayList<AttackTransferMove>();
String myName = state.getMyPlayerName();
BotVars botVars = (BotVars)bot;
int minAttackNum = botVars.minAttackNum;
int attackNumDivisor = botVars.attackNumDivisor;
int minTransNum = botVars.minTransNum;
//int armies = 5;
for(Region fromRegion : state.getVisibleMap().getRegions())
{
if(fromRegion.ownedByPlayer(myName)) //do an attack
{
ArrayList<Region> possibleToRegions = new ArrayList<Region>();
possibleToRegions.addAll(fromRegion.getNeighbors());
while(!possibleToRegions.isEmpty())
{
double rand = Math.random();
int r = (int) (rand*possibleToRegions.size());
Region toRegion = possibleToRegions.get(r);
if(!toRegion.getPlayerName().equals(myName) && fromRegion.getArmies() > minAttackNum) //do an attack
{
attackTransferMoves.add(new AttackTransferMove(myName, fromRegion, toRegion, fromRegion.getArmies()/attackNumDivisor));
break;
}
else if(toRegion.getPlayerName().equals(myName) && isBorder(toRegion, myName) && fromRegion.getArmies() > minTransNum) //do a transfer
{
if(!isBorder(fromRegion, myName)){
attackTransferMoves.add(new AttackTransferMove(myName, fromRegion, toRegion, fromRegion.getArmies()-minTransNum));
}
break;
}
else
possibleToRegions.remove(toRegion);
}
}
}
return attackTransferMoves;
}
public static void main(String[] args)
{
int minAttackNum = Integer.parseInt(args[0]);
int attackNumDivisor = Integer.parseInt(args[1]);
int minTransNum = Integer.parseInt(args[2]);
int startingRegions[] = new int[6];
startingRegions[0] = Integer.parseInt(args[3]);
startingRegions[1] = Integer.parseInt(args[4]);
startingRegions[2] = Integer.parseInt(args[5]);
startingRegions[3] = Integer.parseInt(args[6]);
startingRegions[4] = Integer.parseInt(args[7]);
startingRegions[5] = Integer.parseInt(args[8]);
BotParser parser = new BotParser(new BotVars(minAttackNum, attackNumDivisor, minTransNum, startingRegions));
parser.run();
}
}
| 31.986842 | 139 | 0.71027 |
e1b9c36c4821fb5fa98de1758486c4c1a092af05 | 551 |
/**
* @Title: Test.java
* @Package com.winterchen.controller
* @Description: TODO(用一句话描述该文件做什么)
* @author hemin
* @date 2020年7月3日 下午2:41:58
* @version V1.0
*/
package com.winterchen.controller;
/**
* @ClassName: Test
* @Description: TODO(这里用一句话描述这个类的作用)
* @author hemin
* @date 2020年7月3日
*
*/
//1 到100 求和
public class Test {
public static void main(String[] args) {
int sum=0;
for( int i=0;i<=100;i++) {
sum +=i;
}
System.out.println(sum);
}
}
| 16.69697 | 41 | 0.548094 |
cdae9d58ab64863359affc43b7a6e3e64d6bea42 | 4,723 | import net.runelite.mapping.Export;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;
@ObfuscatedName("b")
final class class2 implements class0 {
@ObfuscatedName("es")
@ObfuscatedSignature(
signature = "Leq;"
)
@Export("urlRequester")
static UrlRequester urlRequester;
@ObfuscatedName("fe")
@ObfuscatedSignature(
signature = "[Llh;"
)
@Export("mapscene")
static IndexedSprite[] mapscene;
@ObfuscatedName("r")
@ObfuscatedSignature(
signature = "(IIIIIZI)Llv;",
garbageValue = "-1348595498"
)
@Export("createSprite")
public static final SpritePixels createSprite(int var0, int var1, int var2, int var3, int var4, boolean var5) {
if(var1 == -1) {
var4 = 0;
} else if(var4 == 2 && var1 != 1) {
var4 = 1;
}
long var6 = ((long)var3 << 42) + (long)var0 + ((long)var1 << 16) + ((long)var2 << 38) + ((long)var4 << 40);
SpritePixels var8;
if(!var5) {
var8 = (SpritePixels)ItemComposition.itemSpriteCache.get(var6);
if(var8 != null) {
return var8;
}
}
ItemComposition var9 = NetWriter.getItemDefinition(var0);
if(var1 > 1 && var9.countObj != null) {
int var10 = -1;
for(int var11 = 0; var11 < 10; ++var11) {
if(var1 >= var9.countCo[var11] && var9.countCo[var11] != 0) {
var10 = var9.countObj[var11];
}
}
if(var10 != -1) {
var9 = NetWriter.getItemDefinition(var10);
}
}
Model var21 = var9.getModel(1);
if(var21 == null) {
return null;
} else {
SpritePixels var22 = null;
if(var9.notedTemplate != -1) {
var22 = createSprite(var9.note, 10, 1, 0, 0, true);
if(var22 == null) {
return null;
}
} else if(var9.notedId != -1) {
var22 = createSprite(var9.unnotedId, var1, var2, var3, 0, false);
if(var22 == null) {
return null;
}
} else if(var9.placeholderTemplateId != -1) {
var22 = createSprite(var9.placeholderId, var1, 0, 0, 0, false);
if(var22 == null) {
return null;
}
}
int[] var12 = Rasterizer2D.graphicsPixels;
int var13 = Rasterizer2D.graphicsPixelsWidth;
int var14 = Rasterizer2D.graphicsPixelsHeight;
int[] var15 = new int[4];
Rasterizer2D.copyDrawRegion(var15);
var8 = new SpritePixels(36, 32);
Rasterizer2D.setRasterBuffer(var8.pixels, 36, 32);
Rasterizer2D.reset();
Graphics3D.Rasterizer3D_method1();
Graphics3D.method2880(16, 16);
Graphics3D.rasterGouraudLowRes = false;
if(var9.placeholderTemplateId != -1) {
var22.drawAt(0, 0);
}
int var16 = var9.zoom2d;
if(var5) {
var16 = (int)((double)var16 * 1.5D);
} else if(var2 == 2) {
var16 = (int)(1.04D * (double)var16);
}
int var17 = var16 * Graphics3D.SINE[var9.xan2d] >> 16;
int var18 = var16 * Graphics3D.COSINE[var9.xan2d] >> 16;
var21.calculateBoundsCylinder();
var21.method2781(0, var9.yan2d, var9.zan2d, var9.xan2d, var9.offsetX2d, var21.modelHeight / 2 + var17 + var9.offsetY2d, var18 + var9.offsetY2d);
if(var9.notedId != -1) {
var22.drawAt(0, 0);
}
if(var2 >= 1) {
var8.method5913(1);
}
if(var2 >= 2) {
var8.method5913(16777215);
}
if(var3 != 0) {
var8.method5914(var3);
}
Rasterizer2D.setRasterBuffer(var8.pixels, 36, 32);
if(var9.notedTemplate != -1) {
var22.drawAt(0, 0);
}
if(var4 == 1 || var4 == 2 && var9.isStackable == 1) {
Font var19 = ItemComposition.field3652;
String var20;
if(var1 < 100000) {
var20 = "<col=ffff00>" + var1 + "</col>";
} else if(var1 < 10000000) {
var20 = "<col=ffffff>" + var1 / 1000 + "K" + "</col>";
} else {
var20 = "<col=00ff80>" + var1 / 1000000 + "M" + "</col>";
}
var19.method5630(var20, 0, 9, 16776960, 1);
}
if(!var5) {
ItemComposition.itemSpriteCache.put(var8, var6);
}
Rasterizer2D.setRasterBuffer(var12, var13, var14);
Rasterizer2D.setDrawRegion(var15);
Graphics3D.Rasterizer3D_method1();
Graphics3D.rasterGouraudLowRes = true;
return var8;
}
}
}
| 31.072368 | 153 | 0.527207 |
92e0907b178cd7b038a278775c7f3d36b04c1197 | 249 | package in.clouthink.synergy.support.management;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
/**
*/
@Configuration
@Profile("prod")
public class MonitoringConfiguration {
}
| 19.153846 | 60 | 0.811245 |
ec798bd9ec8dc87fd391642168cab5f0da26c5eb | 489 | package com.cnews.guji.smart.ui.adapter.movie;
import com.cnews.guji.smart.R;
import com.github.library.BaseQuickAdapter;
import com.github.library.BaseViewHolder;
/**
* 获奖情况
*/
public class MovieAwardsAdapter extends BaseQuickAdapter<String,BaseViewHolder> {
public MovieAwardsAdapter() {
super(R.layout.item_movie_awards,null);
}
@Override
protected void convert(BaseViewHolder helper, String item) {
helper.setText(R.id.tv_award_name,item);
}
}
| 24.45 | 81 | 0.736196 |
e05572b8c9ff73bdf1aca4d81353b8ebae710e91 | 4,858 | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* 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.spongepowered.common.world.volume.buffer.archetype.entity;
import org.spongepowered.api.entity.EntityArchetype;
import org.spongepowered.api.util.Tuple;
import org.spongepowered.api.world.volume.archetype.entity.EntityArchetypeEntry;
import org.spongepowered.api.world.volume.archetype.entity.EntityArchetypeVolume;
import org.spongepowered.api.world.volume.stream.StreamOptions;
import org.spongepowered.api.world.volume.stream.VolumeElement;
import org.spongepowered.api.world.volume.stream.VolumeStream;
import org.spongepowered.common.world.volume.SpongeVolumeStream;
import org.spongepowered.common.world.volume.VolumeStreamUtils;
import org.spongepowered.common.world.volume.buffer.AbstractVolumeBuffer;
import org.spongepowered.math.vector.Vector3d;
import org.spongepowered.math.vector.Vector3i;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ObjectArrayMutableEntityArchetypeBuffer extends AbstractVolumeBuffer implements EntityArchetypeVolume.Mutable<ObjectArrayMutableEntityArchetypeBuffer> {
private final ArrayList<Tuple<Vector3d, EntityArchetype>> entities;
public ObjectArrayMutableEntityArchetypeBuffer(final Vector3i start, final Vector3i size) {
super(start, size);
this.entities = new ArrayList<>();
}
@Override
public Collection<EntityArchetype> entityArchetypes() {
return this.entities.stream()
.map(Tuple::second)
.collect(Collectors.toList());
}
@Override
public Collection<EntityArchetype> entityArchetypes(final Predicate<EntityArchetype> filter) {
return this.entities.stream()
.map(Tuple::second)
.filter(filter)
.collect(Collectors.toList());
}
@Override
public VolumeStream<ObjectArrayMutableEntityArchetypeBuffer, EntityArchetype> entityArchetypeStream(final Vector3i min, final Vector3i max,
final StreamOptions options
) {
VolumeStreamUtils.validateStreamArgs(min, max, this.blockMin(), this.blockMax(), options);
final Stream<Tuple<Vector3d, EntityArchetype>> entryStream;
if (options.carbonCopy()) {
entryStream = new ArrayList<>(this.entities).stream();
} else {
entryStream = this.entities.stream();
}
final Stream<VolumeElement<ObjectArrayMutableEntityArchetypeBuffer, EntityArchetype>> archetypeStream = entryStream
.filter(VolumeStreamUtils.entityArchetypePositionFilter(min, max))
.map(tuple -> VolumeElement.of(this, tuple.second(), tuple.first().toInt()));
return new SpongeVolumeStream<>(archetypeStream, () -> this);
}
@Override
public Stream<EntityArchetypeEntry> entitiesByPosition() {
return this.entities.stream()
.map(tuple -> EntityArchetypeEntry.of(tuple.second(), tuple.first()));
}
@Override
public void addEntity(final EntityArchetypeEntry entry) {
if (!this.containsBlock(Objects.requireNonNull(entry, "EntityArchetype cannot be null").position().toInt())) {
final String message = String.format(
"EntityArchetype position is out of bounds: Found %s but is outside bounds (%s, %s)",
entry.position(),
this.blockMin(),
this.blockMax()
);
throw new IllegalArgumentException(message);
}
this.entities.add(Tuple.of(entry.position(), entry.archetype()));
}
}
| 44.981481 | 165 | 0.728901 |
1a5b81c995b8fd76073516ed55c66f13ce435858 | 52,958 | package eu.bcvsolutions.idm.extras.sync;
import eu.bcvsolutions.idm.InitApplicationData;
import eu.bcvsolutions.idm.acc.domain.*;
import eu.bcvsolutions.idm.acc.dto.*;
import eu.bcvsolutions.idm.acc.dto.filter.*;
import eu.bcvsolutions.idm.acc.service.api.*;
import eu.bcvsolutions.idm.core.api.dto.*;
import eu.bcvsolutions.idm.core.api.dto.filter.IdmIdentityRoleFilter;
import eu.bcvsolutions.idm.core.api.dto.filter.IdmRoleCatalogueFilter;
import eu.bcvsolutions.idm.core.api.dto.filter.IdmRoleFilter;
import eu.bcvsolutions.idm.core.api.dto.filter.IdmRoleGuaranteeRoleFilter;
import eu.bcvsolutions.idm.core.api.service.*;
import eu.bcvsolutions.idm.core.eav.api.domain.PersistentType;
import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormAttributeDto;
import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormValueDto;
import eu.bcvsolutions.idm.core.eav.api.dto.filter.IdmFormAttributeFilter;
import eu.bcvsolutions.idm.core.eav.api.service.FormService;
import eu.bcvsolutions.idm.core.eav.api.service.IdmFormAttributeService;
import eu.bcvsolutions.idm.core.model.entity.IdmIdentity;
import eu.bcvsolutions.idm.extras.TestHelper;
import eu.bcvsolutions.idm.extras.TestResource;
import eu.bcvsolutions.idm.extras.entity.TestRoleResource;
import eu.bcvsolutions.idm.extras.service.api.ExtrasSyncRoleLdapService;
import eu.bcvsolutions.idm.test.api.AbstractIntegrationTest;
import groovy.json.StringEscapeUtils;
import org.junit.*;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.transaction.Transactional;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@Service
public class RoleWorkflowAdSyncTest extends AbstractIntegrationTest{
private static final String ROLE_NAME = "nameOfRole";
private static final String SECOND_ROLE_NAME = "secondRole\\AndItsName";
private static final String SYNC_CONFIG_NAME = "syncConfigNameContract";
private static final String ATTRIBUTE_NAME = "__NAME__";
private static final String ATTRIBUTE_DN = "EAV_ATTRIBUTE";
private static final String ATTRIBUTE_MEMBER = "MEMBER";
private static final String ATTRIBUTE_DN_VALUE = "CN=" + ROLE_NAME + ",OU=Office,OU=Prague,DC=bcvsolutions,DC=eu";
private static final String SECOND_ATTRIBUTE_DN_VALUE = "CN=" + SECOND_ROLE_NAME + ",OU=BigHouse,OU=Prague,DC=bcvsolutions,DC=eu";
private static final String CATALOGUE_CODE_FIRST = "Office";
private static final String CATALOGUE_CODE_SECOND = "Prague";
private static final String SYSTEM_NAME = "TestSystem" + System.currentTimeMillis();
private final String wfExampleKey = "extrasSyncRoleLdap";
private static final String CATALOG_FOLDER = "TestCatalog" + System.currentTimeMillis();
private static String USER_SYSTEM_NAME = "TestUserSystemName" + System.currentTimeMillis();
private static String overridedAttributeName = "EAV_ATTRIBUTE";
@Autowired
private TestHelper helper;
@Autowired
private SysSystemService systemService;
@Autowired
private SysSystemMappingService systemMappingService;
@Autowired
private SysSystemAttributeMappingService schemaAttributeMappingService;
@Autowired
private SysSchemaAttributeService schemaAttributeService;
@Autowired
private SysSyncConfigService syncConfigService;
@Autowired
private SysSyncLogService syncLogService;
@Autowired
private SysSyncItemLogService syncItemLogService;
@Autowired
private SysSyncActionLogService syncActionLogService;
@Autowired
private EntityManager entityManager;
@Autowired
private ApplicationContext applicationContext;
@Autowired
private IdmRoleService roleService;
@Autowired
private FormService formService;
@Autowired
private IdmRoleCatalogueService roleCatalogueService;
@Autowired
private ConfigurationService configurationService;
@Autowired
private SysRoleSystemAttributeService roleSystemAttributeService;
@Autowired
private SysRoleSystemService roleSystemService;
@Autowired
private IdmRoleCatalogueRoleService roleCatalogueRoleService;
@Autowired
private IdmIdentityRoleService identityRoleService;
@Autowired
private IdmFormAttributeService formAttributeService;
@Autowired
private IdmRoleGuaranteeRoleService roleGuaranteeRoleService;
@Autowired
private ExtrasSyncRoleLdapService syncRoleLdapService;
@Before
public void init() {
loginAsAdmin(InitApplicationData.ADMIN_USERNAME);
configurationService.setBooleanValue("idm.pub.acc.enabled", Boolean.TRUE);
configurationService.setValue("idm.pub.acc.syncRole.system.mapping.attributeRoleIdentificator", ATTRIBUTE_DN);
configurationService.setValue("idm.pub.acc.syncRole.provisioningOfIdentities.system.code", USER_SYSTEM_NAME);
configurationService.setValue("idm.pub.acc.syncRole.system.mapping.attributeMemberOf", overridedAttributeName);
SysSystemDto userSystem = systemService.getByCode(USER_SYSTEM_NAME);
if (userSystem == null) {
userSystem = initData(USER_SYSTEM_NAME, true);
userSystem.setDisabledProvisioning(true);
systemService.save(userSystem);
}
}
@After
public void logout() {
if (roleService.getByCode(ROLE_NAME) != null) {
roleService.delete(roleService.getByCode(ROLE_NAME));
}
if (roleService.getByCode(SECOND_ROLE_NAME) != null) {
roleService.delete(roleService.getByCode(SECOND_ROLE_NAME));
}
if (systemService.getByCode(SYSTEM_NAME) != null) {
systemService.delete(systemService.getByCode(SYSTEM_NAME));
}
configurationService.deleteValue("idm.pub.acc.syncRole.system.mapping.attributeRoleIdentificator");
super.logout();
}
@Test
public void n5_testSyncWithWfSituationMissingEntity() {
SysSystemDto system = initData();
IdmRoleFilter roleFilter = new IdmRoleFilter();
roleFilter.setText(ROLE_NAME);
List<IdmRoleDto> roles = roleService.find(roleFilter, null).getContent();
Assert.assertEquals(0, roles.size());
Assert.assertNotNull(system);
SysSyncRoleConfigDto config = doCreateSyncConfig(system);
config.setLinkedActionWfKey(wfExampleKey);
config.setMissingAccountActionWfKey(wfExampleKey);
config.setMissingEntityActionWfKey(wfExampleKey);
config.setUnlinkedActionWfKey(wfExampleKey);
config = (SysSyncRoleConfigDto) syncConfigService.save(config);
// Start sync
helper.startSynchronization(config);
SysSyncLogDto log = checkSyncLog(config, SynchronizationActionType.MISSING_ENTITY, 2,
OperationResultType.WF);
Assert.assertFalse(log.isRunning());
Assert.assertFalse(log.isContainsError());
roles = roleService.find(roleFilter, null).getContent();
Assert.assertEquals(1, roles.size());
IdmRoleDto role = roles.get(0);
List<IdmFormValueDto> dnValues = formService.getValues(role, ATTRIBUTE_DN);
Assert.assertEquals(1, dnValues.size());
Assert.assertEquals(ATTRIBUTE_DN_VALUE, dnValues.get(0).getValue());
IdmRoleCatalogueDto catalogueFirst = getCatalogueByCode(CATALOGUE_CODE_FIRST);
IdmRoleCatalogueDto catalogueSecond = getCatalogueByCode(CATALOGUE_CODE_SECOND);
Assert.assertNotNull(catalogueFirst);
Assert.assertNotNull(catalogueSecond);
// Delete log
syncLogService.delete(log);
}
@Test
public void n5_testSyncWithWfSituationLinked() {
createRolesInSystem();
final String newDN = "CN=" + ROLE_NAME + ",OU=Flat,OU=Pardubice,DC=bcvsolutions,DC=eu";
this.getBean().initIdentityData(ROLE_NAME, newDN, SECOND_ROLE_NAME, SECOND_ATTRIBUTE_DN_VALUE);
IdmRoleFilter roleFilter = new IdmRoleFilter();
roleFilter.setText(ROLE_NAME);
List<IdmRoleDto> roles = roleService.find(roleFilter, null).getContent();
Assert.assertEquals(1, roles.size());
SysSystemDto systemDto = systemService.getByCode(SYSTEM_NAME);
Assert.assertNotNull(systemDto);
SysSyncConfigFilter filter = new SysSyncConfigFilter();
filter.setSystemId(systemDto.getId());
List<AbstractSysSyncConfigDto> syncConfig = syncConfigService.find(filter, null).getContent();
Assert.assertEquals(1, syncConfig.size());
// Start sync
helper.startSynchronization(syncConfig.get(0));
SysSyncLogDto log = checkSyncLog(syncConfig.get(0), SynchronizationActionType.LINKED, 2,
OperationResultType.WF);
Assert.assertFalse(log.isRunning());
Assert.assertFalse(log.isContainsError());
roles = roleService.find(roleFilter, null).getContent();
Assert.assertEquals(1, roles.size());
IdmRoleDto role = roles.get(0);
List<IdmFormValueDto> dnValues = formService.getValues(role, ATTRIBUTE_DN);
Assert.assertEquals(1, dnValues.size());
Assert.assertEquals(newDN, dnValues.get(0).getValue());
IdmRoleCatalogueDto catalogueFirst = getCatalogueByCode("Flat");
IdmRoleCatalogueDto catalogueSecond = getCatalogueByCode("Pardubice");
Assert.assertNotNull(catalogueFirst);
Assert.assertNotNull(catalogueSecond);
// Delete log
syncLogService.delete(log);
}
@Test
public void n5_testSyncWithWfSituationUnlinked() {
SysSystemDto system = initData();
IdmRoleFilter roleFilter = new IdmRoleFilter();
roleFilter.setText(ROLE_NAME);
List<IdmRoleDto> roles = roleService.find(roleFilter, null).getContent();
Assert.assertEquals(0, roles.size());
IdmRoleDto role = new IdmRoleDto();
role.setCode(ROLE_NAME);
roleService.save(role);
Assert.assertNotNull(system);
SysSyncRoleConfigDto config = doCreateSyncConfig(system);
config.setLinkedActionWfKey(wfExampleKey);
config.setMissingAccountActionWfKey(wfExampleKey);
config.setMissingEntityActionWfKey(wfExampleKey);
config.setUnlinkedActionWfKey(wfExampleKey);
config = (SysSyncRoleConfigDto) syncConfigService.save(config);
// Start sync
helper.startSynchronization(config);
SysSyncLogDto log = checkSyncLog(config, SynchronizationActionType.UNLINKED, 1,
OperationResultType.WF);
Assert.assertFalse(log.isRunning());
Assert.assertFalse(log.isContainsError());
roles = roleService.find(roleFilter, null).getContent();
Assert.assertEquals(1, roles.size());
role = roles.get(0);
List<IdmFormValueDto> dnValues = formService.getValues(role, ATTRIBUTE_DN);
Assert.assertEquals(1, dnValues.size());
Assert.assertEquals(ATTRIBUTE_DN_VALUE, dnValues.get(0).getValue());
IdmRoleCatalogueDto catalogueFirst = getCatalogueByCode(CATALOGUE_CODE_FIRST);
IdmRoleCatalogueDto catalogueSecond = getCatalogueByCode(CATALOGUE_CODE_SECOND);
Assert.assertNotNull(catalogueFirst);
Assert.assertNotNull(catalogueSecond);
// Delete log
syncLogService.delete(log);
}
@Test
public void n5_testSyncWithWfSituationMissingAccount() {
createRolesInSystem();
this.getBean().deleteAllResourceData();
IdmRoleFilter roleFilter = new IdmRoleFilter();
roleFilter.setText(ROLE_NAME);
List<IdmRoleDto> roles = roleService.find(roleFilter, null).getContent();
Assert.assertEquals(1, roles.size());
SysSystemDto systemDto = systemService.getByCode(SYSTEM_NAME);
Assert.assertNotNull(systemDto);
SysSyncConfigFilter filter = new SysSyncConfigFilter();
filter.setSystemId(systemDto.getId());
List<AbstractSysSyncConfigDto> syncConfig = syncConfigService.find(filter, null).getContent();
Assert.assertEquals(1, syncConfig.size());
// Start sync
helper.startSynchronization(syncConfig.get(0));
SysSyncLogDto log = checkSyncLog(syncConfig.get(0), SynchronizationActionType.MISSING_ACCOUNT, 2,
OperationResultType.WF);
Assert.assertFalse(log.isRunning());
Assert.assertFalse(log.isContainsError());
roles = roleService.find(roleFilter, null).getContent();
Assert.assertEquals(0, roles.size());
// Delete log
syncLogService.delete(log);
}
@Test
public void n1_testSyncWithWfSituationMissingEntityDoNotCreateCatalog() {
configurationService.setBooleanValue("idm.pub.acc.syncRole.roleCatalog.ResolveCatalog", false);
SysSystemDto system = initData();
Assert.assertNull(getCatalogueByCode(CATALOGUE_CODE_SECOND));
Assert.assertNotNull(system);
SysSyncRoleConfigDto config = doCreateSyncConfig(system);
config.setLinkedActionWfKey(wfExampleKey);
config.setMissingAccountActionWfKey(wfExampleKey);
config.setMissingEntityActionWfKey(wfExampleKey);
config.setUnlinkedActionWfKey(wfExampleKey);
config = (SysSyncRoleConfigDto) syncConfigService.save(config);
// Start sync
helper.startSynchronization(config);
SysSyncLogDto log = checkSyncLog(config, SynchronizationActionType.MISSING_ENTITY, 2,
OperationResultType.WF);
Assert.assertFalse(log.isRunning());
Assert.assertFalse(log.isContainsError());
List<IdmRoleDto> roles = roleService.find(new IdmRoleFilter(), null).getContent();
roles = roles.stream().filter(role -> role.getName().equals(ROLE_NAME) || role.getName().equals(SECOND_ROLE_NAME)).collect(Collectors.toList());
Assert.assertEquals(2, roles.size());
//
IdmRoleFilter roleFilter = new IdmRoleFilter();
roleFilter.setText(ROLE_NAME);
roles = roleService.find(roleFilter, null).getContent();
//
IdmRoleDto role = roles.get(0);
List<IdmFormValueDto> dnValues = formService.getValues(role, ATTRIBUTE_DN);
Assert.assertEquals(1, dnValues.size());
Assert.assertEquals(ATTRIBUTE_DN_VALUE, dnValues.get(0).getValue());
IdmRoleCatalogueDto catalogueFirst = getCatalogueByCode(CATALOGUE_CODE_FIRST);
IdmRoleCatalogueDto catalogueSecond = getCatalogueByCode(CATALOGUE_CODE_SECOND);
Assert.assertNull(catalogueFirst);
Assert.assertNull(catalogueSecond);
// Delete log
syncLogService.delete(log);
configurationService.setBooleanValue("idm.pub.acc.syncRole.roleCatalog.ResolveCatalog", true);
}
@Test
public void n8_testSyncWithWfSituationMissingEntityOneFolderCatalog() {
configurationService.setValue("idm.pub.acc.syncRole.roles.allToOneCatalog", CATALOG_FOLDER);
SysSystemDto system = initData();
IdmRoleFilter roleFilter = new IdmRoleFilter();
roleFilter.setText(ROLE_NAME);
List<IdmRoleDto> roles = roleService.find(roleFilter, null).getContent();
Assert.assertEquals(0, roles.size());
Assert.assertNotNull(system);
SysSyncRoleConfigDto config = doCreateSyncConfig(system);
config.setLinkedActionWfKey(wfExampleKey);
config.setMissingAccountActionWfKey(wfExampleKey);
config.setMissingEntityActionWfKey(wfExampleKey);
config.setUnlinkedActionWfKey(wfExampleKey);
config = (SysSyncRoleConfigDto) syncConfigService.save(config);
// Start sync
helper.startSynchronization(config);
SysSyncLogDto log = checkSyncLog(config, SynchronizationActionType.MISSING_ENTITY, 2,
OperationResultType.WF);
Assert.assertFalse(log.isRunning());
Assert.assertFalse(log.isContainsError());
roles = roleService.find(roleFilter, null).getContent();
Assert.assertEquals(1, roles.size());
IdmRoleDto role = roles.get(0);
List<IdmFormValueDto> dnValues = formService.getValues(role, ATTRIBUTE_DN);
Assert.assertEquals(1, dnValues.size());
Assert.assertEquals(ATTRIBUTE_DN_VALUE, dnValues.get(0).getValue());
IdmRoleCatalogueDto catalogueFirst = getCatalogueByCode(CATALOG_FOLDER);
Assert.assertNotNull(catalogueFirst);
Assert.assertFalse(!isRoleInCatalogue(role.getId(), CATALOG_FOLDER));
// Delete log
syncLogService.delete(log);
configurationService.setValue("idm.pub.acc.syncRole.roles.allToOneCatalog", null);
}
@Test
public void n81_testSyncWithWfSituationMissingEntityCreateCatalog() {
configurationService.setValue("idm.pub.acc.syncRole.roles.allToOneCatalog", CATALOG_FOLDER);
SysSystemDto system = initData();
IdmRoleFilter roleFilter = new IdmRoleFilter();
roleFilter.setText(ROLE_NAME);
List<IdmRoleDto> roles = roleService.find(roleFilter, null).getContent();
Assert.assertEquals(0, roles.size());
Assert.assertNotNull(system);
SysSyncRoleConfigDto config = doCreateSyncConfig(system);
config.setLinkedActionWfKey(wfExampleKey);
config.setMissingAccountActionWfKey(wfExampleKey);
config.setMissingEntityActionWfKey(wfExampleKey);
config.setUnlinkedActionWfKey(wfExampleKey);
config = (SysSyncRoleConfigDto) syncConfigService.save(config);
// Start sync
helper.startSynchronization(config);
SysSyncLogDto log = checkSyncLog(config, SynchronizationActionType.MISSING_ENTITY, 2,
OperationResultType.WF);
Assert.assertFalse(log.isRunning());
Assert.assertFalse(log.isContainsError());
roles = roleService.find(roleFilter, null).getContent();
Assert.assertEquals(1, roles.size());
IdmRoleDto role = roles.get(0);
List<IdmFormValueDto> dnValues = formService.getValues(role, ATTRIBUTE_DN);
Assert.assertEquals(1, dnValues.size());
Assert.assertEquals(ATTRIBUTE_DN_VALUE, dnValues.get(0).getValue());
IdmRoleCatalogueDto catalogueFirst = getCatalogueByCode(CATALOG_FOLDER);
Assert.assertNotNull(catalogueFirst);
Assert.assertTrue(isRoleInCatalogue(role.getId(), CATALOG_FOLDER));
// Delete log
syncLogService.delete(log);
//
configurationService.setValue("idm.pub.acc.syncRole.roleCatalog.catalogueTreeInOneCatalog", null);
}
@Test
public void n82_testSyncWithWfSituationMissingEntityTwiceSync() {
String valueOfMemberAtt = "" + System.currentTimeMillis();
String nameOfEav = "externalIdentifier";
configurationService.setValue("idm.pub.acc.syncRole.identity.eav.externalIdentifier.code", nameOfEav);
configurationService.setValue("idm.pub.acc.syncRole.roles.attributeNameOfMembership", ATTRIBUTE_MEMBER);
configurationService.setBooleanValue("idm.pub.acc.syncRole.update.resolveMembership", true);
IdmIdentityDto identity = this.getHelper().createIdentity();
IdmFormAttributeDto attribute = helper.createEavAttribute(nameOfEav, IdmIdentity.class, PersistentType.SHORTTEXT);
helper.setEavValue(identity, attribute, IdmIdentity.class, valueOfMemberAtt, PersistentType.SHORTTEXT);
SysSystemDto system = initData();
this.getBean().deleteAllResourceData();
this.getBean().addRoleToResource(ROLE_NAME, ATTRIBUTE_DN, valueOfMemberAtt);
IdmRoleFilter roleFilter = new IdmRoleFilter();
roleFilter.setText(ROLE_NAME);
List<IdmRoleDto> roles = roleService.find(roleFilter, null).getContent();
Assert.assertEquals(0, roles.size());
IdmIdentityRoleFilter filter = new IdmIdentityRoleFilter();
filter.setIdentityId(identity.getId());
List<IdmIdentityRoleDto> content = identityRoleService.find(filter , null).getContent();
Assert.assertEquals(0, content.size());
Assert.assertNotNull(system);
SysSyncRoleConfigDto config = doCreateSyncConfig(system);
config.setLinkedActionWfKey(wfExampleKey);
config.setMissingAccountActionWfKey(wfExampleKey);
config.setMissingEntityActionWfKey(wfExampleKey);
config.setUnlinkedActionWfKey(wfExampleKey);
config = (SysSyncRoleConfigDto) syncConfigService.save(config);
// Start sync
helper.startSynchronization(config);
SysSyncLogDto log = checkSyncLog(config, SynchronizationActionType.MISSING_ENTITY, 1,
OperationResultType.WF);
Assert.assertFalse(log.isRunning());
Assert.assertFalse(log.isContainsError());
roles = roleService.find(roleFilter, null).getContent();
Assert.assertEquals(1, roles.size());
content = identityRoleService.find(filter , null).getContent();
Assert.assertEquals(1, content.size());
// Delete log
syncLogService.delete(log);
// Start sync
helper.startSynchronization(config);
SysSyncLogDto log2 = checkSyncLog(config, SynchronizationActionType.LINKED, 1,
OperationResultType.WF);
Assert.assertFalse(log2.isRunning());
Assert.assertFalse(log2.isContainsError());
// after two synchronizations, there must be just one assign role
content = identityRoleService.find(filter , null).getContent();
Assert.assertEquals(1, content.size());
identityRoleService.delete(content.get(0));
// Delete log
syncLogService.delete(log2);
//
configurationService.deleteValue("idm.pub.acc.syncRole.provisioningOfIdentities.system.code");
configurationService.deleteValue("idm.pub.acc.syncRole.system.mapping.attributeMemberOf");
configurationService.setBooleanValue("idm.pub.acc.syncRole.update.resolveMembership", false);
}
@Test
public void n83_testSyncWithWfSituationMissingEntityPriorityLevelRoleGarantee() {
configurationService.setValue("idm.pub.acc.syncRole.roleCatalog.catalogueTreeInOneCatalog", CATALOG_FOLDER);
configurationService.setValue("idm.pub.acc.syncRole.roles.create.priorityOfRoles", "1");
//
String roleGaranteeName = "roleGarantee" + System.currentTimeMillis();
configurationService.setValue("idm.pub.acc.syncRole.roles.create.garanteeOfRoles", roleGaranteeName);
IdmRoleDto garantee = new IdmRoleDto();
garantee.setName(roleGaranteeName);
roleService.save(garantee);
SysSystemDto system = initData();
IdmRoleFilter roleFilter = new IdmRoleFilter();
roleFilter.setText(ROLE_NAME);
List<IdmRoleDto> roles = roleService.find(roleFilter, null).getContent();
Assert.assertEquals(0, roles.size());
Assert.assertNotNull(system);
SysSyncRoleConfigDto config = doCreateSyncConfig(system);
config.setLinkedActionWfKey(wfExampleKey);
config.setMissingAccountActionWfKey(wfExampleKey);
config.setMissingEntityActionWfKey(wfExampleKey);
config.setUnlinkedActionWfKey(wfExampleKey);
config = (SysSyncRoleConfigDto) syncConfigService.save(config);
// Start sync
helper.startSynchronization(config);
SysSyncLogDto log = checkSyncLog(config, SynchronizationActionType.MISSING_ENTITY, 2,
OperationResultType.WF);
Assert.assertFalse(log.isRunning());
Assert.assertFalse(log.isContainsError());
roles = roleService.find(roleFilter, null).getContent();
Assert.assertEquals(1, roles.size());
IdmRoleDto role = roles.get(0);
List<IdmFormValueDto> dnValues = formService.getValues(role, ATTRIBUTE_DN);
Assert.assertEquals(1, dnValues.size());
Assert.assertEquals(ATTRIBUTE_DN_VALUE, dnValues.get(0).getValue());
IdmRoleCatalogueDto catalogueFirst = getCatalogueByCode(CATALOG_FOLDER);
Assert.assertNotNull(catalogueFirst);
Assert.assertTrue(isRoleInCatalogue(role.getId(), CATALOG_FOLDER));
// assert priority level
Assert.assertEquals(role.getPriority(), 1);
// assert role garantee
IdmRoleGuaranteeRoleFilter filter = new IdmRoleGuaranteeRoleFilter();
filter.setRole(role.getId());
List<IdmRoleGuaranteeRoleDto> content = roleGuaranteeRoleService.find(filter, null).getContent();
Assert.assertEquals(content.size(), 1);
Assert.assertNotNull(content.get(0).getGuaranteeRole());
IdmRoleDto assignedRoleGarantee = roleService.get(content.get(0).getGuaranteeRole());
Assert.assertNotNull(assignedRoleGarantee);
Assert.assertEquals(assignedRoleGarantee.getName(), roleGaranteeName);
// Delete log
syncLogService.delete(log);
//
configurationService.setValue("idm.pub.acc.syncRole.roles.create.priorityOfRoles", null);
configurationService.setValue("idm.pub.acc.syncRole.roleCatalog.catalogueTreeInOneCatalog", null);
configurationService.setValue("idm.pub.acc.syncRole.roles.create.garanteeOfRoles", roleGaranteeName);
}
@Test
public void n94_testSyncWithWfSituationMissingEntityTriceSyncForwardManagement() {
SysSystemDto userSystem = systemService.getByCode(USER_SYSTEM_NAME);
String valueOfMemberAtt = "" + System.currentTimeMillis();
String nameOfEav = "externalIdentifier";
configurationService.setBooleanValue("idm.pub.acc.syncRole.roleSystem.forwardManagement.value", true);
configurationService.setBooleanValue("idm.pub.acc.syncRole.roleSystem.update.manageforwardManagement", false);
IdmIdentityDto identity = this.getHelper().createIdentity();
IdmFormAttributeDto attribute = formService.getAttribute(formService.getDefinition(IdmIdentity.class), nameOfEav);
if(attribute == null) {
attribute = helper.createEavAttribute(nameOfEav, IdmIdentity.class, PersistentType.SHORTTEXT);
} helper.setEavValue(identity, attribute, IdmIdentity.class, valueOfMemberAtt, PersistentType.SHORTTEXT);
SysSystemDto system = initData();
IdmRoleFilter roleFilter = new IdmRoleFilter();
roleFilter.setText(ROLE_NAME);
List<IdmRoleDto> roles = roleService.find(roleFilter, null).getContent();
Assert.assertEquals(0, roles.size());
Assert.assertNotNull(system);
SysSyncRoleConfigDto config = doCreateSyncConfig(system);
config.setLinkedActionWfKey(wfExampleKey);
config.setMissingAccountActionWfKey(wfExampleKey);
config.setMissingEntityActionWfKey(wfExampleKey);
config.setUnlinkedActionWfKey(wfExampleKey);
config = (SysSyncRoleConfigDto) syncConfigService.save(config);
// Start sync
helper.startSynchronization(config);
SysSyncLogDto log = checkSyncLog(config, SynchronizationActionType.MISSING_ENTITY, 2,
OperationResultType.WF);
Assert.assertFalse(log.isRunning());
Assert.assertFalse(log.isContainsError());
roles = roleService.find(new IdmRoleFilter(), null).getContent();
roles = roles.stream().filter(role -> role.getName().equals(ROLE_NAME) || role.getName().equals(SECOND_ROLE_NAME)).collect(Collectors.toList());
Assert.assertEquals(2, roles.size());
assertTrue(syncRoleLdapService.isForwardAccountManagement(userSystem.getId(), roles.get(0).getId(), ATTRIBUTE_NAME));
assertTrue(syncRoleLdapService.isForwardAccountManagement(userSystem.getId(), roles.get(1).getId(), ATTRIBUTE_NAME));
// Delete log
syncLogService.delete(log);
// set forward management to false
configurationService.setBooleanValue("idm.pub.acc.syncRole.roleSystem.forwardManagement.value", false);
// Start sync
helper.startSynchronization(config);
SysSyncLogDto log2 = checkSyncLog(config, SynchronizationActionType.LINKED, 2,
OperationResultType.WF);
Assert.assertFalse(log2.isRunning());
Assert.assertFalse(log2.isContainsError());
// Delete log
syncLogService.delete(log2);
// forward management still true
assertTrue(syncRoleLdapService.isForwardAccountManagement(userSystem.getId(), roles.get(0).getId(), ATTRIBUTE_NAME));
// set true to set forward management on update
configurationService.setBooleanValue("idm.pub.acc.syncRole.roleSystem.update.manageforwardManagement", true);
// Start sync
helper.startSynchronization(config);
SysSyncLogDto log3 = checkSyncLog(config, SynchronizationActionType.LINKED, 2,
OperationResultType.WF);
Assert.assertFalse(log3.isRunning());
Assert.assertFalse(log3.isContainsError());
// Delete log
syncLogService.delete(log3);
// forward management false
assertFalse(syncRoleLdapService.isForwardAccountManagement(userSystem.getId(), roles.get(0).getId(), ATTRIBUTE_NAME));
//
configurationService.setBooleanValue("idm.pub.acc.syncRole.roleSystem.update.manageforwardManagement", false);
configurationService.setValue("idm.pub.acc.syncRole.provisioningOfIdentities.system.code", null);
}
@Test
public void n95_contractOnExclusionOptionTest() {
SysSystemDto userSystem = systemService.getByCode(USER_SYSTEM_NAME);
String valueOfMemberAtt = "" + System.currentTimeMillis();
String nameOfEav = "externalIdentifier";
configurationService.setValue("idm.pub.acc.syncRole.roles.nameOfRoles.doNotSentValueOnExclusion", ROLE_NAME);
configurationService.setBooleanValue("idm.pub.acc.syncRole.roleSystem.update.manageforwardManagement", false);
IdmIdentityDto identity = this.getHelper().createIdentity();
IdmFormAttributeDto attribute = formService.getAttribute(formService.getDefinition(IdmIdentity.class), nameOfEav);
if(attribute == null) {
attribute = helper.createEavAttribute(nameOfEav, IdmIdentity.class, PersistentType.SHORTTEXT);
} helper.setEavValue(identity, attribute, IdmIdentity.class, valueOfMemberAtt, PersistentType.SHORTTEXT);
SysSystemDto system = initData();
IdmRoleFilter roleFilter = new IdmRoleFilter();
roleFilter.setText(ROLE_NAME);
List<IdmRoleDto> roles = roleService.find(roleFilter, null).getContent();
Assert.assertEquals(0, roles.size());
Assert.assertNotNull(system);
SysSyncRoleConfigDto config = doCreateSyncConfig(system);
config.setLinkedActionWfKey(wfExampleKey);
config.setMissingAccountActionWfKey(wfExampleKey);
config.setMissingEntityActionWfKey(wfExampleKey);
config.setUnlinkedActionWfKey(wfExampleKey);
config = (SysSyncRoleConfigDto) syncConfigService.save(config);
// Start sync
helper.startSynchronization(config);
SysSyncLogDto log = checkSyncLog(config, SynchronizationActionType.MISSING_ENTITY, 2,
OperationResultType.WF);
Assert.assertFalse(log.isRunning());
Assert.assertFalse(log.isContainsError());
roles = roleService.find(new IdmRoleFilter(), null).getContent();
roles = roles.stream().filter(role -> role.getName().equals(ROLE_NAME) || role.getName().equals(SECOND_ROLE_NAME)).collect(Collectors.toList());
Assert.assertEquals(2, roles.size());
assertTrue(syncRoleLdapService.isSkipValueIfExcluded(userSystem.getId(), roles.get(0).getId(), overridedAttributeName, ATTRIBUTE_NAME));
assertTrue(!syncRoleLdapService.isSkipValueIfExcluded(userSystem.getId(), roles.get(1).getId(), overridedAttributeName, ATTRIBUTE_NAME));
// Delete log
syncLogService.delete(log);
// set forward management to false
configurationService.setValue("idm.pub.acc.syncRole.roles.nameOfRoles.doNotSentValueOnExclusion", null);
// Start sync
helper.startSynchronization(config);
SysSyncLogDto log2 = checkSyncLog(config, SynchronizationActionType.LINKED, 2,
OperationResultType.WF);
Assert.assertFalse(log2.isRunning());
Assert.assertFalse(log2.isContainsError());
// Delete log
syncLogService.delete(log2);
// forward management still true
assertTrue(syncRoleLdapService.isSkipValueIfExcluded(userSystem.getId(), roles.get(0).getId(), overridedAttributeName, ATTRIBUTE_NAME));
// set true to set forward management on update
configurationService.setBooleanValue("idm.pub.acc.syncRole.roles.update.nameOfRoles.manageSentValueOnExclusion", true);
// Start sync
helper.startSynchronization(config);
SysSyncLogDto log3 = checkSyncLog(config, SynchronizationActionType.LINKED, 2,
OperationResultType.WF);
Assert.assertFalse(log3.isRunning());
Assert.assertFalse(log3.isContainsError());
// Delete log
syncLogService.delete(log3);
// forward management false
assertFalse(syncRoleLdapService.isSkipValueIfExcluded(userSystem.getId(), roles.get(0).getId(), overridedAttributeName, ATTRIBUTE_NAME));
//
configurationService.setBooleanValue("idm.pub.acc.syncRole.roles.update.nameOfRoles.manageSentValueOnExclusion", false);
configurationService.setValue("idm.pub.acc.syncRole.provisioningOfIdentities.system.code", null);
}
@Test
public void n93_testSyncWithWfSituationMissingEntityAddResource() {
SysSystemDto userSystem = systemService.getByCode(USER_SYSTEM_NAME);
SysSystemDto system = initData();
IdmRoleFilter roleFilter = new IdmRoleFilter();
roleFilter.setText(ROLE_NAME);
List<IdmRoleDto> roles = roleService.find(roleFilter, null).getContent();
Assert.assertEquals(0, roles.size());
Assert.assertNotNull(system);
SysSyncRoleConfigDto config = doCreateSyncConfig(system);
config.setLinkedActionWfKey(wfExampleKey);
config.setMissingAccountActionWfKey(wfExampleKey);
config.setMissingEntityActionWfKey(wfExampleKey);
config.setUnlinkedActionWfKey(wfExampleKey);
config = (SysSyncRoleConfigDto) syncConfigService.save(config);
// Start sync
helper.startSynchronization(config);
SysSyncLogDto log = checkSyncLog(config, SynchronizationActionType.MISSING_ENTITY, 2,
OperationResultType.WF);
Assert.assertFalse(log.isRunning());
Assert.assertFalse(log.isContainsError());
roles = roleService.find(roleFilter, null).getContent();
Assert.assertEquals(1, roles.size());
IdmRoleDto role = roles.get(0);
List<IdmFormValueDto> dnValues = formService.getValues(role, ATTRIBUTE_DN);
Assert.assertEquals(1, dnValues.size());
Assert.assertEquals(ATTRIBUTE_DN_VALUE, dnValues.get(0).getValue());
// resource existing
SysRoleSystemAttributeDto systemAttribute = getSystemAttribute(userSystem.getId(), overridedAttributeName, role.getId());
Assert.assertNotNull(systemAttribute);
String transformationScript = "'" + ATTRIBUTE_DN_VALUE + "'";
Assert.assertEquals(systemAttribute.getTransformToResourceScript(), transformationScript);
//find second role, which has special char
roleFilter.setText(StringEscapeUtils.escapeJava(SECOND_ROLE_NAME));
roles = roleService.find(roleFilter, null).getContent();
Assert.assertEquals(1, roles.size());
//find system attribute of second role
systemAttribute = getSystemAttribute(userSystem.getId(), overridedAttributeName, roles.get(0).getId());
Assert.assertNotNull(systemAttribute);
transformationScript = "'" + SECOND_ATTRIBUTE_DN_VALUE + "'";
//assert - has atribute have escaped special character
Assert.assertEquals(systemAttribute.getTransformToResourceScript(), StringEscapeUtils.escapeJava(transformationScript));
// Delete log
syncLogService.delete(log);
configurationService.deleteValue("idm.pub.acc.syncRole.provisioningOfIdentities.system.code");
configurationService.deleteValue("idm.pub.acc.syncRole.system.mapping.attributeMemberOf");
}
@Test
public void n91_testSyncWithWfSituationMissingResolveMember() {
String valueOfMemberAtt = "" + System.currentTimeMillis();
String nameOfEav = "externalIdentifier";
configurationService.setValue("idm.pub.acc.syncRole.identity.eav.externalIdentifier.code", nameOfEav);
configurationService.setValue("idm.pub.acc.syncRole.roles.attributeNameOfMembership", ATTRIBUTE_MEMBER);
IdmIdentityDto identity = this.getHelper().createIdentity();
IdmFormAttributeDto attribute = formService.getAttribute(formService.getDefinition(IdmIdentity.class), nameOfEav);
if(attribute == null) {
attribute = helper.createEavAttribute(nameOfEav, IdmIdentity.class, PersistentType.SHORTTEXT);
}
helper.setEavValue(identity, attribute, IdmIdentity.class, valueOfMemberAtt, PersistentType.SHORTTEXT);
SysSystemDto system = initData();
this.getBean().deleteAllResourceData();
this.getBean().addRoleToResource(ROLE_NAME, ATTRIBUTE_DN, valueOfMemberAtt);
IdmRoleFilter roleFilter = new IdmRoleFilter();
roleFilter.setText(ROLE_NAME);
List<IdmRoleDto> roles = roleService.find(roleFilter, null).getContent();
Assert.assertEquals(0, roles.size());
IdmIdentityRoleFilter filter = new IdmIdentityRoleFilter();
filter.setIdentityId(identity.getId());
List<IdmIdentityRoleDto> content = identityRoleService.find(filter , null).getContent();
Assert.assertEquals(0, content.size());
Assert.assertNotNull(system);
SysSyncRoleConfigDto config = doCreateSyncConfig(system);
config.setLinkedActionWfKey(wfExampleKey);
config.setMissingAccountActionWfKey(wfExampleKey);
config.setMissingEntityActionWfKey(wfExampleKey);
config.setUnlinkedActionWfKey(wfExampleKey);
config = (SysSyncRoleConfigDto) syncConfigService.save(config);
// Start sync
helper.startSynchronization(config);
SysSyncLogDto log = checkSyncLog(config, SynchronizationActionType.MISSING_ENTITY, 1,
OperationResultType.WF);
Assert.assertFalse(log.isRunning());
Assert.assertFalse(log.isContainsError());
roles = roleService.find(roleFilter, null).getContent();
Assert.assertEquals(1, roles.size());
content = identityRoleService.find(filter , null).getContent();
Assert.assertEquals(1, content.size());
identityRoleService.delete(content.get(0));
// Delete log
syncLogService.delete(log);
configurationService.deleteValue("idm.pub.acc.syncRole.provisioningOfIdentities.system.code");
configurationService.deleteValue("idm.pub.acc.syncRole.system.mapping.attributeMemberOf");
}
@Test
public void n92_testSyncWithWfSituationLinkedResolveMember() {
createRolesInSystem();
final String newDN = "CN=" + ROLE_NAME + ",OU=Flat,OU=Pardubice,DC=bcvsolutions,DC=eu";
this.getBean().initIdentityData(ROLE_NAME, newDN, SECOND_ROLE_NAME, SECOND_ATTRIBUTE_DN_VALUE);
String valueOfMemberAtt = "" + System.currentTimeMillis();
String nameOfEav = "externalIdentifier";
configurationService.setValue("idm.pub.acc.syncRole.identity.eav.externalIdentifier.code", nameOfEav);
configurationService.setValue("idm.pub.acc.syncRole.roles.attributeNameOfMembership", ATTRIBUTE_MEMBER);
configurationService.setBooleanValue("idm.pub.acc.syncRole.update.resolveMembership", true);
IdmIdentityDto identity = this.getHelper().createIdentity();
IdmFormAttributeFilter attributeFilter = new IdmFormAttributeFilter();
attributeFilter.setCode(nameOfEav);
IdmFormAttributeDto formAttribute = formAttributeService.find(attributeFilter, null).getContent().stream().findFirst().orElse(null);
Assert.assertNotNull(formAttribute);
helper.setEavValue(identity, formAttribute, IdmIdentity.class, valueOfMemberAtt, PersistentType.SHORTTEXT);
this.getBean().deleteAllResourceData();
this.getBean().addRoleToResource(ROLE_NAME, ATTRIBUTE_DN, valueOfMemberAtt);
IdmRoleFilter roleFilter = new IdmRoleFilter();
roleFilter.setText(ROLE_NAME);
List<IdmRoleDto> roles = roleService.find(roleFilter, null).getContent();
Assert.assertEquals(1, roles.size()); // role is in already synced ind idm
IdmIdentityRoleFilter filter = new IdmIdentityRoleFilter();
filter.setIdentityId(identity.getId());
List<IdmIdentityRoleDto> content = identityRoleService.find(filter , null).getContent();
Assert.assertEquals(0, content.size()); // identity does not have assigned this role
SysSystemDto systemDto = systemService.getByCode(SYSTEM_NAME);
Assert.assertNotNull(systemDto);
SysSyncConfigFilter syncFilter = new SysSyncConfigFilter();
syncFilter.setSystemId(systemDto.getId());
List<AbstractSysSyncConfigDto> syncConfig = syncConfigService.find(syncFilter, null).getContent();
Assert.assertEquals(1, syncConfig.size()); // find synchronization config to start sync
// Start sync
helper.startSynchronization(syncConfig.get(0));
SysSyncLogDto log = checkSyncLog(syncConfig.get(0), SynchronizationActionType.LINKED, 1,
OperationResultType.WF);
Assert.assertFalse(log.isRunning());
Assert.assertFalse(log.isContainsError());
roles = roleService.find(roleFilter, null).getContent();
Assert.assertEquals(1, roles.size());
content = identityRoleService.find(filter , null).getContent();
Assert.assertEquals(1, content.size());
identityRoleService.delete(content.get(0));
// Delete log
syncLogService.delete(log);
configurationService.deleteValue("idm.pub.acc.syncRole.provisioningOfIdentities.system.code");
configurationService.deleteValue("idm.pub.acc.syncRole.system.mapping.attributeMemberOf");
configurationService.setBooleanValue("idm.pub.acc.syncRole.update.resolveMembership", false);
}
private SysSyncRoleConfigDto doCreateSyncConfig(SysSystemDto system) {
SysSystemMappingFilter mappingFilter = new SysSystemMappingFilter();
mappingFilter.setEntityType(SystemEntityType.ROLE);
mappingFilter.setSystemId(system.getId());
mappingFilter.setOperationType(SystemOperationType.SYNCHRONIZATION);
List<SysSystemMappingDto> mappings = systemMappingService.find(mappingFilter, null).getContent();
Assert.assertEquals(1, mappings.size());
SysSystemMappingDto mapping = mappings.get(0);
SysSystemAttributeMappingFilter attributeMappingFilter = new SysSystemAttributeMappingFilter();
attributeMappingFilter.setSystemMappingId(mapping.getId());
List<SysSystemAttributeMappingDto> attributes = schemaAttributeMappingService.find(attributeMappingFilter, null)
.getContent();
SysSystemAttributeMappingDto uidAttribute = attributes.stream().filter(attribute -> {
return attribute.isUid();
}).findFirst().orElse(null);
// Create default synchronization config
SysSyncRoleConfigDto syncConfigCustom = new SysSyncRoleConfigDto();
syncConfigCustom.setReconciliation(true);
syncConfigCustom.setCustomFilter(false);
syncConfigCustom.setSystemMapping(mapping.getId());
syncConfigCustom.setCorrelationAttribute(uidAttribute.getId());
syncConfigCustom.setName(SYNC_CONFIG_NAME);
syncConfigCustom.setLinkedAction(SynchronizationLinkedActionType.UPDATE_ENTITY);
syncConfigCustom.setUnlinkedAction(SynchronizationUnlinkedActionType.LINK_AND_UPDATE_ENTITY);
syncConfigCustom.setMissingEntityAction(SynchronizationMissingEntityActionType.CREATE_ENTITY);
syncConfigCustom.setMissingAccountAction(ReconciliationMissingAccountActionType.DELETE_ENTITY);
syncConfigCustom = (SysSyncRoleConfigDto) syncConfigService.save(syncConfigCustom);
SysSyncConfigFilter configFilter = new SysSyncConfigFilter();
configFilter.setSystemId(system.getId());
Assert.assertEquals(1, syncConfigService.find(configFilter, null).getTotalElements());
return syncConfigCustom;
}
private SysSyncLogDto checkSyncLog(AbstractSysSyncConfigDto config, SynchronizationActionType actionType, int count,
OperationResultType resultType) {
SysSyncLogFilter logFilter = new SysSyncLogFilter();
logFilter.setSynchronizationConfigId(config.getId());
List<SysSyncLogDto> logs = syncLogService.find(logFilter, null).getContent();
Assert.assertEquals(1, logs.size());
SysSyncLogDto log = logs.get(0);
if (actionType == null) {
return log;
}
SysSyncActionLogFilter actionLogFilter = new SysSyncActionLogFilter();
actionLogFilter.setSynchronizationLogId(log.getId());
List<SysSyncActionLogDto> actions = syncActionLogService.find(actionLogFilter, null).getContent();
SysSyncActionLogDto actionLog = actions.stream().filter(action -> {
return actionType == action.getSyncAction();
}).findFirst().orElse(null);
Assert.assertNotNull(actionLog);
Assert.assertEquals(resultType, actionLog.getOperationResult());
SysSyncItemLogFilter itemLogFilter = new SysSyncItemLogFilter();
itemLogFilter.setSyncActionLogId(actionLog.getId());
List<SysSyncItemLogDto> items = syncItemLogService.find(itemLogFilter, null).getContent();
Assert.assertEquals(count, items.size());
return log;
}
private SysSystemDto initData() {
return initData(SYSTEM_NAME, false);
}
private SysSystemDto initData(String systemName, boolean isProvisioning) {
// create test system
SysSystemDto system = isProvisioning ? helper.createSystem(TestResource.TABLE_NAME, systemName) : helper.createSystem(TestRoleResource.TABLE_NAME, systemName);
Assert.assertNotNull(system);
// generate schema for system
List<SysSchemaObjectClassDto> objectClasses = systemService.generateSchema(system);
// Create synchronization mapping
SysSystemMappingDto syncSystemMapping = new SysSystemMappingDto();
syncSystemMapping.setName("default_" + System.currentTimeMillis());
syncSystemMapping.setEntityType(SystemEntityType.ROLE);
syncSystemMapping.setOperationType(SystemOperationType.SYNCHRONIZATION);
syncSystemMapping.setObjectClass(objectClasses.get(0).getId());
if (isProvisioning) {
syncSystemMapping.setEntityType(SystemEntityType.IDENTITY);
syncSystemMapping.setOperationType(SystemOperationType.PROVISIONING);
}
final SysSystemMappingDto syncMapping = systemMappingService.save(syncSystemMapping);
if (!isProvisioning) {
createMapping(system, syncMapping);
this.getBean().initIdentityData(ROLE_NAME, ATTRIBUTE_DN_VALUE, SECOND_ROLE_NAME, SECOND_ATTRIBUTE_DN_VALUE);
} else {
createProvMapping(system, syncMapping);
}
return system;
}
private void createMapping(SysSystemDto system, final SysSystemMappingDto entityHandlingResult) {
SysSchemaAttributeFilter schemaAttributeFilter = new SysSchemaAttributeFilter();
schemaAttributeFilter.setSystemId(system.getId());
Page<SysSchemaAttributeDto> schemaAttributesPage = schemaAttributeService.find(schemaAttributeFilter, null);
schemaAttributesPage.forEach(schemaAttr -> {
if (ATTRIBUTE_NAME.equals(schemaAttr.getName())) {
SysSystemAttributeMappingDto attributeMapping = new SysSystemAttributeMappingDto();
attributeMapping.setUid(true);
attributeMapping.setEntityAttribute(true);
attributeMapping.setIdmPropertyName("name");
attributeMapping.setName(schemaAttr.getName());
attributeMapping.setSchemaAttribute(schemaAttr.getId());
attributeMapping.setSystemMapping(entityHandlingResult.getId());
schemaAttributeMappingService.save(attributeMapping);
} else if (ATTRIBUTE_DN.equalsIgnoreCase(schemaAttr.getName())) {
SysSystemAttributeMappingDto attributeMappingTwo = new SysSystemAttributeMappingDto();
attributeMappingTwo.setIdmPropertyName(ATTRIBUTE_DN);
attributeMappingTwo.setEntityAttribute(false);
attributeMappingTwo.setExtendedAttribute(true);
attributeMappingTwo.setName("distinguishedName");
attributeMappingTwo.setSchemaAttribute(schemaAttr.getId());
attributeMappingTwo.setSystemMapping(entityHandlingResult.getId());
schemaAttributeMappingService.save(attributeMappingTwo);
} else if (ATTRIBUTE_MEMBER.equalsIgnoreCase(schemaAttr.getName())) {
SysSystemAttributeMappingDto attributeMappingTwo = new SysSystemAttributeMappingDto();
attributeMappingTwo.setIdmPropertyName(ATTRIBUTE_MEMBER);
attributeMappingTwo.setEntityAttribute(false);
attributeMappingTwo.setExtendedAttribute(true);
attributeMappingTwo.setName("MEMBER");
attributeMappingTwo.setSchemaAttribute(schemaAttr.getId());
attributeMappingTwo.setSystemMapping(entityHandlingResult.getId());
schemaAttributeMappingService.save(attributeMappingTwo);
}
});
}
private void createProvMapping(SysSystemDto system, final SysSystemMappingDto entityHandlingResult) {
SysSchemaAttributeFilter schemaAttributeFilter = new SysSchemaAttributeFilter();
schemaAttributeFilter.setSystemId(system.getId());
Page<SysSchemaAttributeDto> schemaAttributesPage = schemaAttributeService.find(schemaAttributeFilter, null);
schemaAttributesPage.forEach(schemaAttr -> {
if (ATTRIBUTE_NAME.equals(schemaAttr.getName())) {
SysSystemAttributeMappingDto attributeMapping = new SysSystemAttributeMappingDto();
attributeMapping.setUid(true);
attributeMapping.setEntityAttribute(true);
attributeMapping.setIdmPropertyName("username");
attributeMapping.setName(schemaAttr.getName());
attributeMapping.setSchemaAttribute(schemaAttr.getId());
attributeMapping.setSystemMapping(entityHandlingResult.getId());
schemaAttributeMappingService.save(attributeMapping);
} else if (ATTRIBUTE_DN.equalsIgnoreCase(schemaAttr.getName())) {
SysSystemAttributeMappingDto attributeMappingTwo = new SysSystemAttributeMappingDto();
attributeMappingTwo.setIdmPropertyName(ATTRIBUTE_DN);
attributeMappingTwo.setEntityAttribute(false);
attributeMappingTwo.setExtendedAttribute(true);
attributeMappingTwo.setName("distinguishedName");
attributeMappingTwo.setSchemaAttribute(schemaAttr.getId());
attributeMappingTwo.setSystemMapping(entityHandlingResult.getId());
schemaAttributeMappingService.save(attributeMappingTwo);
} else if (ATTRIBUTE_MEMBER.equalsIgnoreCase(schemaAttr.getName())) {
SysSystemAttributeMappingDto attributeMappingTwo = new SysSystemAttributeMappingDto();
attributeMappingTwo.setIdmPropertyName(ATTRIBUTE_MEMBER);
attributeMappingTwo.setEntityAttribute(false);
attributeMappingTwo.setExtendedAttribute(true);
attributeMappingTwo.setName("MEMBER");
attributeMappingTwo.setSchemaAttribute(schemaAttr.getId());
attributeMappingTwo.setSystemMapping(entityHandlingResult.getId());
attributeMappingTwo.setStrategyType(AttributeMappingStrategyType.MERGE);
schemaAttributeMappingService.save(attributeMappingTwo);
}
});
}
@Transactional
public void initIdentityData(String roleName, String eavAttribute, String roleNameTwo, String eavAttributeTwo) {
deleteAllResourceData();
TestRoleResource resourceUserOne = new TestRoleResource();
resourceUserOne.setName(roleName);
resourceUserOne.setEavAttribute(eavAttribute);
entityManager.persist(resourceUserOne);
TestRoleResource resourceUserTwo = new TestRoleResource();
resourceUserTwo.setName(roleNameTwo);
resourceUserTwo.setEavAttribute(eavAttributeTwo);
entityManager.persist(resourceUserTwo);
}
@Transactional
public void addRoleToResource(String roleName, String eavAttribute, String member) {
TestRoleResource resourceUserOne = new TestRoleResource();
resourceUserOne.setName(roleName);
resourceUserOne.setEavAttribute(eavAttribute);
resourceUserOne.setMember(member);
entityManager.persist(resourceUserOne);
}
@Transactional
public void deleteAllResourceData() {
// Delete all
Query q = entityManager.createNativeQuery("DELETE FROM " + TestRoleResource.TABLE_NAME);
q.executeUpdate();
}
private RoleWorkflowAdSyncTest getBean() {
return applicationContext.getAutowireCapableBeanFactory().createBean(this.getClass());
}
private IdmRoleCatalogueDto getCatalogueByCode(String code) {
IdmRoleCatalogueFilter filter = new IdmRoleCatalogueFilter();
filter.setCode(code);
List<IdmRoleCatalogueDto> result = roleCatalogueService.find(filter, null).getContent();
if (result.size() != 1) {
return null;
}
return result.get(0);
}
private void createRolesInSystem () {
SysSystemDto system = initData();
IdmRoleFilter roleFilter = new IdmRoleFilter();
roleFilter.setText(ROLE_NAME);
List<IdmRoleDto> roles = roleService.find(roleFilter, null).getContent();
Assert.assertEquals(0, roles.size());
Assert.assertNotNull(system);
SysSyncRoleConfigDto config = doCreateSyncConfig(system);
config.setLinkedActionWfKey(wfExampleKey);
config.setMissingAccountActionWfKey(wfExampleKey);
config.setMissingEntityActionWfKey(wfExampleKey);
config.setUnlinkedActionWfKey(wfExampleKey);
config = (SysSyncRoleConfigDto) syncConfigService.save(config);
// Start sync
helper.startSynchronization(config);
SysSyncLogDto log = checkSyncLog(config, SynchronizationActionType.MISSING_ENTITY, 2,
OperationResultType.WF);
Assert.assertFalse(log.isRunning());
Assert.assertFalse(log.isContainsError());
roles = roleService.find(roleFilter, null).getContent();
Assert.assertEquals(1, roles.size());
IdmRoleDto role = roles.get(0);
List<IdmFormValueDto> dnValues = formService.getValues(role, ATTRIBUTE_DN);
Assert.assertEquals(1, dnValues.size());
Assert.assertEquals(ATTRIBUTE_DN_VALUE, dnValues.get(0).getValue());
IdmRoleCatalogueDto catalogueFirst = getCatalogueByCode(CATALOGUE_CODE_FIRST);
IdmRoleCatalogueDto catalogueSecond = getCatalogueByCode(CATALOGUE_CODE_SECOND);
Assert.assertNotNull(catalogueFirst);
Assert.assertNotNull(catalogueSecond);
// Delete log
syncLogService.delete(log);
}
/**
* Returns existing system attribute or null
*
* @param attr
* @return
*/
private SysRoleSystemAttributeDto getSystemAttribute(UUID roleSystem, String attributeName, UUID roleId) {
SysRoleSystemAttributeFilter filter = new SysRoleSystemAttributeFilter();
filter.setRoleSystemId(getSysRoleSystem(roleSystem, roleId));
List<SysRoleSystemAttributeDto> content = roleSystemAttributeService.find(filter, null).getContent();
for (SysRoleSystemAttributeDto attribute : content) {
if (attribute.getName().equals(attributeName)) {
return attribute;
}
}
return null;
}
/**
* Returns existing role's system
*
* @param systemId
* @param roleId
* @param objectClassName
* @return
*/
private UUID getSysRoleSystem(UUID systemId, UUID roleId) {
SysRoleSystemFilter filter = new SysRoleSystemFilter();
filter.setRoleId(roleId);
filter.setSystemId(systemId);
List<SysRoleSystemDto> roleSystem = roleSystemService.find(filter, null).getContent();
SysRoleSystemDto attribute = roleSystem.stream().findFirst().orElse(null);
Assert.assertNotNull(attribute);
return attribute.getId();
}
private boolean isRoleInCatalogue(UUID roleId, String inCatalog) {
List<IdmRoleCatalogueRoleDto> allCatalogsByRole = roleCatalogueRoleService.findAllByRole(roleId);
if(!allCatalogsByRole.isEmpty()) {
IdmRoleCatalogueDto inCatalogDto = roleCatalogueService.get(allCatalogsByRole.get(0).getRoleCatalogue());
IdmRoleCatalogueDto rootCatalogue = inCatalogDto.getParent() != null ? getRootCatalogue(allCatalogsByRole.get(0).getRoleCatalogue()) : inCatalogDto;
IdmRoleCatalogueDto catalogue = getCatalogueByCode(inCatalog);
Assert.assertNotNull(catalogue);
return catalogue.getId().equals(rootCatalogue.getId());
}
return false;
}
private IdmRoleCatalogueDto getRootCatalogue(UUID catalogueId) {
List<IdmRoleCatalogueDto> findAllParents = roleCatalogueService.findAllParents(catalogueId);
return findAllParents.stream().filter(parent -> parent.getParent() == null).findFirst().orElse(null);
}
}
| 41.797948 | 161 | 0.792232 |
2d08471fe6d7dc88a2c077c6ef63c506de7db60d | 9,182 | /*
* Copyright (c) 2012, United States Government, as represented by the Secretary of Health and Human Services.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the United States Government 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 UNITED STATES GOVERNMENT BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package gov.hhs.fha.nhinc.gateway.executorservice;
import org.apache.log4j.Logger;
import org.hl7.v3.CommunityPRPAIN201306UV02ResponseType;
import org.hl7.v3.PRPAIN201306UV02;
import org.hl7.v3.ProxyPRPAIN201305UVProxySecuredRequestType;
import org.hl7.v3.RespondingGatewayPRPAIN201305UV02RequestType;
import org.hl7.v3.RespondingGatewayPRPAIN201306UV02ResponseType;
import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import gov.hhs.fha.nhinc.common.nhinccommon.HomeCommunityType;
import gov.hhs.fha.nhinc.common.nhinccommon.NhinTargetSystemType;
import gov.hhs.fha.nhinc.connectmgr.UrlInfo;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants;
import gov.hhs.fha.nhinc.patientdiscovery.PatientDiscovery201306Processor;
import gov.hhs.fha.nhinc.patientdiscovery.response.ResponseFactory;
import gov.hhs.fha.nhinc.patientdiscovery.response.ResponseParams;
import gov.hhs.fha.nhinc.transform.subdisc.HL7PRPA201306Transforms;
/**
* Implements the PRPAIN201306UV02 (PDClient Response) Aggregation Strategy Each response returned from a
* CallableRequest comes to processResponse where it is aggregated into the cumulativeResponse.
*
* Also implements PD response processing: Update correlation in database for this response with patient id and
* associated assigning authority id
*
* Update home community id to assigning authority id mapping in database
*
* @author paul.eftis, zack melnick
*
* @param <Target>
* @param <Request>
* @param <Response>
* @param <CumulativeResponse>
*/
public class PDProcessor<Target extends UrlInfo, Request extends RespondingGatewayPRPAIN201305UV02RequestType,
Response extends PRPAIN201306UV02, CumulativeResponse extends RespondingGatewayPRPAIN201306UV02ResponseType>
extends ResponseProcessor<Target, Request, Response, CumulativeResponse> {
private static final Logger LOG = Logger.getLogger(PDProcessor.class);
private RespondingGatewayPRPAIN201306UV02ResponseType cumulativeResponse = null;
private AssertionType pdassertion = null;
private int count = 0;
/**
* Public constructor for PDProcessor.
* @param assertion the Assertion
*/
public PDProcessor(AssertionType assertion) {
super();
pdassertion = assertion;
cumulativeResponse = new RespondingGatewayPRPAIN201306UV02ResponseType();
}
@Override
public CumulativeResponse getCumulativeResponse() {
return (CumulativeResponse) cumulativeResponse;
}
/**
* Synchronization is covered by blocking queue implemented by the ExecutorCompletionService (i.e. we do not need to
* synchronize anything in processResponse or combineResponses)
*
* In TaskExecutor we have the following: Future<Result> fut = executorCompletionService.take(); which will block
* until a result is available. Once result is available it will be processed here and complete processing before
* the next future is retrieved and processed, so processor does not have to be concerned with synchronization.
*
* @param request is the RespondingGatewayPRPAIN201305UV02RequestType for the PD web service client call
* @param individual is the PRPAIN201306UV02 response returned from the CallableRequest
* @param t is the UrlInfo target that returned the response
*/
@Override
public void processResponse(Request request, Response individual, Target t) {
try {
processPDResponse(request, individual, t);
} catch (Exception e) {
// add error response for exception to cumulativeResponse
CommunityPRPAIN201306UV02ResponseType communityResponse = new CommunityPRPAIN201306UV02ResponseType();
communityResponse.setPRPAIN201306UV02(processError(e.getMessage(), request, null));
cumulativeResponse.getCommunityResponse().add(communityResponse);
}
}
/**
* Called from CallableRequest for any exception from the WebServiceClient Generate a new PRPAIN201306UV02 with the
* error and the source of the error.
*
* @param error (exception message)
* @param request is the ProxyPRPAIN201305UVProxySecuredRequestType for the PD web service client call
* @param target is the UrlInfo target
* @return Response PRPAIN201306UV02 object with the error
*/
@Override
public Response processError(String error, Request request, Target target) {
LOG.debug("PDProcessor::processError has error=" + error);
Response response =
(Response) new HL7PRPA201306Transforms().createPRPA201306ForErrors(request.getPRPAIN201305UV02(),
NhincConstants.PATIENT_DISCOVERY_ANSWER_NOT_AVAIL_ERR_CODE);
return response;
}
/**
* PD response processing does the following: 1. Aggregate responses 2. Update correlation in database for this
* response with patient id and associated assigning authority id 3. Update home community id to assigning authority
* id mapping in database
*
* Response processing code is from connect sources
*
* @param current is the PRPAIN201306UV02 returned from the CallableRequest
* @param request is the RespondingGatewayPRPAIN201305UV02RequestType sent by the web service client (needed for
* response processing)
* @param t is the UrlInfo target to send the web service request (needed for response processing) WebServiceClient
*/
@SuppressWarnings("static-access")
private void processPDResponse(RespondingGatewayPRPAIN201305UV02RequestType request, PRPAIN201306UV02 current,
Target t) throws Exception {
// for debug
count++;
LOG.debug("PDProcessor::processPDResponse combine next response count=" + count);
try {
// store the correlation result and handle Trust/Verify Mode
ProxyPRPAIN201305UVProxySecuredRequestType oProxyPRPAIN201305UVProxySecuredRequestType =
new ProxyPRPAIN201305UVProxySecuredRequestType();
oProxyPRPAIN201305UVProxySecuredRequestType.setPRPAIN201305UV02(request.getPRPAIN201305UV02());
NhinTargetSystemType target = new NhinTargetSystemType();
HomeCommunityType home = new HomeCommunityType();
home.setHomeCommunityId(t.getHcid());
target.setHomeCommunity(home);
target.setUrl(t.getUrl());
oProxyPRPAIN201305UVProxySecuredRequestType.setNhinTargetSystem(target);
ResponseParams params = new ResponseParams();
params.assertion = pdassertion;
params.origRequest = oProxyPRPAIN201305UVProxySecuredRequestType;
params.response = current;
// process response (store correlation and handle trust/verify mode)
current = new ResponseFactory().getResponseMode().processResponse(params);
// store the AA to HCID mapping
new PatientDiscovery201306Processor().storeMapping(current);
// aggregate the response
CommunityPRPAIN201306UV02ResponseType communityResponse = new CommunityPRPAIN201306UV02ResponseType();
communityResponse.setPRPAIN201306UV02(current);
cumulativeResponse.getCommunityResponse().add(communityResponse);
LOG.debug("PDProcessor::processPDResponse done count=" + count);
} catch (Exception ex) {
ExecutorServiceHelper.getInstance().outputCompleteException(ex);
throw ex;
}
}
}
| 49.632432 | 120 | 0.740688 |
f81daebf38b2266bebe0f0f0f0880d777cf83ca0 | 34 | non-sealed class C implements I {} | 34 | 34 | 0.764706 |
8f6c76ae11f90405e5c0b5eed3b045031eb36c53 | 10,880 | package com.wffwebdemo.wffwebdemoproject.page.template.users;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;
import com.webfirmframework.wffweb.server.page.BrowserPageContext;
import com.webfirmframework.wffweb.tag.html.AbstractHtml;
import com.webfirmframework.wffweb.tag.html.Br;
import com.webfirmframework.wffweb.tag.html.attribute.Type;
import com.webfirmframework.wffweb.tag.html.attribute.event.ServerAsyncMethod;
import com.webfirmframework.wffweb.tag.html.attribute.event.mouse.OnClick;
import com.webfirmframework.wffweb.tag.html.attribute.global.Style;
import com.webfirmframework.wffweb.tag.html.formatting.B;
import com.webfirmframework.wffweb.tag.html.formsandinputs.Button;
import com.webfirmframework.wffweb.tag.html.programming.Script;
import com.webfirmframework.wffweb.tag.html.stylesandsemantics.Div;
import com.webfirmframework.wffweb.tag.html.stylesandsemantics.StyleTag;
import com.webfirmframework.wffweb.tag.html.tables.TBody;
import com.webfirmframework.wffweb.tag.html.tables.Table;
import com.webfirmframework.wffweb.tag.html.tables.Td;
import com.webfirmframework.wffweb.tag.html.tables.Th;
import com.webfirmframework.wffweb.tag.html.tables.Tr;
import com.webfirmframework.wffweb.tag.htmlwff.NoTag;
import com.webfirmframework.wffweb.wffbm.data.WffBMObject;
import com.wffwebdemo.wffwebdemoproject.page.ServerLogPage;
import com.wffwebdemo.wffwebdemoproject.page.model.DocumentModel;
@SuppressWarnings("serial")
public class ListUsersTempate extends Div implements ServerAsyncMethod {
private static final Logger LOGGER = Logger
.getLogger(ListUsersTempate.class.getName());
private TBody tBody;
private DocumentModel documentModel;
private List<AbstractHtml> previousRows;
private int rowCount = 0;
private Button nextRowsButton;
private Button lazyNextRowsButton;
private Button markGreenButton;
private Button markVioletButton;
private Button removeColoumnStyleButton;
private Button removeColoumnStyleOneByOneButton;
private Style countryColumnStyle;
public ListUsersTempate(DocumentModel documentModel) {
super(null);
this.documentModel = documentModel;
countryColumnStyle = new Style("background:yellow;color:orange");
develop();
}
private void develop() {
new StyleTag(this) {
{
new NoTag(this, "table {\n font-family: arial, sans-serif;");
new NoTag(this, "border-collapse: collapse;\n width: 100%;");
new NoTag(this, "}\n\ntd, th {");
new NoTag(this,
"border: 1px solid #dddddd;\n text-align: left;");
new NoTag(this, "padding: 8px;\n}");
new NoTag(this,
"tr:nth-child(even) {\n background-color: #dddddd;");
new NoTag(this, "}");
}
};
//this way also you can execute JavaScript
//check browser console when clicking on list users button
new Script(this, new Type(Type.TEXT_JAVASCRIPT)) {
{
new NoTag(this, "console.log('list users template is added');");
}
};
new Div(this) {
{
new NoTag(null, "Users list");
}
};
new Br(this);
new Br(this);
nextRowsButton = new Button(this, new OnClick(this)) {
{
new B(this) {
{
new NoTag(this, "Next 25 rows");
}
};
}
};
new Br(this);
new Br(this);
lazyNextRowsButton = new Button(this, new OnClick(this)) {
{
new B(this) {
{
new NoTag(this, "Next 1000 rows as stream");
}
};
}
};
new Br(this);
new Br(this);
markGreenButton = new Button(this, new OnClick(this)) {
{
new B(this) {
{
new NoTag(this, "Mark column green");
}
};
}
};
new Br(this);
new Br(this);
markVioletButton = new Button(this, new OnClick(this)) {
{
new B(this) {
{
new NoTag(this, "Mark column violet");
}
};
}
};
new Br(this);
new Br(this);
removeColoumnStyleButton = new Button(this, new OnClick(this)) {
{
new B(this) {
{
new NoTag(this,
"Remove style from column all together");
}
};
}
};
new Br(this);
new Br(this);
removeColoumnStyleOneByOneButton = new Button(this, new OnClick(this)) {
{
new B(this) {
{
new NoTag(this, "Remove style attribute from column one by one");
}
};
}
};
new Br(this);
new Br(this);
new Table(this) {
{
tBody = new TBody(this) {
{
new Tr(this) {
{
new Th(this) {
{
new NoTag(this, "Company (会社)");
}
};
new Th(this) {
{
new NoTag(this, "Contact (接触)");
}
};
new Th(this) {
{
new NoTag(this, "Country (国)");
}
};
}
};
}
};
}
};
// initially add rows
addRows();
}
private void addRows() {
List<AbstractHtml> rows = new LinkedList<AbstractHtml>();
for (int i = 0; i < 25; i++) {
Tr tr = new Tr(null) {
{
rowCount++;
new Td(this) {
{
new NoTag(this, "Alfreds Futterkiste " + rowCount);
}
};
new Td(this) {
{
new NoTag(this, "Maria Anders " + rowCount);
}
};
new Td(this, countryColumnStyle) {
{
new NoTag(this, "Germany " + rowCount);
}
};
}
};
rows.add(tr);
}
if (previousRows != null) {
tBody.removeChildren(previousRows);
}
tBody.appendChildren(rows);
previousRows = rows;
}
private void addRowsAsStream() {
List<AbstractHtml> rows = new LinkedList<AbstractHtml>();
if (previousRows != null) {
tBody.removeChildren(previousRows);
}
for (int i = 0; i < 1000; i++) {
Tr tr = new Tr(tBody) {
{
rowCount++;
new Td(this) {
{
new NoTag(this, "Alfreds Futterkiste " + rowCount);
}
};
new Td(this) {
{
new NoTag(this, "Maria Anders " + rowCount);
}
};
new Td(this, countryColumnStyle) {
{
new NoTag(this, "Germany " + rowCount);
}
};
}
};
rows.add(tr);
}
previousRows = rows;
}
@Override
public WffBMObject asyncMethod(WffBMObject wffBMObject, Event event) {
if (nextRowsButton.equals(event.getSourceTag())) {
addRows();
displayInServerLogPage("nextRowsButton");
} else if (markGreenButton.equals(event.getSourceTag())) {
LOGGER.info("Mark column green");
countryColumnStyle.addCssProperties("background:green");
displayInServerLogPage("Mark column green");
} else if (markVioletButton.equals(event.getSourceTag())) {
LOGGER.info("Mark column violet");
countryColumnStyle.addCssProperties("background:violet");
displayInServerLogPage("Mark column violet");
} else if (removeColoumnStyleButton.equals(event.getSourceTag())) {
LOGGER.info("remove style all together");
countryColumnStyle.getCssProperties().clear();
displayInServerLogPage("remove style all together ");
} else if (removeColoumnStyleOneByOneButton
.equals(event.getSourceTag())) {
LOGGER.info("remove style attribyte one by one");
AbstractHtml[] ownerTags = countryColumnStyle.getOwnerTags();
try {
documentModel.getBrowserPage().holdPush();
for (AbstractHtml ownerTag : ownerTags) {
ownerTag.removeAttributes(
countryColumnStyle.getAttributeName());
}
} finally {
documentModel.getBrowserPage().unholdPush();
}
displayInServerLogPage("remove style atribyte one by one");
} else if (lazyNextRowsButton.equals(event.getSourceTag())) {
addRowsAsStream();
LOGGER.info("lazyNextRowsButton");
displayInServerLogPage("lazyNextRowsButton");
}
return null;
}
private void displayInServerLogPage(String msg) {
Object serverLogPageInstanceId = documentModel.getHttpSession()
.getAttribute("serverLogPageInstanceId");
if (serverLogPageInstanceId != null) {
ServerLogPage serverLogPage = (ServerLogPage) BrowserPageContext.INSTANCE
.getBrowserPage(serverLogPageInstanceId.toString());
if (serverLogPage != null) {
serverLogPage.log(msg);
}
}
}
}
| 31.536232 | 89 | 0.483456 |
d884112900202048abaf6ccce91f6a3cdd0a230e | 556 | package br.com.sysagro.repositories;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import br.com.sysagro.models.Fazenda;
public interface FazendaRepository extends JpaRepository<Fazenda, Long> {
@Query("select f from Fazenda f join fetch f.proprietario where f.nome like :descricao order by f.id")
List<Fazenda> findNomeContaining(String descricao);
@Query("select f from Fazenda f join fetch f.proprietario order by f.id")
List<Fazenda> findAll();
}
| 29.263158 | 103 | 0.791367 |
8805c85b9fb00203ce55c188fcce292815011f77 | 203 | package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
public class RedCrater extends LinearOpMode {
@Override
public void runOpMode() {
}
}
| 16.916667 | 60 | 0.753695 |
74a5c2984f95dce36ee1f7f4ad5b293f5df61514 | 5,014 | /*
* This file is generated by jOOQ.
*/
package com.yg.gqlwfdl.dataaccess.db.tables.records;
import com.yg.gqlwfdl.dataaccess.db.tables.CompanyPartnership;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record3;
import org.jooq.Row3;
import org.jooq.impl.UpdatableRecordImpl;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.11.2"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class CompanyPartnershipRecord extends UpdatableRecordImpl<CompanyPartnershipRecord> implements Record3<Long, Long, Long> {
private static final long serialVersionUID = -1052776363;
/**
* Setter for <code>public.company_partnership.id</code>.
*/
public void setId(Long value) {
set(0, value);
}
/**
* Getter for <code>public.company_partnership.id</code>.
*/
public Long getId() {
return (Long) get(0);
}
/**
* Setter for <code>public.company_partnership.company_a</code>.
*/
public void setCompanyA(Long value) {
set(1, value);
}
/**
* Getter for <code>public.company_partnership.company_a</code>.
*/
public Long getCompanyA() {
return (Long) get(1);
}
/**
* Setter for <code>public.company_partnership.company_b</code>.
*/
public void setCompanyB(Long value) {
set(2, value);
}
/**
* Getter for <code>public.company_partnership.company_b</code>.
*/
public Long getCompanyB() {
return (Long) get(2);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Record1<Long> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record3 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row3<Long, Long, Long> fieldsRow() {
return (Row3) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row3<Long, Long, Long> valuesRow() {
return (Row3) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<Long> field1() {
return CompanyPartnership.COMPANY_PARTNERSHIP.ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Long> field2() {
return CompanyPartnership.COMPANY_PARTNERSHIP.COMPANY_A;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Long> field3() {
return CompanyPartnership.COMPANY_PARTNERSHIP.COMPANY_B;
}
/**
* {@inheritDoc}
*/
@Override
public Long component1() {
return getId();
}
/**
* {@inheritDoc}
*/
@Override
public Long component2() {
return getCompanyA();
}
/**
* {@inheritDoc}
*/
@Override
public Long component3() {
return getCompanyB();
}
/**
* {@inheritDoc}
*/
@Override
public Long value1() {
return getId();
}
/**
* {@inheritDoc}
*/
@Override
public Long value2() {
return getCompanyA();
}
/**
* {@inheritDoc}
*/
@Override
public Long value3() {
return getCompanyB();
}
/**
* {@inheritDoc}
*/
@Override
public CompanyPartnershipRecord value1(Long value) {
setId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public CompanyPartnershipRecord value2(Long value) {
setCompanyA(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public CompanyPartnershipRecord value3(Long value) {
setCompanyB(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public CompanyPartnershipRecord values(Long value1, Long value2, Long value3) {
value1(value1);
value2(value2);
value3(value3);
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached CompanyPartnershipRecord
*/
public CompanyPartnershipRecord() {
super(CompanyPartnership.COMPANY_PARTNERSHIP);
}
/**
* Create a detached, initialised CompanyPartnershipRecord
*/
public CompanyPartnershipRecord(Long id, Long companyA, Long companyB) {
super(CompanyPartnership.COMPANY_PARTNERSHIP);
set(0, id);
set(1, companyA);
set(2, companyB);
}
}
| 20.979079 | 130 | 0.515756 |
71a59505f08043ba4601db5bd1f0becf96ebb777 | 5,438 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.google.android.gms.wearable.internal;
import android.os.Parcel;
import com.google.android.gms.common.internal.safeparcel.zzb;
import com.google.android.gms.common.internal.safeparcel.zzc;
// Referenced classes of package com.google.android.gms.wearable.internal:
// zzco
public class zzcp
implements android.os.Parcelable.Creator
{
public zzcp()
{
// 0 0:aload_0
// 1 1:invokespecial #11 <Method void Object()>
// 2 4:return
}
static void zza(zzco zzco1, Parcel parcel, int i)
{
i = zzc.zzaZ(parcel);
// 0 0:aload_1
// 1 1:invokestatic #20 <Method int zzc.zzaZ(Parcel)>
// 2 4:istore_2
zzc.zzc(parcel, 2, zzco1.statusCode);
// 3 5:aload_1
// 4 6:iconst_2
// 5 7:aload_0
// 6 8:getfield #26 <Field int zzco.statusCode>
// 7 11:invokestatic #30 <Method void zzc.zzc(Parcel, int, int)>
zzc.zzc(parcel, 3, zzco1.zzbhU);
// 8 14:aload_1
// 9 15:iconst_3
// 10 16:aload_0
// 11 17:getfield #33 <Field int zzco.zzbhU>
// 12 20:invokestatic #30 <Method void zzc.zzc(Parcel, int, int)>
zzc.zzJ(parcel, i);
// 13 23:aload_1
// 14 24:iload_2
// 15 25:invokestatic #37 <Method void zzc.zzJ(Parcel, int)>
// 16 28:return
}
public Object createFromParcel(Parcel parcel)
{
return ((Object) (zzlu(parcel)));
// 0 0:aload_0
// 1 1:aload_1
// 2 2:invokevirtual #43 <Method zzco zzlu(Parcel)>
// 3 5:areturn
}
public Object[] newArray(int i)
{
return ((Object []) (zzpW(i)));
// 0 0:aload_0
// 1 1:iload_1
// 2 2:invokevirtual #49 <Method zzco[] zzpW(int)>
// 3 5:areturn
}
public zzco zzlu(Parcel parcel)
{
int k = zzb.zzaY(parcel);
// 0 0:aload_1
// 1 1:invokestatic #54 <Method int zzb.zzaY(Parcel)>
// 2 4:istore 4
int j = 0;
// 3 6:iconst_0
// 4 7:istore_3
int i = 0;
// 5 8:iconst_0
// 6 9:istore_2
do
if(parcel.dataPosition() < k)
//* 7 10:aload_1
//* 8 11:invokevirtual #60 <Method int Parcel.dataPosition()>
//* 9 14:iload 4
//* 10 16:icmpge 88
{
int l = zzb.zzaX(parcel);
// 11 19:aload_1
// 12 20:invokestatic #63 <Method int zzb.zzaX(Parcel)>
// 13 23:istore 5
switch(zzb.zzdc(l))
//* 14 25:iload 5
//* 15 27:invokestatic #67 <Method int zzb.zzdc(int)>
{
//* 16 30:lookupswitch 2: default 56
// 2: 59
// 3: 69
//* 17 56:goto 79
case 2: // '\002'
j = zzb.zzg(parcel, l);
// 18 59:aload_1
// 19 60:iload 5
// 20 62:invokestatic #71 <Method int zzb.zzg(Parcel, int)>
// 21 65:istore_3
break;
//* 22 66:goto 85
case 3: // '\003'
i = zzb.zzg(parcel, l);
// 23 69:aload_1
// 24 70:iload 5
// 25 72:invokestatic #71 <Method int zzb.zzg(Parcel, int)>
// 26 75:istore_2
break;
//* 27 76:goto 85
default:
zzb.zzb(parcel, l);
// 28 79:aload_1
// 29 80:iload 5
// 30 82:invokestatic #74 <Method void zzb.zzb(Parcel, int)>
break;
}
} else
//* 31 85:goto 10
if(parcel.dataPosition() != k)
//* 32 88:aload_1
//* 33 89:invokevirtual #60 <Method int Parcel.dataPosition()>
//* 34 92:iload 4
//* 35 94:icmpeq 128
throw new com.google.android.gms.common.internal.safeparcel.zzb.zza((new StringBuilder(37)).append("Overread allowed size end=").append(k).toString(), parcel);
// 36 97:new #76 <Class com.google.android.gms.common.internal.safeparcel.zzb$zza>
// 37 100:dup
// 38 101:new #78 <Class StringBuilder>
// 39 104:dup
// 40 105:bipush 37
// 41 107:invokespecial #81 <Method void StringBuilder(int)>
// 42 110:ldc1 #83 <String "Overread allowed size end=">
// 43 112:invokevirtual #87 <Method StringBuilder StringBuilder.append(String)>
// 44 115:iload 4
// 45 117:invokevirtual #90 <Method StringBuilder StringBuilder.append(int)>
// 46 120:invokevirtual #94 <Method String StringBuilder.toString()>
// 47 123:aload_1
// 48 124:invokespecial #97 <Method void com.google.android.gms.common.internal.safeparcel.zzb$zza(String, Parcel)>
// 49 127:athrow
else
return new zzco(j, i);
// 50 128:new #22 <Class zzco>
// 51 131:dup
// 52 132:iload_3
// 53 133:iload_2
// 54 134:invokespecial #100 <Method void zzco(int, int)>
// 55 137:areturn
while(true);
}
public zzco[] zzpW(int i)
{
return new zzco[i];
// 0 0:iload_1
// 1 1:anewarray zzco[]
// 2 4:areturn
}
}
| 32.957576 | 163 | 0.522986 |
ccfff96abf7e610cb33e34a2331e8e7465cb5ab7 | 797 | package com.example.a68.databaseapplication;
import java.io.Serializable;
public class Student implements Serializable {
private String name;
private String phone;
private String career;
public Student() {
}
public Student(String name, String phone, String career) {
this.name = name;
this.phone = phone;
this.career = career;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getCareer() {
return career;
}
public void setCareer(String career) {
this.career = career;
}
}
| 17.711111 | 62 | 0.602258 |
8773070b1b3fd55392f2f1a4916cbc7ab88b0d5a | 299 | package dtt.cms.app.common;
public class ResourceMapping {
public final static String LOGIN_PAGE_URL = "/login";
public final static String LOGIN_PAGE_RESOURCE = "login/index";
public static final String HOME_PAGE_URL = "/";
public static final String HOME_PAGE_RESOURCE = "/home/index";
}
| 27.181818 | 64 | 0.762542 |
dca0025f54bb78681bf2e1216c2adbe3d93d281d | 2,903 | package com.ibm.fsd.sba.training.repository;
import com.ibm.fsd.sba.training.entity.Trainings;
import com.ibm.fsd.sba.training.model.TrainingsDto;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface TrainingRepository extends JpaRepository<Trainings, Integer> {
List<Trainings> findByMentorId(Long id);
List<Trainings> findByUserId(Long id);
List<Trainings> findByStatus(Integer status);
@Query(value = "SELECT t.`ID`," +
" t.`USER_ID`," +
" t.`MENTOR_ID`," +
" t.`SKILL_ID`," +
" t.`STATUS`," +
" t.`PROGRESS`," +
" t.`RATING`," +
" t.`START_DATE`," +
" t.`END_DATE`," +
" t.`START_TIME`," +
" t.`END_TIME`" +
" FROM Trainings t " +
" WHERE (t.skill_id = :skillId or :skillId is null)" +
" and (t.start_time < :startTime or :startTime is null or :startTime = '')" +
" and (t.end_time < :endTime or :endTime is null or :endTime = '')",
nativeQuery = true)
List<Trainings> findTrainings(@Param("skillId") Long id,
@Param("startTime") String startTime,
@Param("endTime") String endTime);
@Query(value = "SELECT t.`ID`," +
" t.`USER_ID`," +
" t.`MENTOR_ID`," +
" t.`SKILL_ID`," +
" t.`STATUS`," +
" t.`PROGRESS`," +
" t.`RATING`," +
" t.`START_DATE`," +
" t.`END_DATE`," +
" t.`START_TIME`," +
" t.`END_TIME`" +
" FROM Trainings t " +
" WHERE (t.MENTOR_ID = :userId or :userId is null)" +
" and (t.STATUS = :status or :status is null)" ,
nativeQuery = true)
List<Trainings> findConfirm(@Param("userId") Long userId,
@Param("status") Integer status);
@Query(value = "SELECT t.`ID`," +
" t.`USER_ID`," +
" t.`MENTOR_ID`," +
" t.`SKILL_ID`," +
" t.`STATUS`," +
" t.`PROGRESS`," +
" t.`RATING`," +
" t.`START_DATE`," +
" t.`END_DATE`," +
" t.`START_TIME`," +
" t.`END_TIME`" +
" FROM Trainings t " +
" WHERE (t.MENTOR_ID = :mentorId or :mentorId is null)" +
" and (t.USER_ID = :userId or :userId is null)",
nativeQuery = true)
List<Trainings> findTrainingByUserId(@Param("userId") Long userId, @Param("mentorId") Long mentorId);
}
| 39.22973 | 105 | 0.495005 |
f107dc8438984a815168d5f596aa9c029efa27db | 923 | package com.builtbroken.atomic.config.mods;
import net.minecraftforge.common.config.Config;
/**
*
* Created by Dark(DarkGuardsman, Robert) on 9/14/2018.
*/
public class ConfigIC2
{
@Config.Name("enable_recipes")
@Config.Comment("Enable recipes that offer alternatives using IC2 items")
@Config.LangKey("config.atomicscience:mods.ic2.recipes.title")
public boolean ENABLE_RECIPES = true;
@Config.Name("fe_per_eu")
@Config.Comment("How much (FE) Forge energy to exchange for (EU) IC2 energy")
@Config.LangKey("config.atomicscience:mods.ic2.fe_per_eu.title")
@Config.RangeInt(min = 0)
public double FE_PER_EU = 4; //Matched with Mekanism
@Config.Name("enable_ic2")
@Config.Comment("Set to true to enable IC2 (EU) power support. Requires restart to take full effect.")
@Config.LangKey("config.atomicscience:mods.ic2.power.title")
public boolean ENABLE_POWER = true;
}
| 34.185185 | 106 | 0.72481 |
374775f1b3fbb346fb7199c4198e0264d0356ca9 | 3,102 | /*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 4893959 8013069
* @summary basic test for PBE MAC algorithms.
* @author Valerie Peng
*/
import java.io.PrintStream;
import java.util.*;
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class HmacPBESHA1 {
private static final String[] MAC_ALGOS = {
"HmacPBESHA1",
"PBEWithHmacSHA1",
"PBEWithHmacSHA224",
"PBEWithHmacSHA256",
"PBEWithHmacSHA384",
"PBEWithHmacSHA512"
};
private static final int[] MAC_LENGTHS = { 20, 20, 28, 32, 48, 64 };
private static final String KEY_ALGO = "PBE";
private static final String PROVIDER = "SunJCE";
private static SecretKey key = null;
public static void main(String argv[]) throws Exception {
for (int i = 0; i < MAC_ALGOS.length; i++) {
runtest(MAC_ALGOS[i], MAC_LENGTHS[i]);
}
System.out.println("\nTest Passed");
}
private static void runtest(String algo, int length) throws Exception {
System.out.println("Testing: " + algo);
if (key == null) {
char[] password = { 't', 'e', 's', 't' };
PBEKeySpec keySpec = new PBEKeySpec(password);
SecretKeyFactory kf =
SecretKeyFactory.getInstance(KEY_ALGO, PROVIDER);
key = kf.generateSecret(keySpec);
}
Mac mac = Mac.getInstance(algo, PROVIDER);
byte[] plainText = new byte[30];
PBEParameterSpec spec =
new PBEParameterSpec("saltValue".getBytes(), 250);
mac.init(key, spec);
mac.update(plainText);
byte[] value1 = mac.doFinal();
if (value1.length != length) {
throw new Exception("incorrect MAC output length, expected " +
length + ", got " + value1.length);
}
mac.update(plainText);
byte[] value2 = mac.doFinal();
if (!Arrays.equals(value1, value2)) {
throw new Exception("generated different MAC outputs");
}
}
}
| 35.655172 | 79 | 0.644423 |
5748f8395f382f326318f9d94036ab776b508c21 | 1,551 | /*
* Copyright 2012 Evgeny Dolganov ([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 com.gf.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.gf.Handler;
import com.gf.Interceptor;
/**
* Annotation for injecting context's object into handler.
* Use it for <tt>Handlers</tt>, <tt>Interceptors</tt>, <tt>Filters</tt>.
* <p>Example:
* <pre>
*
* @Mapping(SomeAction.class)
* public class SomeHandler extends Handler<SomeAction>{
*
* @Inject
* SomeService service;
*
* @Override
* public void invoke(SomeAction action) throws Exception {
* service.someMethod();
* }
* }
* </pre>
*
* @author Evgeny Dolganov
* @see com.gf.core.Engine#addToContext(Object)
* @see Handler
* @see Interceptor
* @see Filter
*/
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Inject {
}
| 27.696429 | 75 | 0.717602 |
85a19d93f09ee0101c1dece6a9e65b0f2e39d65e | 1,589 | /*
* Copyright 2013 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.optaplanner.core.impl.localsearch.decider.acceptor.stepcountinghillclimbing;
import org.optaplanner.core.api.score.Score;
/**
* Determines what increment the counter of Step Counting Hill Climbing.
*/
public enum StepCountingHillClimbingType {
/**
* Every selected move is counted.
*/
SELECTED_MOVE,
/**
* Every accepted move is counted.
* <p/>
* Note: If acceptedCountLimit = 1, then this behaves exactly the same as {link #STEP}.
*/
ACCEPTED_MOVE,
/**
* Every step is counted. Every step was always an accepted move. This is the default.
* <p/>
* Note: If acceptedCountLimit = 1, then this behaves exactly the same as {link #ACCEPTED_MOVE}.
*/
STEP,
/**
* Every step that equals or improves the {@link Score} of the last step is counted.
*/
EQUAL_OR_IMPROVING_STEP,
/**
* Every step that improves the {@link Score} of the last step is counted.
*/
IMPROVING_STEP;
}
| 31.156863 | 100 | 0.687225 |
3f876a18b0d0d18868d8ed71b13611c1fdcffa9d | 2,959 | package codepath.kaughlinpractice.fridgefone.model;
import android.util.Log;
import com.parse.ParseClassName;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.SaveCallback;
import org.json.JSONException;
import org.json.JSONObject;
import codepath.kaughlinpractice.fridgefone.AddItemAdapter;
@ParseClassName("Item")
public class Item extends ParseObject {
private static final String KEY_NAME = "name";
private static final String KEY_IMAGE_URL = "imageURL";
private static final String ingredient_base_URL = "https://spoonacular.com/cdn/ingredients_100x100/";
public Item() { }
public String getName() {
return getString(KEY_NAME);
}
public void setName(String name) {
put(KEY_NAME, name);
}
public String getImageURL() {
return getString(KEY_IMAGE_URL);
}
public void setImageURL(String image) {
put(KEY_IMAGE_URL, image);
}
public static class Query extends ParseQuery<Item> {
public Query() {
super(Item.class);
}
public Query getFridgeItems() {
return this;
}
}
// For Adding Items
public static Item fromJSON(JSONObject jsonObject) throws JSONException {
final Item item = new Item();
item.setName(jsonObject.getString("name"));
String imageName = jsonObject.getString("image");
String url = ingredient_base_URL + imageName;
item.setImageURL(url);
item.saveInBackground(new SaveCallback() {
@Override
public void done(ParseException e) {
if (e == null) {
} else {
Log.d("Item", "Error");
e.printStackTrace();
}
}
});
return item;
}
// For AutoComplete
public static Item autoFromJSON(JSONObject jsonObject, AddItemAdapter addItemAdapter) throws JSONException {
final Item item = new Item();
String capitalName = capitalizeString(jsonObject.getString("name"));
item.setName(capitalName);
String imageName = jsonObject.getString("image");
String url = ingredient_base_URL + imageName;
item.setImageURL(url);
// Update the adapter
addItemAdapter.add(item);
addItemAdapter.notifyDataSetChanged();
return item;
}
public static String capitalizeString(String recipeName) {
String capitalName = "";
String[] strArray = recipeName.split(" ");
for (String s : strArray) {
String word = s.substring(0, 1).toUpperCase() + s.substring(1);
capitalName += word + " ";
}
// Take off the extra space
capitalName = capitalName.substring(0,capitalName.length()-1);
return capitalName;
}
@Override
public String toString() {
return getName();
}
}
| 28.180952 | 112 | 0.624535 |
b36645f459db967be7363f55ab1278d8d50300cc | 15,399 | package harlan.paradoxie.dizzypassword.activity;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.dou361.dialogui.DialogUIUtils;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.weasel.secret.common.domain.Secret;
import com.weasel.secret.common.domain.Subject;
import com.weasel.secret.common.helper.EntryptionHelper;
import org.greenrobot.eventbus.EventBus;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import harlan.paradoxie.dizzypassword.R;
import harlan.paradoxie.dizzypassword.adapter.LSwipeAdapter;
import harlan.paradoxie.dizzypassword.api.AllApi;
import harlan.paradoxie.dizzypassword.db.help.dbutlis.SecretHelp;
import harlan.paradoxie.dizzypassword.db.help.dbutlis.SecretListHelp;
import harlan.paradoxie.dizzypassword.dbdomain.SecretList;
import harlan.paradoxie.dizzypassword.domian.EditSecretDatail;
import harlan.paradoxie.dizzypassword.domian.ServerSecret;
import harlan.paradoxie.dizzypassword.domian.UpdataView;
import harlan.paradoxie.dizzypassword.help.Date_U;
import harlan.paradoxie.dizzypassword.help.GsonUtil;
import harlan.paradoxie.dizzypassword.help.ObjectUtils;
import harlan.paradoxie.dizzypassword.util.SPUtils;
import harlan.paradoxie.dizzypassword.util.StringUtils;
import harlan.paradoxie.dizzypassword.widget.CustListView;
public class EditSecret extends Activity {
@Bind(R.id.back)
TextView back;
@Bind(R.id.title)
TextView title;
@Bind(R.id.secrettitle)
EditText secrettitle;
@Bind(R.id.url)
EditText url;
@Bind(R.id.edit_listview)
CustListView editListview;
String json;
String location = "0";
LSwipeAdapter adapter;
String key;
@Bind(R.id.editok)
Button editok;
Dialog dialog;
harlan.paradoxie.dizzypassword.dbdomain.Secret subjectsBean;
@Bind(R.id.account)
EditText account;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_secret);
ButterKnife.bind(this);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle != null) {
json = bundle.getString("json");
location = bundle.getString("location");
key = bundle.getString("key");
Log.e("backinfo", "json:" + json);
Log.e("backinfo", "location:" + location);
Log.e("backinfo", "key:" + key);
subjectsBean = GsonUtil.getGsonInstance().fromJson(json, harlan.paradoxie.dizzypassword.dbdomain.Secret.class);
secrettitle.setText(subjectsBean.getTitle());
account.setText(subjectsBean.getAccount());
url.setText(subjectsBean.getUrl());
/* if(location.equals("0")){
adapter = new LSwipeAdapter(EditSecret.this, subjectsBean.getSecretLists(), key);
}else{*/
adapter = new LSwipeAdapter(EditSecret.this, subjectsBean.getSecrets(), key);
// }
editListview.setAdapter(adapter);
}
}
@OnClick({R.id.editok, R.id.back})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.back:
finish();
break;
case R.id.editok:
String eorre = isEmptyEorre();
if (StringUtils.isEmpty(secrettitle.getText().toString().trim())) {
Toast.makeText(EditSecret.this, "请输入标题", Toast.LENGTH_LONG).show();
} else if (StringUtils.isEmpty(account.getText().toString().trim())) {
Toast.makeText(EditSecret.this, "请输入账号", Toast.LENGTH_LONG).show();
} else if (!StringUtils.isEmpty(eorre)) {
Toast.makeText(EditSecret.this, eorre, Toast.LENGTH_LONG).show();
} else {
if (!StringUtils.isEmpty(SPUtils.getInstance().getString("username", ""))) {
Subject subject = new Subject();
subject.setTitle(secrettitle.getText().toString().trim());
subject.setId(subjectsBean.getId());
subject.setUrl(url.getText().toString().trim());
// Log.e("backinfo","时间格式:"+Date_U.getNowDate());
subject.setUpdateTime(Date_U.getNowDate());
subject.setAccount(account.getText().toString());
List<SecretList> secrets = new ArrayList<SecretList>();
List<Secret> secretList = new ArrayList<>();
Type type = new TypeToken<ArrayList<SecretList>>() {
}.getType();
secrets = GsonUtil.getGsonInstance().fromJson(GsonUtil.getGsonInstance().toJson(adapter.getData()), type);
for (int i = 0; i < secrets.size(); i++) {
Secret secret = new Secret();
secret.setId(secrets.get(i).getId());
secret.setName(secrets.get(i).getName());
secret.setValue(secrets.get(i).getValue());
/* if(secrets.get(i).getSubjectId()!=null){
secret.setSubjectId(secrets.get(i).getSubjectId());
}*/
secretList.add(secret);
}
subject.setVersion(subjectsBean.getVersion());
subject.setSecrets(secretList);
Log.e("backinfo", "未加密前的数据:" + GsonUtil.getGsonInstance().toJson(subject));
try {
Log.e("backinfo", "key:" + key);
subject.entryptAllSecret(key);
Sava(subject);
} catch (Exception e) {
Log.e("backinfo", "加密出错");
e.printStackTrace();
}
Log.e("backinfo", "加密后的数据:" + GsonUtil.getGsonInstance().toJson(subject));
} else {
updateDB(false);
UpdataView updataView = new UpdataView();
updataView.setView("db");
EventBus.getDefault().post(updataView);
finish();
Toast.makeText(EditSecret.this, "修改成功", Toast.LENGTH_LONG).show();
}
}
break;
}
}
/**
* setCloud表示是否已经同步,true表示已经同步了,false 不同步
*/
private void updateDB(boolean setCloud) {
harlan.paradoxie.dizzypassword.dbdomain.Secret secret = new harlan.paradoxie.dizzypassword.dbdomain.Secret();
secret.setUrl(url.getText().toString().trim());
if (subjectsBean.getId() != null) {
secret.setId(subjectsBean.getId());
}
secret.setSid(subjectsBean.getSid());
secret.setTitle(secrettitle.getText().toString().trim());
secret.setAccount(account.getText().toString().trim());
secret.setCloud(setCloud);
secret.setUpdateTime(Date_U.getNowDate());
SecretHelp.update(secret);
SecretListHelp.delete(subjectsBean.getSid());
List<SecretList> secrets;
Type type = new TypeToken<ArrayList<SecretList>>() {
}.getType();
secrets = GsonUtil.getGsonInstance().fromJson(GsonUtil.getGsonInstance().toJson(adapter.getData()), type);
// Log.e("backinfo","编辑:"+GsonUtil.getGsonInstance().toJson(adapter.getData()));
secret.setSecrets(secrets);
Iterator var2 = secret.getSecrets().iterator();
while (var2.hasNext()) {
SecretList secretList = (SecretList) var2.next();
try {
secretList.setValue(EntryptionHelper.encrypt(key, secretList.getValue()));
secretList.setSecretId(subjectsBean.getSid());
} catch (Exception e) {
e.printStackTrace();
}
}
SecretListHelp.insertList(secrets);
// SecretHelp.update(secret, secret.getSecrets());
}
private String isEmptyEorre() {
try {
Log.e("backinfo", "数据:" + GsonUtil.getGsonInstance().toJson(adapter.getData()));
for (int i = 0; i < adapter.getData().size(); i++) {
if (StringUtils.isEmpty((String) ObjectUtils.getValueByKey(adapter.getData().get(i), "name"))) {
return "请输入或自定义第" + (i + 1) + "项目的密码类型";
} else if (StringUtils.isEmpty((String) ObjectUtils.getValueByKey(adapter.getData().get(i), "value"))) {
return "请输入第" + (i + 1) + "项目的密码";
}
}
return "";
} catch (Exception e) {
return "获取数据出错";
}
}
private void Sava(Subject subject) {
dialog = DialogUIUtils.showLoading(EditSecret.this, "正在修改...", true, true, false, true).show();
Log.e("backinfo", "上传数据:" + GsonUtil.getGsonInstance().toJson(subject));
OkGo.<String>post(AllApi.save).upJson(GsonUtil.getGsonInstance().toJson(subject)).execute(new StringCallback() {
@Override
public void onSuccess(Response<String> response) {
Log.e("backinfo", "修改数据:" + response.body());
try {
EditSecretDatail editSecretDatail = GsonUtil.fromjson(response.body(), EditSecretDatail.class);
if ("0000".equals(editSecretDatail.getCode())) {
editSecretDatail.getBody().setSid(subjectsBean.getSid());
SecretHelp.update(editSecretDatail.getBody());
List<SecretList> secretLists = new ArrayList<>();
for (int i = 0; i < editSecretDatail.getBody().getSecrets().size(); i++) {
SecretList secretList = new SecretList();
secretList.setSid(SecretListHelp.Getsid(editSecretDatail.getBody().getSecrets().get(i).getId()));
secretList.setId(editSecretDatail.getBody().getSecrets().get(i).getId());
secretList.setName(editSecretDatail.getBody().getSecrets().get(i).getName());
secretList.setSecretId(subjectsBean.getSecrets().get(i).getSecretId());
secretList.setValue(editSecretDatail.getBody().getSecrets().get(i).getValue());
secretList.setSubjectId(editSecretDatail.getBody().getSecrets().get(i).getSubjectId());
secretLists.add(secretList);
// editSecretDatail.getBody().getSecrets().get(i).setSid(SecretListHelp.Getsid(editSecretDatail.getBody().getSecrets().get(i).getId()));
}
SecretListHelp.updateList(secretLists);
UpdataView updataView = new UpdataView();
updataView.setView("db");
EventBus.getDefault().post(updataView);
finish();
}
Toast.makeText(EditSecret.this, editSecretDatail.getMessage(), Toast.LENGTH_LONG).show();
/* if ("false".equals(response.headers().get("logined"))) {
Intent intent = new Intent(EditSecret.this, Login.class);
SPUtils.getInstance().remove("username");
EventBus.getDefault().post(false);
startActivity(intent);
} else {
Toast.makeText(EditSecret.this, "添加成功", Toast.LENGTH_LONG).show();
dialog.dismiss();
harlan.paradoxie.dizzypassword.dbdomain.Secret secret = new harlan.paradoxie.dizzypassword.dbdomain.Secret();
secret.setUrl(serverSecret.getUrl());
secret.setId(serverSecret.getId());
secret.setSid(subjectsBean.getSid());
secret.setTitle(serverSecret.getTitle());
secret.setCloud(true);
secret.setAccount(serverSecret.getAccount());
secret.setUpdateTime(Date_U.getNowDate());
SecretHelp.update(secret);
SecretListHelp.delete(subjectsBean.getSid());
List<SecretList> secrets = new ArrayList<SecretList>();
Type type = new TypeToken<ArrayList<SecretList>>() {
}.getType();
// secrets = GsonUtil.getGsonInstance().fromJson(GsonUtil.getGsonInstance().toJson(adapter.getData()), type);
Log.e("backinfo", "编辑:" + GsonUtil.getGsonInstance().toJson(secrets));
// secret.setSecrets(secrets);
for (int i = 0; i < serverSecret.getSecrets().size(); i++) {
SecretList secretList = new SecretList();
secretList.setSubjectId(serverSecret.getSecrets().get(i).getSubjectId());
secretList.setValue(serverSecret.getSecrets().get(i).getValue());
secretList.setId(serverSecret.getSecrets().get(i).getId());
secretList.setName(serverSecret.getSecrets().get(i).getName());
secretList.setSecretId(subjectsBean.getSid());
secrets.add(secretList);
}
secret.setSecrets(secrets);
Log.e("backinfo", "插入数据库数据:" + GsonUtil.getGsonInstance().toJson(secret));
SecretListHelp.insertList(secrets);
UpdataView updataView = new UpdataView();
updataView.setView("db");
EventBus.getDefault().post(updataView);
finish();
}*/
} catch (Exception e) {
Toast.makeText(EditSecret.this, "解析出错", Toast.LENGTH_LONG).show();
Log.e("backinfo", e.getMessage());
e.printStackTrace();
}
}
@Override
public void onFinish() {
dialog.dismiss();
super.onFinish();
}
@Override
public void onError(Response<String> response) {
Log.e("backinfo", "修改出错");
updateDB(false);
UpdataView updataView = new UpdataView();
updataView.setView("db");
EventBus.getDefault().post(updataView);
finish();
super.onError(response);
}
});
}
}
| 47.091743 | 163 | 0.557309 |
392752cddbd37fa33f0d017419bdae9f76fd560f | 3,619 | package com.example.valuepaljava.config;
import com.example.valuepaljava.auth.ApplicationUserService;
import com.example.valuepaljava.jwt.JwtAuthenticationFilter;
import com.example.valuepaljava.jwt.JwtTokenVerifier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final PasswordEncoder passwordEncoder;
private final ApplicationUserService applicationUserService;
@Autowired
public SecurityConfig(PasswordEncoder passwordEncoder,
ApplicationUserService applicationUserService) {
this.passwordEncoder = passwordEncoder;
this.applicationUserService = applicationUserService;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().headers();
http
.csrf().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.addFilter(new JwtAuthenticationFilter(authenticationManager()))
.addFilterAfter(new JwtTokenVerifier(), JwtAuthenticationFilter.class)
.authorizeRequests()
// .antMatchers("/calls/**", "/users/**")
// .hasRole("STUDENT")
// .antMatchers("/test")
// .hasRole("TEST")
// .antMatchers("/testTwo")
// .hasRole("TWO")
.antMatchers("/**/**")
// .hasRole("ADMIN")
// .anyRequest().authenticated();
.permitAll();
// .antMatchers(HttpMethod.GET, "/**")
// .hasRole("STUDENT")
// .antMatchers(HttpMethod.POST, "/**")
// .hasRole("STUDENT")
// .anyRequest()
// .authenticated();
}
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/h2-console/**");
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(daoAuthenticationProvider());
}
@Bean
public DaoAuthenticationProvider daoAuthenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(passwordEncoder);
provider.setUserDetailsService(applicationUserService);
return provider;
}
}
| 41.125 | 107 | 0.687206 |
18ecab5ce0d2fca418daa4dc157cf4ef9edf863c | 207 | package me.philcali.rss.api.ompl;
public interface IOutline extends IOutlineContainer {
String getType();
String getTitle();
String getText();
String getHtmlUrl();
String getXmlUrl();
}
| 20.7 | 53 | 0.700483 |
2f21cd7bcb9f408c38a832f8c11cfaadb20150ac | 1,868 | package space.dubovitsky.hibernate.dao.impl;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.java.Log;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import space.dubovitsky.hibernate.dao.CourseDao;
import space.dubovitsky.hibernate.model.Course;
import java.util.List;
@Log
@Transactional
@Getter @Setter
@Repository(value = "courseDao")
public class HibernateCourseDao implements CourseDao {
@Autowired //! Это как @Autowired, но из пакета javax.annotation
private SessionFactory sessionFactory;
@Override
@Transactional(readOnly = true)
public List<Course> findAllCourses() {
List courseList = sessionFactory.getCurrentSession()
.createQuery("from Course c").list(); //! Регистр имеет значение(Сourse или course) HQL! И мы работаем не с таблицами уже, а с сущностями
return courseList;
}
@Override
@Transactional(readOnly = true)
public Course getCourseById(int id) {
log.info(String.format("Invoke method %s with args[]", "getCourseById", id));
Course courseById = sessionFactory.getCurrentSession().byId(Course.class).load(id);
return courseById;
}
@Override
public void deleteCourseById(int id) {
Course course = new Course();
course.setId(id);
sessionFactory.getCurrentSession().delete(course);
log.info(String.format("Course %s with id %d removed successfully", course, id));
}
@Override
public void addCourse(Course course) {
sessionFactory.getCurrentSession().save(course);
}
@Override
public void updateCourse(Course course) {
sessionFactory.getCurrentSession().update(course);
}
}
| 31.661017 | 153 | 0.718415 |
12ebf9192f049a01cca1dcfd8ae13bcb3498c13a | 4,194 | /*
* Copyright (C) 2004-2016 L2J DataPack
*
* This file is part of L2J DataPack.
*
* L2J DataPack is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* L2J DataPack is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package quests.Q00166_MassOfDarkness;
import java.util.HashMap;
import java.util.Map;
import com.l2jserver.gameserver.enums.Race;
import com.l2jserver.gameserver.model.actor.L2Npc;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
import com.l2jserver.gameserver.model.quest.Quest;
import com.l2jserver.gameserver.model.quest.QuestState;
import com.l2jserver.gameserver.model.quest.State;
import com.l2jserver.gameserver.network.NpcStringId;
/**
* Mass of Darkness (166)
* @author xban1x
*/
public class Q00166_MassOfDarkness extends Quest
{
// NPCs
private static final int UNDRIAS = 30130;
private static final int IRIA = 30135;
private static final int DORANKUS = 30139;
private static final int TRUDY = 30143;
// Items
private static final int UNDRIAS_LETTER = 1088;
private static final int CEREMONIAL_DAGGER = 1089;
private static final int DREVIANT_WINE = 1090;
private static final int GARMIELS_SCRIPTURE = 1091;
// Misc
private static final int MIN_LVL = 2;
private static final Map<Integer, Integer> NPCs = new HashMap<>();
static
{
NPCs.put(IRIA, CEREMONIAL_DAGGER);
NPCs.put(DORANKUS, DREVIANT_WINE);
NPCs.put(TRUDY, GARMIELS_SCRIPTURE);
}
public Q00166_MassOfDarkness()
{
super(166, Q00166_MassOfDarkness.class.getSimpleName(), "Mass of Darkness");
addStartNpc(UNDRIAS);
addTalkId(UNDRIAS, IRIA, DORANKUS, TRUDY);
registerQuestItems(UNDRIAS_LETTER, CEREMONIAL_DAGGER, DREVIANT_WINE, GARMIELS_SCRIPTURE);
}
@Override
public String onAdvEvent(String event, L2Npc npc, L2PcInstance player)
{
final QuestState st = getQuestState(player, false);
if ((st != null) && event.equals("30130-03.htm"))
{
st.startQuest();
st.giveItems(UNDRIAS_LETTER, 1);
return event;
}
return null;
}
@Override
public String onTalk(L2Npc npc, L2PcInstance player)
{
final QuestState st = getQuestState(player, true);
String htmltext = getNoQuestMsg(player);
if (st != null)
{
switch (npc.getId())
{
case UNDRIAS:
{
switch (st.getState())
{
case State.CREATED:
{
htmltext = (player.getRace() == Race.DARK_ELF) ? (player.getLevel() >= MIN_LVL) ? "30130-02.htm" : "30130-01.htm" : "30130-00.htm";
break;
}
case State.STARTED:
{
if (st.isCond(2) && st.hasQuestItems(UNDRIAS_LETTER, CEREMONIAL_DAGGER, DREVIANT_WINE, GARMIELS_SCRIPTURE))
{
showOnScreenMsg(player, NpcStringId.DELIVERY_DUTY_COMPLETE_N_GO_FIND_THE_NEWBIE_GUIDE, 2, 5000); // TODO: Newbie Guide
st.addExpAndSp(5672, 466);
st.giveAdena(2966, true);
st.exitQuest(false, true);
htmltext = "30130-05.html";
}
else
{
htmltext = "30130-04.html";
}
break;
}
case State.COMPLETED:
{
htmltext = getAlreadyCompletedMsg(player);
break;
}
}
break;
}
case IRIA:
case DORANKUS:
case TRUDY:
{
if (st.isStarted())
{
final int npcId = npc.getId();
final int itemId = NPCs.get(npcId);
if (st.isCond(1) && !st.hasQuestItems(itemId))
{
st.giveItems(itemId, 1);
if (st.hasQuestItems(CEREMONIAL_DAGGER, DREVIANT_WINE, GARMIELS_SCRIPTURE))
{
st.setCond(2, true);
}
htmltext = npcId + "-01.html";
}
else
{
htmltext = npcId + "-02.html";
}
break;
}
}
}
}
return htmltext;
}
} | 28.147651 | 138 | 0.67382 |
353469fcc5c1c4a5dee29fd9a7a5ef38cc863882 | 531 | package io.choerodon.core.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 加在 DTO 的某个 field 上,表示这个 field 是用存放子节点信息.
* <p>
* 头行结构中行的标记,也可以用作单个对象的子属性标记
* <p>
* 起作用的地方
* <ul>
* <li>自动校验(可以递归校验子节点)</li>
* <li>自动设置BaseDTO 的StdWho等信息(自动蔓延)</li>
* </ul>
*
* @author [email protected]
*/
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Children {
} | 22.125 | 44 | 0.734463 |
6396798ab76e95731a26bf92f97d0b0e3f23c4a4 | 646 | package ac.cn.saya.payment.provider.repository;
import ac.cn.saya.alibaba.cloud.api.entity.PaymentEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/**
* @Title: PaymentDao
* @ProjectName springcloudalibabastudy
* @Description: TODO
* @Author liunengkai
* @Date: 2020-03-07 15:03
* @Description:
*/
@Mapper
public interface PaymentDao {
/**
* 新增
*
* @param payment
* @return
*/
public int create(PaymentEntity payment);
/**
* 根据Id查询
*
* @param id
* @return
*/
public PaymentEntity getPaymentById(@Param("id") Long id);
}
| 18.457143 | 62 | 0.651703 |
c09394895a2109b296cd77829e0ebd5c7c89b75b | 3,207 | package com.experian.aperture.streaming.client.response;
import com.experian.aperture.streaming.client.ErrorCode;
import com.experian.aperture.streaming.client.StreamingMethod;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
/**
* ErrorFailureMessageFactory tests steps.
*/
final class FailRequestResponseFactoryTestsSteps {
private String message;
private ArrayList<FailRequestResponse> failResponses;
/**
* Create a fail request response.
* @param errorMessage The error message thrown from the server.
* @param method The validation request method.
* @param referenceId The reference id of the requests.
* @return HubExceptionFactoryTestsSteps.
*/
FailRequestResponseFactoryTestsSteps whenICreateFailRequestResponse(final StreamingMethod method, final String referenceId, final String errorMessage) {
message = FailRequestResponseFactory.createFailRequestResponse(method, referenceId, errorMessage).getError().getValue();
return this;
}
/**
* Assert the error message.
* @param errorMessage The error message thrown from the server.
* @return HubExceptionFactoryTestsSteps.
*/
FailRequestResponseFactoryTestsSteps thenIShouldGetTheErrorMessage(final String errorMessage) {
assertThat(message, is(errorMessage));
return this;
}
/**
* Create a list of fail request responses.
* @param method The method name.
* @param error The error code.
* @param referenceIds The list of reference Ids.
* @return HubExceptionFactoryTestsSteps
*/
FailRequestResponseFactoryTestsSteps whenICreateFailRequestResponses(final StreamingMethod method, final ErrorCode error, final List<String> referenceIds) {
this.failResponses = FailRequestResponseFactory.createFailRequestResponses(method, error, referenceIds);
return this;
}
/**
* Assert the list size.
* @param expectedCount The expected size.
* @return HubExceptionFactoryTestsSteps
*/
FailRequestResponseFactoryTestsSteps thenIShouldGetTheFailResponseListOfExpectedCount(final int expectedCount) {
assertThat(this.failResponses.size(), is(expectedCount));
return this;
}
/**
* Assert the fail request method.
* @param expectedMethod The expected method.
* @return HubExceptionFactoryTestsSteps
*/
FailRequestResponseFactoryTestsSteps thenIShouldGetTheFailResponseListOfExpectedMethod(final StreamingMethod expectedMethod) {
assertTrue(this.failResponses.stream().allMatch(x -> x.getMethod().equals(expectedMethod)));
return this;
}
/**
* Assert the fail request error code.
* @param expectedErrorCode The expected error code.
* @return HubExceptionFactoryTestsSteps
*/
FailRequestResponseFactoryTestsSteps thenIShouldGetTheFailResponseListOfExpectedErrorCode(final ErrorCode expectedErrorCode) {
assertTrue(this.failResponses.stream().allMatch(x -> x.getError().equals(expectedErrorCode)));
return this;
}
}
| 38.178571 | 160 | 0.741191 |
1fd7f90826e9530fb384f60161fefba0499258a2 | 813 | package org.mongodb.morphia.issue45;
import org.junit.Test;
import org.mongodb.morphia.TestBase;
import org.mongodb.morphia.annotations.Embedded;
import org.mongodb.morphia.annotations.Entity;
import org.mongodb.morphia.annotations.Transient;
import org.mongodb.morphia.testutil.TestEntity;
import org.junit.Assert;
public class TestEmptyEntityMapping extends TestBase {
@Entity
static class A extends TestEntity {
private static final long serialVersionUID = 1L;
@Embedded B b;
}
@Embedded
static class B {
@Transient String foo;
}
@Test
public void testEmptyEmbeddedNotNullAfterReload() throws Exception {
A a = new A();
a.b = new B();
ds.save(a);
Assert.assertNotNull(a.b);
a = ds.find(A.class, "_id", a.getId()).get();
Assert.assertNull(a.b);
}
}
| 21.972973 | 70 | 0.718327 |
85bbafeef150e0f2966d226bec9dee02969f33e1 | 1,815 | package me.mrletsplay.mrcore.bukkitimpl;
import java.util.Map;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import me.mrletsplay.mrcore.json.JSONArray;
import me.mrletsplay.mrcore.json.JSONObject;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ComponentBuilder;
/**
* Warning: This class is not yet fully compatible with MC 1.13+
* @author MrLetsplay2003
* @since 1.9.4
*
*/
public class ExtraChatComponents {
/**
* @author MrLetsplay2003
*/
public static class ItemStackComponent {
private ItemStack item;
public ItemStackComponent(ItemStack item) {
this.item = item;
}
public ItemStack getItem() {
return item;
}
@SuppressWarnings("deprecation")
public BaseComponent[] toBase() {
JSONObject o = new JSONObject();
o.set("id", item.getType().getId());
o.set("Count", item.getAmount());
if(item.hasItemMeta()) {
ItemMeta meta = item.getItemMeta();
JSONObject tag = new JSONObject();
if(meta.hasDisplayName() || meta.hasLore()) {
JSONObject display = new JSONObject();
if(meta.hasDisplayName()) display.set("Name", meta.getDisplayName());
if(meta.hasLore()) display.set("Lore", new JSONArray(meta.getLore()));
tag.set("display", display);
}
if(meta.hasEnchants()) {
JSONArray ench = new JSONArray();
for(Map.Entry<Enchantment, Integer> en : meta.getEnchants().entrySet()) {
JSONObject e = new JSONObject();
e.set("id", en.getKey().getName()); // TODO: 1.8 - 1.13
e.set("lvl", en.getValue());
ench.add(e);
}
tag.set("ench", ench);
}
o.set("tag", tag);
}
BaseComponent[] b = new ComponentBuilder(o.toString()).create();
return b;
}
}
}
| 25.928571 | 78 | 0.663361 |
afb390f87766b7c4260028f1854d63236eb291c9 | 1,765 | package org.pp.modules.dev.base;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.IBean;
/**
* Generated by JFinal, do not modify this file.
*/
@SuppressWarnings("serial")
public abstract class BaseModels<M extends BaseModels<M>> extends Model<M> implements IBean {
/**
* 自增长主键ID
*/
public void setId(java.lang.Long id) {
set("id", id);
}
/**
* 自增长主键ID
*/
public java.lang.Long getId() {
return getLong("id");
}
/**
* 所属模块
*/
public void setModuleId(java.lang.Long moduleId) {
set("module_id", moduleId);
}
/**
* 所属模块
*/
public java.lang.Long getModuleId() {
return getLong("module_id");
}
/**
* 数据表
*/
public void setTables(java.lang.String tables) {
set("tables", tables);
}
/**
* 数据表
*/
public java.lang.String getTables() {
return getStr("tables");
}
/**
* 类型
*/
public void setType(java.lang.String type) {
set("type", type);
}
/**
* 类型
*/
public java.lang.String getType() {
return getStr("type");
}
/**
* 代码
*/
public void setCode(java.lang.String code) {
set("code", code);
}
/**
* 代码
*/
public java.lang.String getCode() {
return getStr("code");
}
/**
* 名称
*/
public void setTitle(java.lang.String title) {
set("title", title);
}
/**
* 名称
*/
public java.lang.String getTitle() {
return getStr("title");
}
/**
* 状态
*/
public void setStatus(java.lang.String status) {
set("status", status);
}
/**
* 状态
*/
public java.lang.String getStatus() {
return getStr("status");
}
/**
* 数据主键字段
*/
public void setPkField(java.lang.String pkField) {
set("pk_field", pkField);
}
/**
* 数据主键字段
*/
public java.lang.String getPkField() {
return getStr("pk_field");
}
}
| 14.233871 | 93 | 0.6017 |
a51bf070928605203c758bf9a05d66d89a967865 | 3,225 | package com.example.ywang.diseaseidentification.application;
import android.app.Application;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import com.baidu.lbsapi.BMapManager;
import com.baidu.lbsapi.MKGeneralListener;
import com.baidu.mapapi.CoordType;
import com.baidu.mapapi.SDKInitializer;
import com.example.ywang.diseaseidentification.utils.iflytek.RecognitionManager;
import com.example.ywang.diseaseidentification.utils.iflytek.SynthesisManager;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechUtility;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
public class MyApplication extends Application {
public static String TAG = "Init";
public BMapManager mBMapManager;
private static MyApplication mInstance = null;
//设置APPID/AK/SK
public static final String APP_ID = "17747286";
public static final String API_KEY = "cjWrIRKGpcwLM4AUfW8LTopn";
public static final String SECRET_KEY = "VPeZ3SNXgM2p9NdIgOuFdSUEPQUtzQ9q";
@Override
public void onCreate() {
super.onCreate();
SpeechUtility.createUtility(this,SpeechConstant.APPID + "=5d7360d3");
RecognitionManager.getSingleton().init(this,"5d7360d3");
SynthesisManager.getSingleton().init(this,"5d7360d3");
//在使用SDK各组件之前初始化context信息,传入ApplicationContext
SDKInitializer.initialize(this);
//包括BD09LL和GCJ02两种坐标,默认是BD09LL坐标。
SDKInitializer.setCoordType(CoordType.BD09LL);
mInstance = this;
initEngineManager(this);
initImageLoader(this);
}
public void initEngineManager(Context context) {
if (mBMapManager == null) {
mBMapManager = new BMapManager(context);
}
if (!mBMapManager.init(new MyGeneralListener())) {
Toast.makeText(MyApplication.getInstance().getApplicationContext(), "BMapManager初始化错误!",
Toast.LENGTH_LONG).show();
}
Log.d(TAG, "initEngineManager");
}
public static MyApplication getInstance() {
return mInstance;
}
// 常用事件监听,用来处理通常的网络错误,授权验证错误等
public static class MyGeneralListener implements MKGeneralListener {
@Override
public void onGetPermissionState(int iError) {
//非零值表示key验证未通过
if (iError != 0) { // 授权Key错误:
Log.d(TAG, "请在AndroidManifest.xml中输入正确的授权Key,并检查您的网络连接是否正常!error: " + iError);
} else {
Log.d(TAG, "key认证成功");
}
}
}
/**
* 初始化ImageLoader
*/
public static void initImageLoader(Context context) {
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
context)
.threadPoolSize(3).threadPriority(Thread.NORM_PRIORITY - 2)
//.memoryCache(new WeakMemoryCache())
.denyCacheImageMultipleSizesInMemory()
.tasksProcessingOrder( QueueProcessingType.LIFO)
.build();
ImageLoader.getInstance().init(config);
}
}
| 36.235955 | 100 | 0.688992 |
f50ff7541a814e63036d642048902dc8c9c452e9 | 2,274 | package org.fornever.koala.local;
import java.util.Map;
import org.dizitart.no2.Document;
import org.dizitart.no2.Nitrite;
import org.dizitart.no2.NitriteCollection;
import org.dizitart.no2.NitriteId;
import org.dizitart.no2.WriteResult;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
public class NitritelTest {
private Nitrite db;
private NitriteCollection collection;
private ObjectMapper mapper = new ObjectMapper();
@Before
public void setUp() throws Exception {
this.db = Nitrite.builder().openOrCreate();
this.collection = this.db.getCollection("buildings");
}
@After
public void tearDown() throws Exception {
this.db.close();
}
@SuppressWarnings("unchecked")
@Test
public void testCreate() {
Document doc = new Document();
doc.putAll(mapper.convertValue(new Building("Building1", "四川成都", 123), Map.class));
assert this.collection.insert(doc).getAffectedCount() > 0;
}
@SuppressWarnings("unchecked")
@Test
public void testDelete() {
Document doc = new Document();
doc.putAll(mapper.convertValue(new Building("Building3", "四川成都32", 123), Map.class));
WriteResult r = this.collection.insert(doc);
assert r.getAffectedCount() > 0;
NitriteId id = r.iterator().next();
assert this.collection.remove(this.collection.getById(id)).getAffectedCount() > 0;
}
@SuppressWarnings("unchecked")
@Test
public void testRetrive() {
Document doc = new Document();
doc.putAll(mapper.convertValue(new Building("Building2", "四川成都3", 123), Map.class));
WriteResult r = this.collection.insert(doc);
assert r.getAffectedCount() > 0;
assert this.collection.getById(r.iterator().next()).get("name") == "Building2";
}
@SuppressWarnings("unchecked")
@Test
public void testUpdate() {
Document doc = new Document();
doc.putAll(mapper.convertValue(new Building("Building3", "四川成都3", 123), Map.class));
WriteResult r = this.collection.insert(doc);
NitriteId id = r.iterator().next();
assert r.getAffectedCount() > 0;
assert this.collection.getById(id).get("name") == "Building3";
doc.put("name", "changed");
assert this.collection.update(doc).getAffectedCount() > 0;
assert this.collection.getById(id).get("name") == "changed";
}
}
| 28.78481 | 87 | 0.726473 |
c2829aa5702224cede84333d6fbd897f0ce7b5d5 | 21,140 | package edu.gatech.gtri.trustmark.v1_0.impl.tip;
import edu.gatech.gtri.trustmark.v1_0.model.TrustInteroperabilityProfile;
import edu.gatech.gtri.trustmark.v1_0.tip.TrustExpression;
import edu.gatech.gtri.trustmark.v1_0.tip.TrustExpressionFailure;
import edu.gatech.gtri.trustmark.v1_0.tip.TrustExpressionType;
import edu.gatech.gtri.trustmark.v1_0.tip.TrustExpressionTypeOwner;
import edu.gatech.gtri.trustmark.v1_0.tip.evaluator.TrustExpressionEvaluatorData;
import edu.gatech.gtri.trustmark.v1_0.tip.parser.TrustExpressionParserData;
import org.gtri.fj.data.NonEmptyList;
import org.gtri.fj.data.Validation;
import org.gtri.fj.function.F2;
import org.gtri.fj.function.F3;
import org.gtri.fj.product.P;
import org.gtri.fj.product.P2;
import static edu.gatech.gtri.trustmark.v1_0.tip.TrustExpressionFailure.failureTypeMismatch;
import static edu.gatech.gtri.trustmark.v1_0.tip.TrustExpressionType.TrustExpressionTypeBoolean.TYPE_BOOLEAN;
import static edu.gatech.gtri.trustmark.v1_0.tip.TrustExpressionType.TrustExpressionTypeDateTimeStamp.TYPE_DATE_TIME_STAMP;
import static edu.gatech.gtri.trustmark.v1_0.tip.TrustExpressionType.TrustExpressionTypeDecimal.TYPE_DECIMAL;
import static edu.gatech.gtri.trustmark.v1_0.tip.TrustExpressionType.TrustExpressionTypeString.TYPE_STRING;
import static edu.gatech.gtri.trustmark.v1_0.tip.TrustExpressionType.TrustExpressionTypeStringList.TYPE_STRING_LIST;
import static org.gtri.fj.data.NonEmptyList.nel;
import static org.gtri.fj.data.Validation.accumulate;
import static org.gtri.fj.data.Validation.condition;
import static org.gtri.fj.data.Validation.fail;
import static org.gtri.fj.data.Validation.success;
import static org.gtri.fj.product.P.p;
public class TrustExpressionTypeUtility {
private TrustExpressionTypeUtility() {
}
public static Validation<NonEmptyList<TrustExpressionFailure>, P2<TrustExpressionParserData, TrustExpressionParserData>> mustSatisfyAndForParser(
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, TrustExpressionParserData>> trustExpressionLeft,
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, TrustExpressionParserData>> trustExpressionRight,
final NonEmptyList<TrustInteroperabilityProfile> trustInteroperabilityProfileNonEmptyList) {
return expressionMustBeSuccessAndTypeMustBe(
trustExpressionLeft,
nel(TYPE_BOOLEAN),
trustExpressionRight,
nel(TYPE_BOOLEAN),
trustInteroperabilityProfileNonEmptyList);
}
public static Validation<NonEmptyList<TrustExpressionFailure>, P2<TrustExpressionEvaluatorData, Validation<NonEmptyList<TrustExpressionFailure>, TrustExpressionEvaluatorData>>> mustSatisfyAndForEvaluator(
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, TrustExpressionEvaluatorData>> trustExpressionLeft,
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, TrustExpressionEvaluatorData>> trustExpressionRight,
final NonEmptyList<TrustInteroperabilityProfile> trustInteroperabilityProfileNonEmptyList) {
final Validation<NonEmptyList<TrustExpressionFailure>, TrustExpressionEvaluatorData> trustExpressionEvaluatorDataLeftValidation =
expressionMustBeSuccess(trustExpressionLeft, trustInteroperabilityProfileNonEmptyList, TrustExpressionFailure::failureExpressionLeft).bind(trustExpressionTypeOwner ->
typeMustBe(trustExpressionTypeOwner, nel(TYPE_BOOLEAN), trustInteroperabilityProfileNonEmptyList, TrustExpressionFailure::failureTypeUnexpectedLeft));
final Validation<NonEmptyList<TrustExpressionFailure>, TrustExpressionEvaluatorData> trustExpressionEvaluatorDataRightValidation =
expressionMustBeSuccess(trustExpressionRight, trustInteroperabilityProfileNonEmptyList, TrustExpressionFailure::failureExpressionRight).bind(trustExpressionTypeOwner ->
typeMustBe(trustExpressionTypeOwner, nel(TYPE_BOOLEAN), trustInteroperabilityProfileNonEmptyList, TrustExpressionFailure::failureTypeUnexpectedRight));
return trustExpressionEvaluatorDataLeftValidation
.map(trustExpressionEvaluatorDataLeft -> p(trustExpressionEvaluatorDataLeft, trustExpressionEvaluatorDataRightValidation))
.f().bind(nelLeft -> trustExpressionEvaluatorDataRightValidation
.map(trustExpressionEvaluatorDataRight -> p(trustExpressionEvaluatorDataRight, trustExpressionEvaluatorDataLeftValidation))
.f().map(nelRight -> nelLeft.append(nelRight)));
}
public static Validation<NonEmptyList<TrustExpressionFailure>, P2<TrustExpressionParserData, TrustExpressionParserData>> mustSatisfyOrForParser(
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, TrustExpressionParserData>> trustExpressionLeft,
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, TrustExpressionParserData>> trustExpressionRight,
final NonEmptyList<TrustInteroperabilityProfile> trustInteroperabilityProfileNonEmptyList) {
return expressionMustBeSuccessAndTypeMustBe(
trustExpressionLeft,
nel(TYPE_BOOLEAN),
trustExpressionRight,
nel(TYPE_BOOLEAN),
trustInteroperabilityProfileNonEmptyList);
}
public static Validation<NonEmptyList<TrustExpressionFailure>, P2<TrustExpressionEvaluatorData, Validation<NonEmptyList<TrustExpressionFailure>, TrustExpressionEvaluatorData>>> mustSatisfyOrForEvaluator(
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, TrustExpressionEvaluatorData>> trustExpressionLeft,
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, TrustExpressionEvaluatorData>> trustExpressionRight,
final NonEmptyList<TrustInteroperabilityProfile> trustInteroperabilityProfileNonEmptyList) {
final Validation<NonEmptyList<TrustExpressionFailure>, TrustExpressionEvaluatorData> trustExpressionEvaluatorDataLeftValidation =
expressionMustBeSuccess(trustExpressionLeft, trustInteroperabilityProfileNonEmptyList, TrustExpressionFailure::failureExpressionLeft).bind(trustExpressionTypeOwner ->
typeMustBe(trustExpressionTypeOwner, nel(TYPE_BOOLEAN), trustInteroperabilityProfileNonEmptyList, TrustExpressionFailure::failureTypeUnexpectedLeft));
final Validation<NonEmptyList<TrustExpressionFailure>, TrustExpressionEvaluatorData> trustExpressionEvaluatorDataRightValidation =
expressionMustBeSuccess(trustExpressionRight, trustInteroperabilityProfileNonEmptyList, TrustExpressionFailure::failureExpressionRight).bind(trustExpressionTypeOwner ->
typeMustBe(trustExpressionTypeOwner, nel(TYPE_BOOLEAN), trustInteroperabilityProfileNonEmptyList, TrustExpressionFailure::failureTypeUnexpectedRight));
return trustExpressionEvaluatorDataLeftValidation
.map(trustExpressionEvaluatorDataLeft -> p(trustExpressionEvaluatorDataLeft, trustExpressionEvaluatorDataRightValidation))
.f().bind(nelLeft -> trustExpressionEvaluatorDataRightValidation
.map(trustExpressionEvaluatorDataRight -> p(trustExpressionEvaluatorDataRight, trustExpressionEvaluatorDataLeftValidation))
.f().map(nelRight -> nelLeft.append(nelRight)));
}
public static <T1 extends TrustExpressionTypeOwner> Validation<NonEmptyList<TrustExpressionFailure>, P2<T1, T1>> mustSatisfyLessThan(
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, T1>> trustExpressionLeft,
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, T1>> trustExpressionRight,
final NonEmptyList<TrustInteroperabilityProfile> trustInteroperabilityProfileNonEmptyList) {
return expressionMustBeSuccessAndTypeMustMatchAndTypeMustBeOrderable(trustExpressionLeft, trustExpressionRight, trustInteroperabilityProfileNonEmptyList);
}
public static <T1 extends TrustExpressionTypeOwner> Validation<NonEmptyList<TrustExpressionFailure>, P2<T1, T1>> mustSatisfyLessThanOrEqual(
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, T1>> trustExpressionLeft,
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, T1>> trustExpressionRight,
final NonEmptyList<TrustInteroperabilityProfile> trustInteroperabilityProfileNonEmptyList) {
return expressionMustBeSuccessAndTypeMustMatchAndTypeMustBeOrderable(trustExpressionLeft, trustExpressionRight, trustInteroperabilityProfileNonEmptyList);
}
public static <T1 extends TrustExpressionTypeOwner> Validation<NonEmptyList<TrustExpressionFailure>, P2<T1, T1>> mustSatisfyGreaterThan(
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, T1>> trustExpressionLeft,
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, T1>> trustExpressionRight,
final NonEmptyList<TrustInteroperabilityProfile> trustInteroperabilityProfileNonEmptyList) {
return expressionMustBeSuccessAndTypeMustMatchAndTypeMustBeOrderable(trustExpressionLeft, trustExpressionRight, trustInteroperabilityProfileNonEmptyList);
}
public static <T1 extends TrustExpressionTypeOwner> Validation<NonEmptyList<TrustExpressionFailure>, P2<T1, T1>> mustSatisfyGreaterThanOrEqual(
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, T1>> trustExpressionLeft,
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, T1>> trustExpressionRight,
final NonEmptyList<TrustInteroperabilityProfile> trustInteroperabilityProfileNonEmptyList) {
return expressionMustBeSuccessAndTypeMustMatchAndTypeMustBeOrderable(trustExpressionLeft, trustExpressionRight, trustInteroperabilityProfileNonEmptyList);
}
public static <T1 extends TrustExpressionTypeOwner> Validation<NonEmptyList<TrustExpressionFailure>, P2<T1, T1>> mustSatisfyNotEqual(
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, T1>> trustExpressionLeft,
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, T1>> trustExpressionRight,
final NonEmptyList<TrustInteroperabilityProfile> trustInteroperabilityProfileNonEmptyList) {
return expressionMustBeSuccessAndTypeMustMatch(trustExpressionLeft, trustExpressionRight, trustInteroperabilityProfileNonEmptyList);
}
public static <T1 extends TrustExpressionTypeOwner> Validation<NonEmptyList<TrustExpressionFailure>, P2<T1, T1>> mustSatisfyEqual(
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, T1>> trustExpressionLeft,
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, T1>> trustExpressionRight,
final NonEmptyList<TrustInteroperabilityProfile> trustInteroperabilityProfileNonEmptyList) {
return expressionMustBeSuccessAndTypeMustMatch(trustExpressionLeft, trustExpressionRight, trustInteroperabilityProfileNonEmptyList);
}
public static <T1 extends TrustExpressionTypeOwner> Validation<NonEmptyList<TrustExpressionFailure>, P2<T1, T1>> mustSatisfyContains(
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, T1>> trustExpressionLeft,
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, T1>> trustExpressionRight,
final NonEmptyList<TrustInteroperabilityProfile> trustInteroperabilityProfileNonEmptyList) {
return expressionMustBeSuccessAndTypeMustBe(
trustExpressionLeft,
nel(TYPE_STRING_LIST),
trustExpressionRight,
nel(TYPE_STRING),
trustInteroperabilityProfileNonEmptyList);
}
public static <T1 extends TrustExpressionTypeOwner> Validation<NonEmptyList<TrustExpressionFailure>, T1> mustSatisfyNoop(
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, T1>> trustExpression,
final NonEmptyList<TrustInteroperabilityProfile> trustInteroperabilityProfileNonEmptyList) {
return expressionMustBeSuccess(trustExpression, trustInteroperabilityProfileNonEmptyList, TrustExpressionFailure::failureExpression);
}
public static <T1 extends TrustExpressionTypeOwner> Validation<NonEmptyList<TrustExpressionFailure>, T1> mustSatisfyNot(
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, T1>> trustExpression,
final NonEmptyList<TrustInteroperabilityProfile> trustInteroperabilityProfileNonEmptyList) {
return expressionMustBeSuccessAndTypeMustBe(trustExpression, TYPE_BOOLEAN, trustInteroperabilityProfileNonEmptyList);
}
public static <T1 extends TrustExpressionTypeOwner> Validation<NonEmptyList<TrustExpressionFailure>, T1> mustSatisfyExists(
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, T1>> trustExpression,
final NonEmptyList<TrustInteroperabilityProfile> trustInteroperabilityProfileNonEmptyList) {
return expressionMustBeSuccess(trustExpression, trustInteroperabilityProfileNonEmptyList, TrustExpressionFailure::failureExpression);
}
private static <T1 extends TrustExpressionTypeOwner> Validation<NonEmptyList<TrustExpressionFailure>, P2<T1, T1>> expressionMustBeSuccessAndTypeMustMatchAndTypeMustBeOrderable(
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, T1>> trustExpressionLeft,
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, T1>> trustExpressionRight,
final NonEmptyList<TrustInteroperabilityProfile> trustInteroperabilityProfileNonEmptyList) {
return expressionMustBeSuccessAndTypeMustBe(
trustExpressionLeft,
nel(TYPE_BOOLEAN, TYPE_DATE_TIME_STAMP, TYPE_DECIMAL, TYPE_STRING),
trustExpressionRight,
nel(TYPE_BOOLEAN, TYPE_DATE_TIME_STAMP, TYPE_DECIMAL, TYPE_STRING),
trustInteroperabilityProfileNonEmptyList)
.bind(p -> typeMustMatch(p._1(), p._2(), trustInteroperabilityProfileNonEmptyList));
}
private static <T1 extends TrustExpressionTypeOwner> Validation<NonEmptyList<TrustExpressionFailure>, P2<T1, T1>> expressionMustBeSuccessAndTypeMustMatch(
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, T1>> trustExpressionLeft,
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, T1>> trustExpressionRight,
final NonEmptyList<TrustInteroperabilityProfile> trustInteroperabilityProfileNonEmptyList) {
return accumulate(
expressionMustBeSuccess(trustExpressionLeft, trustInteroperabilityProfileNonEmptyList, TrustExpressionFailure::failureExpressionLeft),
expressionMustBeSuccess(trustExpressionRight, trustInteroperabilityProfileNonEmptyList, TrustExpressionFailure::failureExpressionRight),
P::p)
.bind(p -> typeMustMatch(p._1(), p._2(), trustInteroperabilityProfileNonEmptyList));
}
private static <T1 extends TrustExpressionTypeOwner> Validation<NonEmptyList<TrustExpressionFailure>, P2<T1, T1>> expressionMustBeSuccessAndTypeMustBe(
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, T1>> trustExpressionLeft,
final NonEmptyList<TrustExpressionType> trustExpressionTypeNonEmptyListLeft,
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, T1>> trustExpressionRight,
final NonEmptyList<TrustExpressionType> trustExpressionTypeNonEmptyListRight,
final NonEmptyList<TrustInteroperabilityProfile> trustInteroperabilityProfileNonEmptyList) {
return accumulate(
expressionMustBeSuccess(trustExpressionLeft, trustInteroperabilityProfileNonEmptyList, TrustExpressionFailure::failureExpressionLeft).bind(trustExpressionTypeOwner ->
typeMustBe(trustExpressionTypeOwner, trustExpressionTypeNonEmptyListLeft, trustInteroperabilityProfileNonEmptyList, TrustExpressionFailure::failureTypeUnexpectedLeft)),
expressionMustBeSuccess(trustExpressionRight, trustInteroperabilityProfileNonEmptyList, TrustExpressionFailure::failureExpressionRight).bind(trustExpressionTypeOwner ->
typeMustBe(trustExpressionTypeOwner, trustExpressionTypeNonEmptyListRight, trustInteroperabilityProfileNonEmptyList, TrustExpressionFailure::failureTypeUnexpectedRight)),
P::p);
}
private static <T1 extends TrustExpressionTypeOwner> Validation<NonEmptyList<TrustExpressionFailure>, T1> expressionMustBeSuccessAndTypeMustBe(
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, T1>> trustExpression,
final TrustExpressionType trustExpressionType,
final NonEmptyList<TrustInteroperabilityProfile> trustInteroperabilityProfileNonEmptyList) {
return expressionMustBeSuccessAndTypeMustBe(trustExpression, nel(trustExpressionType), trustInteroperabilityProfileNonEmptyList);
}
private static <T1 extends TrustExpressionTypeOwner> Validation<NonEmptyList<TrustExpressionFailure>, T1> expressionMustBeSuccessAndTypeMustBe(
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, T1>> trustExpression,
final NonEmptyList<TrustExpressionType> trustExpressionTypeNonEmptyList,
final NonEmptyList<TrustInteroperabilityProfile> trustInteroperabilityProfileNonEmptyList) {
return expressionMustBeSuccess(trustExpression, trustInteroperabilityProfileNonEmptyList, TrustExpressionFailure::failureExpression).bind(trustExpressionTypeOwner ->
typeMustBe(trustExpressionTypeOwner, trustExpressionTypeNonEmptyList, trustInteroperabilityProfileNonEmptyList, TrustExpressionFailure::failureTypeUnexpected));
}
private static <T1> Validation<NonEmptyList<TrustExpressionFailure>, T1> expressionMustBeSuccess(
final TrustExpression<Validation<NonEmptyList<TrustExpressionFailure>, T1>> trustExpression,
final NonEmptyList<TrustInteroperabilityProfile> trustInteroperabilityProfileNonEmptyList,
final F2<NonEmptyList<TrustInteroperabilityProfile>, NonEmptyList<TrustExpressionFailure>, TrustExpressionFailure> trustExpressionFailureF) {
return trustExpression.getData()
.f().map(nel -> nel(trustExpressionFailureF.f(trustInteroperabilityProfileNonEmptyList, nel)));
}
private static <T1 extends TrustExpressionTypeOwner> Validation<NonEmptyList<TrustExpressionFailure>, T1> typeMustBe(
final T1 trustExpressionTypeOwner,
final TrustExpressionType trustExpressionType,
final NonEmptyList<TrustInteroperabilityProfile> trustInteroperabilityProfileNonEmptyList,
final F3<NonEmptyList<TrustInteroperabilityProfile>, NonEmptyList<TrustExpressionType>, TrustExpressionType, TrustExpressionFailure> trustExpressionFailureF) {
return typeMustBe(trustExpressionTypeOwner, nel(trustExpressionType), trustInteroperabilityProfileNonEmptyList, trustExpressionFailureF);
}
private static <T1 extends TrustExpressionTypeOwner> Validation<NonEmptyList<TrustExpressionFailure>, T1> typeMustBe(
final T1 trustExpressionTypeOwner,
final NonEmptyList<TrustExpressionType> trustExpressionTypeNonEmptyList,
final NonEmptyList<TrustInteroperabilityProfile> trustInteroperabilityProfileNonEmptyList,
final F3<NonEmptyList<TrustInteroperabilityProfile>, NonEmptyList<TrustExpressionType>, TrustExpressionType, TrustExpressionFailure> trustExpressionFailureF) {
return condition(
trustExpressionTypeNonEmptyList.toList().exists(trustExpressionType -> trustExpressionType == trustExpressionTypeOwner.getTrustExpressionType()),
nel(trustExpressionFailureF.f(trustInteroperabilityProfileNonEmptyList, trustExpressionTypeNonEmptyList, trustExpressionTypeOwner.getTrustExpressionType())),
trustExpressionTypeOwner);
}
private static <T1 extends TrustExpressionTypeOwner> Validation<NonEmptyList<TrustExpressionFailure>, P2<T1, T1>> typeMustMatch(
final T1 trustExpressionLeft,
final T1 trustExpressionRight,
final NonEmptyList<TrustInteroperabilityProfile> trustInteroperabilityProfileNonEmptyList) {
return trustExpressionLeft.matchType(
trustExpressionRight,
() -> success(p(trustExpressionLeft, trustExpressionRight)),
() -> fail(nel(failureTypeMismatch(trustInteroperabilityProfileNonEmptyList, trustExpressionLeft.getTrustExpressionType(), trustExpressionRight.getTrustExpressionType()))));
}
}
| 74.43662 | 208 | 0.792952 |
423d6292618c571859c967e12b442c436cbb38d2 | 1,219 | package net.minecraft.network.play.client;
import java.io.IOException;
import net.minecraft.network.INetHandler;
import net.minecraft.network.Packet;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.play.INetHandlerPlayServer;
public class C0DPacketCloseWindow extends Packet
{
private int field_149556_a;
private static final String __OBFID = "CL_00001354";
public C0DPacketCloseWindow() {}
public C0DPacketCloseWindow(int p_i45247_1_)
{
this.field_149556_a = p_i45247_1_;
}
public void processPacket(INetHandlerPlayServer p_149555_1_)
{
p_149555_1_.processCloseWindow(this);
}
/**
* Reads the raw packet data from the data stream.
*/
public void readPacketData(PacketBuffer p_148837_1_) throws IOException
{
this.field_149556_a = p_148837_1_.readByte();
}
/**
* Writes the raw packet data to the data stream.
*/
public void writePacketData(PacketBuffer p_148840_1_) throws IOException
{
p_148840_1_.writeByte(this.field_149556_a);
}
public void processPacket(INetHandler p_148833_1_)
{
this.processPacket((INetHandlerPlayServer)p_148833_1_);
}
}
| 25.93617 | 76 | 0.721083 |
2a5d2231b7ab6ee3721cd38cb82d96c7b3b4440f | 160 | package org.jeecg.modules.datasources.model;
import lombok.Data;
@Data
public class WaterfallJobLock {
/**
* 锁名称
*/
private String lockName;
} | 14.545455 | 44 | 0.68125 |
92f12c5c0a5777fc8babbcf42e72a36313602c7e | 2,144 | package base;
public class Main {
/**
* # Lab Three
*
* Ok for this lab we're going to reiterate a lot of the things that we went over in class.
*
* Our Goals are:
* - Conditionals
* - If
* - Else
* - Else If
*/
public static void main(String[] args) {
// Make an if statement that triggers a print or println statement
if (true) {
System.out.println("If statement triggered a println statement");
}
// Make an if, else statement where the else statement triggers a print or println statement
if (!true) {
System.out.println("First half of statement triggered by an if not true clause");
} else {
System.out.println("Second half of statement triggered by an else clause");
}
// Make an if, else if, else statement where the else if statement triggers a print or println statement
if (!true) {
System.out.println("Not true");
} else if (!true){
System.out.println("true");
} else {
System.out.println("else statement triggered a println statement");
}
// Make 2 variables and use them in an if else conditional print from one of the sections
boolean strawberry = true;
boolean banana = false;
if (strawberry && !banana) {
System.out.println("I can make a strawberry banana crepe");
}
else {
System.out.println("whoops");
}
// Make an if statement using 2 variables and an AND(&&) statement that triggers a print or println statement
boolean tennis = true;
boolean soccer = false;
if (tennis && !soccer) {
System.out.println("I play both soccer and tennis");
}
// Make an if statement using 2 variables and an OR(||) statement that triggers a print or println statement
boolean pancakes = true;
boolean waffles = false;
if (pancakes || waffles) {
System.out.print("I can make pancakes or waffles");
}
}
}
| 36.338983 | 117 | 0.577425 |
ffb40e6fe0f9da634c6fc26a6d007e1d73fafa2e | 1,901 | /*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
*/
package org.biojava.bio.seq.db.biofetch;
import java.util.Map;
import org.biojava.bio.BioException;
import org.biojava.bio.seq.db.SequenceDBLite;
import org.biojava.directory.RegistryException;
import org.biojava.directory.SequenceDBProvider;
/**
* Directory-services plugin for biofetch databases.
*
* This class is instantiated automatically by the
* directory-services code, and is not of direct
* interest to users.
*
* @author Thomas Down
* @author Keith James
* @since 1.3
*/
public class BioFetchSequenceDBProvider implements SequenceDBProvider {
public String getName() {
return "biofetch";
}
public SequenceDBLite getSequenceDB(Map config)
throws RegistryException, BioException
{
String location = (String) config.get("location");
if (location == null) {
throw new RegistryException("BioFetch provider requires"
+ " a location parameter");
}
String dbName = (String) config.get("dbname");
if (dbName == null) {
throw new RegistryException("BioFetch provider requires"
+ " a dbname parameter");
}
return new BioFetchSequenceDB(location, dbName);
}
}
| 29.246154 | 71 | 0.644398 |
3311732832930dd9ee7ec6cfe7f6084463a5363d | 45,029 | /*
* Copyright 2011-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not
* use this file except in compliance with the License. A copy of the License is
* located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.elasticmapreduce.model;
import java.io.Serializable;
/**
* <p>
* The detailed description of the cluster.
* </p>
*/
public class Cluster implements Serializable, Cloneable {
/**
* <p>
* The unique identifier for the cluster.
* </p>
*/
private String id;
/**
* <p>
* The name of the cluster.
* </p>
*/
private String name;
/**
* <p>
* The current status details about the cluster.
* </p>
*/
private ClusterStatus status;
private Ec2InstanceAttributes ec2InstanceAttributes;
/**
* <p>
* The path to the Amazon S3 location where logs for this cluster are
* stored.
* </p>
*/
private String logUri;
/**
* <p>
* The AMI version requested for this cluster.
* </p>
*/
private String requestedAmiVersion;
/**
* <p>
* The AMI version running on this cluster.
* </p>
*/
private String runningAmiVersion;
/**
* <p>
* The release label for the Amazon EMR release. For Amazon EMR 3.x and 2.x
* AMIs, use amiVersion instead instead of ReleaseLabel.
* </p>
*/
private String releaseLabel;
/**
* <p>
* Specifies whether the cluster should terminate after completing all
* steps.
* </p>
*/
private Boolean autoTerminate;
/**
* <p>
* Indicates whether Amazon EMR will lock the cluster to prevent the EC2
* instances from being terminated by an API call or user intervention, or
* in the event of a cluster error.
* </p>
*/
private Boolean terminationProtected;
/**
* <p>
* Indicates whether the job flow is visible to all IAM users of the AWS
* account associated with the job flow. If this value is set to
* <code>true</code>, all IAM users of that AWS account can view and manage
* the job flow if they have the proper policy permissions set. If this
* value is <code>false</code>, only the IAM user that created the cluster
* can view and manage it. This value can be changed using the
* <a>SetVisibleToAllUsers</a> action.
* </p>
*/
private Boolean visibleToAllUsers;
/**
* <p>
* The applications installed on this cluster.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<Application> applications;
/**
* <p>
* A list of tags associated with a cluster.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<Tag> tags;
/**
* <p>
* The IAM role that will be assumed by the Amazon EMR service to access AWS
* resources on your behalf.
* </p>
*/
private String serviceRole;
/**
* <p>
* An approximation of the cost of the job flow, represented in
* m1.small/hours. This value is incremented one time for every hour an
* m1.small instance runs. Larger instances are weighted more, so an EC2
* instance that is roughly four times more expensive would result in the
* normalized instance hours being incremented by four. This result is only
* an approximation and does not reflect the actual billing rate.
* </p>
*/
private Integer normalizedInstanceHours;
/**
* <p>
* The public DNS name of the master EC2 instance.
* </p>
*/
private String masterPublicDnsName;
/**
* <note>
* <p>
* Amazon EMR releases 4.x or later.
* </p>
* </note>
* <p>
* The list of Configurations supplied to the EMR cluster.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<Configuration> configurations;
/**
* <p>
* The unique identifier for the cluster.
* </p>
*
* @param id
* The unique identifier for the cluster.
*/
public void setId(String id) {
this.id = id;
}
/**
* <p>
* The unique identifier for the cluster.
* </p>
*
* @return The unique identifier for the cluster.
*/
public String getId() {
return this.id;
}
/**
* <p>
* The unique identifier for the cluster.
* </p>
*
* @param id
* The unique identifier for the cluster.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public Cluster withId(String id) {
setId(id);
return this;
}
/**
* <p>
* The name of the cluster.
* </p>
*
* @param name
* The name of the cluster.
*/
public void setName(String name) {
this.name = name;
}
/**
* <p>
* The name of the cluster.
* </p>
*
* @return The name of the cluster.
*/
public String getName() {
return this.name;
}
/**
* <p>
* The name of the cluster.
* </p>
*
* @param name
* The name of the cluster.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public Cluster withName(String name) {
setName(name);
return this;
}
/**
* <p>
* The current status details about the cluster.
* </p>
*
* @param status
* The current status details about the cluster.
*/
public void setStatus(ClusterStatus status) {
this.status = status;
}
/**
* <p>
* The current status details about the cluster.
* </p>
*
* @return The current status details about the cluster.
*/
public ClusterStatus getStatus() {
return this.status;
}
/**
* <p>
* The current status details about the cluster.
* </p>
*
* @param status
* The current status details about the cluster.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public Cluster withStatus(ClusterStatus status) {
setStatus(status);
return this;
}
/**
* @param ec2InstanceAttributes
*/
public void setEc2InstanceAttributes(
Ec2InstanceAttributes ec2InstanceAttributes) {
this.ec2InstanceAttributes = ec2InstanceAttributes;
}
/**
* @return
*/
public Ec2InstanceAttributes getEc2InstanceAttributes() {
return this.ec2InstanceAttributes;
}
/**
* @param ec2InstanceAttributes
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public Cluster withEc2InstanceAttributes(
Ec2InstanceAttributes ec2InstanceAttributes) {
setEc2InstanceAttributes(ec2InstanceAttributes);
return this;
}
/**
* <p>
* The path to the Amazon S3 location where logs for this cluster are
* stored.
* </p>
*
* @param logUri
* The path to the Amazon S3 location where logs for this cluster are
* stored.
*/
public void setLogUri(String logUri) {
this.logUri = logUri;
}
/**
* <p>
* The path to the Amazon S3 location where logs for this cluster are
* stored.
* </p>
*
* @return The path to the Amazon S3 location where logs for this cluster
* are stored.
*/
public String getLogUri() {
return this.logUri;
}
/**
* <p>
* The path to the Amazon S3 location where logs for this cluster are
* stored.
* </p>
*
* @param logUri
* The path to the Amazon S3 location where logs for this cluster are
* stored.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public Cluster withLogUri(String logUri) {
setLogUri(logUri);
return this;
}
/**
* <p>
* The AMI version requested for this cluster.
* </p>
*
* @param requestedAmiVersion
* The AMI version requested for this cluster.
*/
public void setRequestedAmiVersion(String requestedAmiVersion) {
this.requestedAmiVersion = requestedAmiVersion;
}
/**
* <p>
* The AMI version requested for this cluster.
* </p>
*
* @return The AMI version requested for this cluster.
*/
public String getRequestedAmiVersion() {
return this.requestedAmiVersion;
}
/**
* <p>
* The AMI version requested for this cluster.
* </p>
*
* @param requestedAmiVersion
* The AMI version requested for this cluster.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public Cluster withRequestedAmiVersion(String requestedAmiVersion) {
setRequestedAmiVersion(requestedAmiVersion);
return this;
}
/**
* <p>
* The AMI version running on this cluster.
* </p>
*
* @param runningAmiVersion
* The AMI version running on this cluster.
*/
public void setRunningAmiVersion(String runningAmiVersion) {
this.runningAmiVersion = runningAmiVersion;
}
/**
* <p>
* The AMI version running on this cluster.
* </p>
*
* @return The AMI version running on this cluster.
*/
public String getRunningAmiVersion() {
return this.runningAmiVersion;
}
/**
* <p>
* The AMI version running on this cluster.
* </p>
*
* @param runningAmiVersion
* The AMI version running on this cluster.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public Cluster withRunningAmiVersion(String runningAmiVersion) {
setRunningAmiVersion(runningAmiVersion);
return this;
}
/**
* <p>
* The release label for the Amazon EMR release. For Amazon EMR 3.x and 2.x
* AMIs, use amiVersion instead instead of ReleaseLabel.
* </p>
*
* @param releaseLabel
* The release label for the Amazon EMR release. For Amazon EMR 3.x
* and 2.x AMIs, use amiVersion instead instead of ReleaseLabel.
*/
public void setReleaseLabel(String releaseLabel) {
this.releaseLabel = releaseLabel;
}
/**
* <p>
* The release label for the Amazon EMR release. For Amazon EMR 3.x and 2.x
* AMIs, use amiVersion instead instead of ReleaseLabel.
* </p>
*
* @return The release label for the Amazon EMR release. For Amazon EMR 3.x
* and 2.x AMIs, use amiVersion instead instead of ReleaseLabel.
*/
public String getReleaseLabel() {
return this.releaseLabel;
}
/**
* <p>
* The release label for the Amazon EMR release. For Amazon EMR 3.x and 2.x
* AMIs, use amiVersion instead instead of ReleaseLabel.
* </p>
*
* @param releaseLabel
* The release label for the Amazon EMR release. For Amazon EMR 3.x
* and 2.x AMIs, use amiVersion instead instead of ReleaseLabel.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public Cluster withReleaseLabel(String releaseLabel) {
setReleaseLabel(releaseLabel);
return this;
}
/**
* <p>
* Specifies whether the cluster should terminate after completing all
* steps.
* </p>
*
* @param autoTerminate
* Specifies whether the cluster should terminate after completing
* all steps.
*/
public void setAutoTerminate(Boolean autoTerminate) {
this.autoTerminate = autoTerminate;
}
/**
* <p>
* Specifies whether the cluster should terminate after completing all
* steps.
* </p>
*
* @return Specifies whether the cluster should terminate after completing
* all steps.
*/
public Boolean getAutoTerminate() {
return this.autoTerminate;
}
/**
* <p>
* Specifies whether the cluster should terminate after completing all
* steps.
* </p>
*
* @param autoTerminate
* Specifies whether the cluster should terminate after completing
* all steps.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public Cluster withAutoTerminate(Boolean autoTerminate) {
setAutoTerminate(autoTerminate);
return this;
}
/**
* <p>
* Specifies whether the cluster should terminate after completing all
* steps.
* </p>
*
* @return Specifies whether the cluster should terminate after completing
* all steps.
*/
public Boolean isAutoTerminate() {
return this.autoTerminate;
}
/**
* <p>
* Indicates whether Amazon EMR will lock the cluster to prevent the EC2
* instances from being terminated by an API call or user intervention, or
* in the event of a cluster error.
* </p>
*
* @param terminationProtected
* Indicates whether Amazon EMR will lock the cluster to prevent the
* EC2 instances from being terminated by an API call or user
* intervention, or in the event of a cluster error.
*/
public void setTerminationProtected(Boolean terminationProtected) {
this.terminationProtected = terminationProtected;
}
/**
* <p>
* Indicates whether Amazon EMR will lock the cluster to prevent the EC2
* instances from being terminated by an API call or user intervention, or
* in the event of a cluster error.
* </p>
*
* @return Indicates whether Amazon EMR will lock the cluster to prevent the
* EC2 instances from being terminated by an API call or user
* intervention, or in the event of a cluster error.
*/
public Boolean getTerminationProtected() {
return this.terminationProtected;
}
/**
* <p>
* Indicates whether Amazon EMR will lock the cluster to prevent the EC2
* instances from being terminated by an API call or user intervention, or
* in the event of a cluster error.
* </p>
*
* @param terminationProtected
* Indicates whether Amazon EMR will lock the cluster to prevent the
* EC2 instances from being terminated by an API call or user
* intervention, or in the event of a cluster error.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public Cluster withTerminationProtected(Boolean terminationProtected) {
setTerminationProtected(terminationProtected);
return this;
}
/**
* <p>
* Indicates whether Amazon EMR will lock the cluster to prevent the EC2
* instances from being terminated by an API call or user intervention, or
* in the event of a cluster error.
* </p>
*
* @return Indicates whether Amazon EMR will lock the cluster to prevent the
* EC2 instances from being terminated by an API call or user
* intervention, or in the event of a cluster error.
*/
public Boolean isTerminationProtected() {
return this.terminationProtected;
}
/**
* <p>
* Indicates whether the job flow is visible to all IAM users of the AWS
* account associated with the job flow. If this value is set to
* <code>true</code>, all IAM users of that AWS account can view and manage
* the job flow if they have the proper policy permissions set. If this
* value is <code>false</code>, only the IAM user that created the cluster
* can view and manage it. This value can be changed using the
* <a>SetVisibleToAllUsers</a> action.
* </p>
*
* @param visibleToAllUsers
* Indicates whether the job flow is visible to all IAM users of the
* AWS account associated with the job flow. If this value is set to
* <code>true</code>, all IAM users of that AWS account can view and
* manage the job flow if they have the proper policy permissions
* set. If this value is <code>false</code>, only the IAM user that
* created the cluster can view and manage it. This value can be
* changed using the <a>SetVisibleToAllUsers</a> action.
*/
public void setVisibleToAllUsers(Boolean visibleToAllUsers) {
this.visibleToAllUsers = visibleToAllUsers;
}
/**
* <p>
* Indicates whether the job flow is visible to all IAM users of the AWS
* account associated with the job flow. If this value is set to
* <code>true</code>, all IAM users of that AWS account can view and manage
* the job flow if they have the proper policy permissions set. If this
* value is <code>false</code>, only the IAM user that created the cluster
* can view and manage it. This value can be changed using the
* <a>SetVisibleToAllUsers</a> action.
* </p>
*
* @return Indicates whether the job flow is visible to all IAM users of the
* AWS account associated with the job flow. If this value is set to
* <code>true</code>, all IAM users of that AWS account can view and
* manage the job flow if they have the proper policy permissions
* set. If this value is <code>false</code>, only the IAM user that
* created the cluster can view and manage it. This value can be
* changed using the <a>SetVisibleToAllUsers</a> action.
*/
public Boolean getVisibleToAllUsers() {
return this.visibleToAllUsers;
}
/**
* <p>
* Indicates whether the job flow is visible to all IAM users of the AWS
* account associated with the job flow. If this value is set to
* <code>true</code>, all IAM users of that AWS account can view and manage
* the job flow if they have the proper policy permissions set. If this
* value is <code>false</code>, only the IAM user that created the cluster
* can view and manage it. This value can be changed using the
* <a>SetVisibleToAllUsers</a> action.
* </p>
*
* @param visibleToAllUsers
* Indicates whether the job flow is visible to all IAM users of the
* AWS account associated with the job flow. If this value is set to
* <code>true</code>, all IAM users of that AWS account can view and
* manage the job flow if they have the proper policy permissions
* set. If this value is <code>false</code>, only the IAM user that
* created the cluster can view and manage it. This value can be
* changed using the <a>SetVisibleToAllUsers</a> action.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public Cluster withVisibleToAllUsers(Boolean visibleToAllUsers) {
setVisibleToAllUsers(visibleToAllUsers);
return this;
}
/**
* <p>
* Indicates whether the job flow is visible to all IAM users of the AWS
* account associated with the job flow. If this value is set to
* <code>true</code>, all IAM users of that AWS account can view and manage
* the job flow if they have the proper policy permissions set. If this
* value is <code>false</code>, only the IAM user that created the cluster
* can view and manage it. This value can be changed using the
* <a>SetVisibleToAllUsers</a> action.
* </p>
*
* @return Indicates whether the job flow is visible to all IAM users of the
* AWS account associated with the job flow. If this value is set to
* <code>true</code>, all IAM users of that AWS account can view and
* manage the job flow if they have the proper policy permissions
* set. If this value is <code>false</code>, only the IAM user that
* created the cluster can view and manage it. This value can be
* changed using the <a>SetVisibleToAllUsers</a> action.
*/
public Boolean isVisibleToAllUsers() {
return this.visibleToAllUsers;
}
/**
* <p>
* The applications installed on this cluster.
* </p>
*
* @return The applications installed on this cluster.
*/
public java.util.List<Application> getApplications() {
if (applications == null) {
applications = new com.amazonaws.internal.SdkInternalList<Application>();
}
return applications;
}
/**
* <p>
* The applications installed on this cluster.
* </p>
*
* @param applications
* The applications installed on this cluster.
*/
public void setApplications(java.util.Collection<Application> applications) {
if (applications == null) {
this.applications = null;
return;
}
this.applications = new com.amazonaws.internal.SdkInternalList<Application>(
applications);
}
/**
* <p>
* The applications installed on this cluster.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if
* any). Use {@link #setApplications(java.util.Collection)} or
* {@link #withApplications(java.util.Collection)} if you want to override
* the existing values.
* </p>
*
* @param applications
* The applications installed on this cluster.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public Cluster withApplications(Application... applications) {
if (this.applications == null) {
setApplications(new com.amazonaws.internal.SdkInternalList<Application>(
applications.length));
}
for (Application ele : applications) {
this.applications.add(ele);
}
return this;
}
/**
* <p>
* The applications installed on this cluster.
* </p>
*
* @param applications
* The applications installed on this cluster.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public Cluster withApplications(
java.util.Collection<Application> applications) {
setApplications(applications);
return this;
}
/**
* <p>
* A list of tags associated with a cluster.
* </p>
*
* @return A list of tags associated with a cluster.
*/
public java.util.List<Tag> getTags() {
if (tags == null) {
tags = new com.amazonaws.internal.SdkInternalList<Tag>();
}
return tags;
}
/**
* <p>
* A list of tags associated with a cluster.
* </p>
*
* @param tags
* A list of tags associated with a cluster.
*/
public void setTags(java.util.Collection<Tag> tags) {
if (tags == null) {
this.tags = null;
return;
}
this.tags = new com.amazonaws.internal.SdkInternalList<Tag>(tags);
}
/**
* <p>
* A list of tags associated with a cluster.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if
* any). Use {@link #setTags(java.util.Collection)} or
* {@link #withTags(java.util.Collection)} if you want to override the
* existing values.
* </p>
*
* @param tags
* A list of tags associated with a cluster.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public Cluster withTags(Tag... tags) {
if (this.tags == null) {
setTags(new com.amazonaws.internal.SdkInternalList<Tag>(tags.length));
}
for (Tag ele : tags) {
this.tags.add(ele);
}
return this;
}
/**
* <p>
* A list of tags associated with a cluster.
* </p>
*
* @param tags
* A list of tags associated with a cluster.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public Cluster withTags(java.util.Collection<Tag> tags) {
setTags(tags);
return this;
}
/**
* <p>
* The IAM role that will be assumed by the Amazon EMR service to access AWS
* resources on your behalf.
* </p>
*
* @param serviceRole
* The IAM role that will be assumed by the Amazon EMR service to
* access AWS resources on your behalf.
*/
public void setServiceRole(String serviceRole) {
this.serviceRole = serviceRole;
}
/**
* <p>
* The IAM role that will be assumed by the Amazon EMR service to access AWS
* resources on your behalf.
* </p>
*
* @return The IAM role that will be assumed by the Amazon EMR service to
* access AWS resources on your behalf.
*/
public String getServiceRole() {
return this.serviceRole;
}
/**
* <p>
* The IAM role that will be assumed by the Amazon EMR service to access AWS
* resources on your behalf.
* </p>
*
* @param serviceRole
* The IAM role that will be assumed by the Amazon EMR service to
* access AWS resources on your behalf.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public Cluster withServiceRole(String serviceRole) {
setServiceRole(serviceRole);
return this;
}
/**
* <p>
* An approximation of the cost of the job flow, represented in
* m1.small/hours. This value is incremented one time for every hour an
* m1.small instance runs. Larger instances are weighted more, so an EC2
* instance that is roughly four times more expensive would result in the
* normalized instance hours being incremented by four. This result is only
* an approximation and does not reflect the actual billing rate.
* </p>
*
* @param normalizedInstanceHours
* An approximation of the cost of the job flow, represented in
* m1.small/hours. This value is incremented one time for every hour
* an m1.small instance runs. Larger instances are weighted more, so
* an EC2 instance that is roughly four times more expensive would
* result in the normalized instance hours being incremented by four.
* This result is only an approximation and does not reflect the
* actual billing rate.
*/
public void setNormalizedInstanceHours(Integer normalizedInstanceHours) {
this.normalizedInstanceHours = normalizedInstanceHours;
}
/**
* <p>
* An approximation of the cost of the job flow, represented in
* m1.small/hours. This value is incremented one time for every hour an
* m1.small instance runs. Larger instances are weighted more, so an EC2
* instance that is roughly four times more expensive would result in the
* normalized instance hours being incremented by four. This result is only
* an approximation and does not reflect the actual billing rate.
* </p>
*
* @return An approximation of the cost of the job flow, represented in
* m1.small/hours. This value is incremented one time for every hour
* an m1.small instance runs. Larger instances are weighted more, so
* an EC2 instance that is roughly four times more expensive would
* result in the normalized instance hours being incremented by
* four. This result is only an approximation and does not reflect
* the actual billing rate.
*/
public Integer getNormalizedInstanceHours() {
return this.normalizedInstanceHours;
}
/**
* <p>
* An approximation of the cost of the job flow, represented in
* m1.small/hours. This value is incremented one time for every hour an
* m1.small instance runs. Larger instances are weighted more, so an EC2
* instance that is roughly four times more expensive would result in the
* normalized instance hours being incremented by four. This result is only
* an approximation and does not reflect the actual billing rate.
* </p>
*
* @param normalizedInstanceHours
* An approximation of the cost of the job flow, represented in
* m1.small/hours. This value is incremented one time for every hour
* an m1.small instance runs. Larger instances are weighted more, so
* an EC2 instance that is roughly four times more expensive would
* result in the normalized instance hours being incremented by four.
* This result is only an approximation and does not reflect the
* actual billing rate.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public Cluster withNormalizedInstanceHours(Integer normalizedInstanceHours) {
setNormalizedInstanceHours(normalizedInstanceHours);
return this;
}
/**
* <p>
* The public DNS name of the master EC2 instance.
* </p>
*
* @param masterPublicDnsName
* The public DNS name of the master EC2 instance.
*/
public void setMasterPublicDnsName(String masterPublicDnsName) {
this.masterPublicDnsName = masterPublicDnsName;
}
/**
* <p>
* The public DNS name of the master EC2 instance.
* </p>
*
* @return The public DNS name of the master EC2 instance.
*/
public String getMasterPublicDnsName() {
return this.masterPublicDnsName;
}
/**
* <p>
* The public DNS name of the master EC2 instance.
* </p>
*
* @param masterPublicDnsName
* The public DNS name of the master EC2 instance.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public Cluster withMasterPublicDnsName(String masterPublicDnsName) {
setMasterPublicDnsName(masterPublicDnsName);
return this;
}
/**
* <note>
* <p>
* Amazon EMR releases 4.x or later.
* </p>
* </note>
* <p>
* The list of Configurations supplied to the EMR cluster.
* </p>
*
* @return <p>
* Amazon EMR releases 4.x or later.
* </p>
* </note>
* <p>
* The list of Configurations supplied to the EMR cluster.
*/
public java.util.List<Configuration> getConfigurations() {
if (configurations == null) {
configurations = new com.amazonaws.internal.SdkInternalList<Configuration>();
}
return configurations;
}
/**
* <note>
* <p>
* Amazon EMR releases 4.x or later.
* </p>
* </note>
* <p>
* The list of Configurations supplied to the EMR cluster.
* </p>
*
* @param configurations
* <p>
* Amazon EMR releases 4.x or later.
* </p>
* </note>
* <p>
* The list of Configurations supplied to the EMR cluster.
*/
public void setConfigurations(
java.util.Collection<Configuration> configurations) {
if (configurations == null) {
this.configurations = null;
return;
}
this.configurations = new com.amazonaws.internal.SdkInternalList<Configuration>(
configurations);
}
/**
* <note>
* <p>
* Amazon EMR releases 4.x or later.
* </p>
* </note>
* <p>
* The list of Configurations supplied to the EMR cluster.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if
* any). Use {@link #setConfigurations(java.util.Collection)} or
* {@link #withConfigurations(java.util.Collection)} if you want to override
* the existing values.
* </p>
*
* @param configurations
* <p>
* Amazon EMR releases 4.x or later.
* </p>
* </note>
* <p>
* The list of Configurations supplied to the EMR cluster.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public Cluster withConfigurations(Configuration... configurations) {
if (this.configurations == null) {
setConfigurations(new com.amazonaws.internal.SdkInternalList<Configuration>(
configurations.length));
}
for (Configuration ele : configurations) {
this.configurations.add(ele);
}
return this;
}
/**
* <note>
* <p>
* Amazon EMR releases 4.x or later.
* </p>
* </note>
* <p>
* The list of Configurations supplied to the EMR cluster.
* </p>
*
* @param configurations
* <p>
* Amazon EMR releases 4.x or later.
* </p>
* </note>
* <p>
* The list of Configurations supplied to the EMR cluster.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public Cluster withConfigurations(
java.util.Collection<Configuration> configurations) {
setConfigurations(configurations);
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getId() != null)
sb.append("Id: " + getId() + ",");
if (getName() != null)
sb.append("Name: " + getName() + ",");
if (getStatus() != null)
sb.append("Status: " + getStatus() + ",");
if (getEc2InstanceAttributes() != null)
sb.append("Ec2InstanceAttributes: " + getEc2InstanceAttributes()
+ ",");
if (getLogUri() != null)
sb.append("LogUri: " + getLogUri() + ",");
if (getRequestedAmiVersion() != null)
sb.append("RequestedAmiVersion: " + getRequestedAmiVersion() + ",");
if (getRunningAmiVersion() != null)
sb.append("RunningAmiVersion: " + getRunningAmiVersion() + ",");
if (getReleaseLabel() != null)
sb.append("ReleaseLabel: " + getReleaseLabel() + ",");
if (getAutoTerminate() != null)
sb.append("AutoTerminate: " + getAutoTerminate() + ",");
if (getTerminationProtected() != null)
sb.append("TerminationProtected: " + getTerminationProtected()
+ ",");
if (getVisibleToAllUsers() != null)
sb.append("VisibleToAllUsers: " + getVisibleToAllUsers() + ",");
if (getApplications() != null)
sb.append("Applications: " + getApplications() + ",");
if (getTags() != null)
sb.append("Tags: " + getTags() + ",");
if (getServiceRole() != null)
sb.append("ServiceRole: " + getServiceRole() + ",");
if (getNormalizedInstanceHours() != null)
sb.append("NormalizedInstanceHours: "
+ getNormalizedInstanceHours() + ",");
if (getMasterPublicDnsName() != null)
sb.append("MasterPublicDnsName: " + getMasterPublicDnsName() + ",");
if (getConfigurations() != null)
sb.append("Configurations: " + getConfigurations());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof Cluster == false)
return false;
Cluster other = (Cluster) obj;
if (other.getId() == null ^ this.getId() == null)
return false;
if (other.getId() != null
&& other.getId().equals(this.getId()) == false)
return false;
if (other.getName() == null ^ this.getName() == null)
return false;
if (other.getName() != null
&& other.getName().equals(this.getName()) == false)
return false;
if (other.getStatus() == null ^ this.getStatus() == null)
return false;
if (other.getStatus() != null
&& other.getStatus().equals(this.getStatus()) == false)
return false;
if (other.getEc2InstanceAttributes() == null
^ this.getEc2InstanceAttributes() == null)
return false;
if (other.getEc2InstanceAttributes() != null
&& other.getEc2InstanceAttributes().equals(
this.getEc2InstanceAttributes()) == false)
return false;
if (other.getLogUri() == null ^ this.getLogUri() == null)
return false;
if (other.getLogUri() != null
&& other.getLogUri().equals(this.getLogUri()) == false)
return false;
if (other.getRequestedAmiVersion() == null
^ this.getRequestedAmiVersion() == null)
return false;
if (other.getRequestedAmiVersion() != null
&& other.getRequestedAmiVersion().equals(
this.getRequestedAmiVersion()) == false)
return false;
if (other.getRunningAmiVersion() == null
^ this.getRunningAmiVersion() == null)
return false;
if (other.getRunningAmiVersion() != null
&& other.getRunningAmiVersion().equals(
this.getRunningAmiVersion()) == false)
return false;
if (other.getReleaseLabel() == null ^ this.getReleaseLabel() == null)
return false;
if (other.getReleaseLabel() != null
&& other.getReleaseLabel().equals(this.getReleaseLabel()) == false)
return false;
if (other.getAutoTerminate() == null ^ this.getAutoTerminate() == null)
return false;
if (other.getAutoTerminate() != null
&& other.getAutoTerminate().equals(this.getAutoTerminate()) == false)
return false;
if (other.getTerminationProtected() == null
^ this.getTerminationProtected() == null)
return false;
if (other.getTerminationProtected() != null
&& other.getTerminationProtected().equals(
this.getTerminationProtected()) == false)
return false;
if (other.getVisibleToAllUsers() == null
^ this.getVisibleToAllUsers() == null)
return false;
if (other.getVisibleToAllUsers() != null
&& other.getVisibleToAllUsers().equals(
this.getVisibleToAllUsers()) == false)
return false;
if (other.getApplications() == null ^ this.getApplications() == null)
return false;
if (other.getApplications() != null
&& other.getApplications().equals(this.getApplications()) == false)
return false;
if (other.getTags() == null ^ this.getTags() == null)
return false;
if (other.getTags() != null
&& other.getTags().equals(this.getTags()) == false)
return false;
if (other.getServiceRole() == null ^ this.getServiceRole() == null)
return false;
if (other.getServiceRole() != null
&& other.getServiceRole().equals(this.getServiceRole()) == false)
return false;
if (other.getNormalizedInstanceHours() == null
^ this.getNormalizedInstanceHours() == null)
return false;
if (other.getNormalizedInstanceHours() != null
&& other.getNormalizedInstanceHours().equals(
this.getNormalizedInstanceHours()) == false)
return false;
if (other.getMasterPublicDnsName() == null
^ this.getMasterPublicDnsName() == null)
return false;
if (other.getMasterPublicDnsName() != null
&& other.getMasterPublicDnsName().equals(
this.getMasterPublicDnsName()) == false)
return false;
if (other.getConfigurations() == null
^ this.getConfigurations() == null)
return false;
if (other.getConfigurations() != null
&& other.getConfigurations().equals(this.getConfigurations()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode
+ ((getId() == null) ? 0 : getId().hashCode());
hashCode = prime * hashCode
+ ((getName() == null) ? 0 : getName().hashCode());
hashCode = prime * hashCode
+ ((getStatus() == null) ? 0 : getStatus().hashCode());
hashCode = prime
* hashCode
+ ((getEc2InstanceAttributes() == null) ? 0
: getEc2InstanceAttributes().hashCode());
hashCode = prime * hashCode
+ ((getLogUri() == null) ? 0 : getLogUri().hashCode());
hashCode = prime
* hashCode
+ ((getRequestedAmiVersion() == null) ? 0
: getRequestedAmiVersion().hashCode());
hashCode = prime
* hashCode
+ ((getRunningAmiVersion() == null) ? 0
: getRunningAmiVersion().hashCode());
hashCode = prime
* hashCode
+ ((getReleaseLabel() == null) ? 0 : getReleaseLabel()
.hashCode());
hashCode = prime
* hashCode
+ ((getAutoTerminate() == null) ? 0 : getAutoTerminate()
.hashCode());
hashCode = prime
* hashCode
+ ((getTerminationProtected() == null) ? 0
: getTerminationProtected().hashCode());
hashCode = prime
* hashCode
+ ((getVisibleToAllUsers() == null) ? 0
: getVisibleToAllUsers().hashCode());
hashCode = prime
* hashCode
+ ((getApplications() == null) ? 0 : getApplications()
.hashCode());
hashCode = prime * hashCode
+ ((getTags() == null) ? 0 : getTags().hashCode());
hashCode = prime
* hashCode
+ ((getServiceRole() == null) ? 0 : getServiceRole().hashCode());
hashCode = prime
* hashCode
+ ((getNormalizedInstanceHours() == null) ? 0
: getNormalizedInstanceHours().hashCode());
hashCode = prime
* hashCode
+ ((getMasterPublicDnsName() == null) ? 0
: getMasterPublicDnsName().hashCode());
hashCode = prime
* hashCode
+ ((getConfigurations() == null) ? 0 : getConfigurations()
.hashCode());
return hashCode;
}
@Override
public Cluster clone() {
try {
return (Cluster) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!", e);
}
}
}
| 32.511913 | 89 | 0.580737 |
c67223224bd99ac7742dea41ff2f57f3861ca43d | 1,304 | package com.twu.biblioteca;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class BookTest {
@Test
public void getNameTest() {
Book book = new Book("1984", "George Orwell", 1949);
assertEquals("1984", book.getName());
}
@Test
public void getAuthorTest() {
Book book = new Book("1984", "George Orwell", 1949);
assertEquals("George Orwell", book.getAuthor());
}
@Test
public void getYearPublishedTest() {
Book book = new Book("1984", "George Orwell", 1949);
assertEquals(1949, book.getYearPublished());
}
@Test
public void shouldSuccessfullyCheckInAnAvailableBook() {
Book book = new Book("1984", "George Orwell", 1949);
book.checkIn();
assertTrue(book.isCheckedIn());
}
@Test
public void shouldSuccessfullyCheckOutAnAvailableBook() {
Book book = new Book("1984", "George Orwell", 1949);
book.checkOut();
assertEquals(false, book.isCheckedIn());
}
/*@Test
public void shouldUnsuccessfullyCheckOutAnUnavailableBook() {
Book book = new Book("1984", "GeorgeOrwell", 1949);
book.checkOut();
assertEquals(false, book.isCheckedIn());
}*/
}
| 26.08 | 65 | 0.630368 |
b3c74add09b013eeec28d987618d14d045dd2517 | 1,312 | /*
* Copyright © 2013-2016 The Nxt Core Developers.
* Copyright © 2016-2020 Jelurida IP B.V.
*
* See the LICENSE.txt file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with Jelurida B.V.,
* no part of the Nxt software, including this file, may be copied, modified,
* propagated, or distributed except according to the terms contained in the
* LICENSE.txt file.
*
* Removal or modification of this copyright notice is prohibited.
*
*/
package nxt.http;
import nxt.Account;
import nxt.Attachment;
import nxt.NxtException;
import org.json.simple.JSONStreamAware;
import javax.servlet.http.HttpServletRequest;
public final class SendMessage extends CreateTransaction {
static final SendMessage instance = new SendMessage();
private SendMessage() {
super(new APITag[] {APITag.MESSAGES, APITag.CREATE_TRANSACTION}, "recipient");
}
@Override
protected JSONStreamAware processRequest(HttpServletRequest req) throws NxtException {
long recipientId = ParameterParser.getAccountId(req, "recipient", false);
Account account = ParameterParser.getSenderAccount(req);
return createTransaction(req, account, recipientId, 0, Attachment.ARBITRARY_MESSAGE);
}
}
| 31.238095 | 93 | 0.747713 |
be18d641955b74bb7efbbefc5f0e08580c1e66b9 | 13,587 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2;
import android.os.Handler;
import android.os.HandlerThread;
import com.google.android.exoplayer2.decoder.DecoderInputBuffer;
import com.google.android.exoplayer2.source.MediaPeriod;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.SampleStream;
import com.google.android.exoplayer2.source.SinglePeriodTimeline;
import com.google.android.exoplayer2.source.TrackGroup;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelection;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.upstream.Allocator;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.MimeTypes;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import junit.framework.TestCase;
/**
* Unit test for {@link ExoPlayer}.
*/
public final class ExoPlayerTest extends TestCase {
/**
* For tests that rely on the player transitioning to the ended state, the duration in
* milliseconds after starting the player before the test will time out. This is to catch cases
* where the player under test is not making progress, in which case the test should fail.
*/
private static final int TIMEOUT_MS = 10000;
public void testPlayToEnd() throws Exception {
PlayerWrapper playerWrapper = new PlayerWrapper();
Format format = Format.createVideoSampleFormat(null, MimeTypes.VIDEO_H264, null,
Format.NO_VALUE, Format.NO_VALUE, 1280, 720, Format.NO_VALUE, null, null);
playerWrapper.setup(new SinglePeriodTimeline(0, false), new Object(), format);
playerWrapper.blockUntilEndedOrError(TIMEOUT_MS);
}
/**
* Wraps a player with its own handler thread.
*/
private static final class PlayerWrapper implements ExoPlayer.EventListener {
private final CountDownLatch endedCountDownLatch;
private final HandlerThread playerThread;
private final Handler handler;
private Timeline expectedTimeline;
private Object expectedManifest;
private Format expectedFormat;
private ExoPlayer player;
private Exception exception;
private boolean seenPositionDiscontinuity;
public PlayerWrapper() {
endedCountDownLatch = new CountDownLatch(1);
playerThread = new HandlerThread("ExoPlayerTest thread");
playerThread.start();
handler = new Handler(playerThread.getLooper());
}
// Called on the test thread.
public void blockUntilEndedOrError(long timeoutMs) throws Exception {
if (!endedCountDownLatch.await(timeoutMs, TimeUnit.MILLISECONDS)) {
exception = new TimeoutException("Test playback timed out.");
}
release();
// Throw any pending exception (from playback, timing out or releasing).
if (exception != null) {
throw exception;
}
}
public void setup(final Timeline timeline, final Object manifest, final Format format) {
expectedTimeline = timeline;
expectedManifest = manifest;
expectedFormat = format;
handler.post(new Runnable() {
@Override
public void run() {
try {
Renderer fakeRenderer = new FakeVideoRenderer(expectedFormat);
player = ExoPlayerFactory.newInstance(new Renderer[] {fakeRenderer},
new DefaultTrackSelector());
player.addListener(PlayerWrapper.this);
player.setPlayWhenReady(true);
player.prepare(new FakeMediaSource(timeline, manifest, format));
} catch (Exception e) {
handlePlayerException(e);
}
}
});
}
public void release() throws InterruptedException {
handler.post(new Runnable() {
@Override
public void run() {
try {
if (player != null) {
player.release();
}
} catch (Exception e) {
handlePlayerException(e);
} finally {
playerThread.quit();
}
}
});
playerThread.join();
}
private void handlePlayerException(Exception exception) {
if (this.exception == null) {
this.exception = exception;
}
endedCountDownLatch.countDown();
}
// ExoPlayer.EventListener implementation.
@Override
public void onLoadingChanged(boolean isLoading) {
// Do nothing.
}
@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if (playbackState == ExoPlayer.STATE_ENDED) {
endedCountDownLatch.countDown();
}
}
@Override
public void onTimelineChanged(Timeline timeline, Object manifest) {
assertEquals(expectedTimeline, timeline);
assertEquals(expectedManifest, manifest);
}
@Override
public void onTracksChanged(TrackGroupArray trackGroups,
TrackSelectionArray trackSelections) {
assertEquals(new TrackGroupArray(new TrackGroup(expectedFormat)), trackGroups);
}
@Override
public void onPlayerError(ExoPlaybackException exception) {
this.exception = exception;
endedCountDownLatch.countDown();
}
@Override
public void onPositionDiscontinuity() {
assertFalse(seenPositionDiscontinuity);
assertEquals(0, player.getCurrentWindowIndex());
assertEquals(0, player.getCurrentPeriodIndex());
assertEquals(0, player.getCurrentPosition());
assertEquals(0, player.getBufferedPosition());
assertEquals(expectedTimeline, player.getCurrentTimeline());
assertEquals(expectedManifest, player.getCurrentManifest());
seenPositionDiscontinuity = true;
}
}
/**
* Fake {@link MediaSource} that provides a given timeline (which must have one period). Creating
* the period will return a {@link FakeMediaPeriod}.
*/
private static final class FakeMediaSource implements MediaSource {
private final Timeline timeline;
private final Object manifest;
private final Format format;
private FakeMediaPeriod mediaPeriod;
private boolean preparedSource;
private boolean releasedPeriod;
private boolean releasedSource;
public FakeMediaSource(Timeline timeline, Object manifest, Format format) {
Assertions.checkArgument(timeline.getPeriodCount() == 1);
this.timeline = timeline;
this.manifest = manifest;
this.format = format;
}
@Override
public void prepareSource(ExoPlayer player, boolean isTopLevelSource, Listener listener) {
assertFalse(preparedSource);
preparedSource = true;
listener.onSourceInfoRefreshed(timeline, manifest);
}
@Override
public void maybeThrowSourceInfoRefreshError() throws IOException {
assertTrue(preparedSource);
}
@Override
public MediaPeriod createPeriod(int index, Allocator allocator, long positionUs) {
assertTrue(preparedSource);
assertNull(mediaPeriod);
assertFalse(releasedPeriod);
assertFalse(releasedSource);
assertEquals(0, index);
assertEquals(0, positionUs);
mediaPeriod = new FakeMediaPeriod(format);
return mediaPeriod;
}
@Override
public void releasePeriod(MediaPeriod mediaPeriod) {
assertTrue(preparedSource);
assertNotNull(this.mediaPeriod);
assertFalse(releasedPeriod);
assertFalse(releasedSource);
assertEquals(this.mediaPeriod, mediaPeriod);
this.mediaPeriod.release();
releasedPeriod = true;
}
@Override
public void releaseSource() {
assertTrue(preparedSource);
assertNotNull(this.mediaPeriod);
assertTrue(releasedPeriod);
assertFalse(releasedSource);
releasedSource = true;
}
}
/**
* Fake {@link MediaPeriod} that provides one track with a given {@link Format}. Selecting that
* track will give the player a {@link FakeSampleStream}.
*/
private static final class FakeMediaPeriod implements MediaPeriod {
private final TrackGroup trackGroup;
private boolean preparedPeriod;
public FakeMediaPeriod(Format format) {
trackGroup = new TrackGroup(format);
}
public void release() {
preparedPeriod = false;
}
@Override
public void prepare(Callback callback) {
assertFalse(preparedPeriod);
preparedPeriod = true;
callback.onPrepared(this);
}
@Override
public void maybeThrowPrepareError() throws IOException {
assertTrue(preparedPeriod);
}
@Override
public TrackGroupArray getTrackGroups() {
assertTrue(preparedPeriod);
return new TrackGroupArray(trackGroup);
}
@Override
public long selectTracks(TrackSelection[] selections, boolean[] mayRetainStreamFlags,
SampleStream[] streams, boolean[] streamResetFlags, long positionUs) {
assertTrue(preparedPeriod);
assertEquals(1, selections.length);
assertEquals(1, mayRetainStreamFlags.length);
assertEquals(1, streams.length);
assertEquals(1, streamResetFlags.length);
assertEquals(0, positionUs);
if (streams[0] != null && (selections[0] == null || !mayRetainStreamFlags[0])) {
streams[0] = null;
}
if (streams[0] == null && selections[0] != null) {
FakeSampleStream stream = new FakeSampleStream(trackGroup.getFormat(0));
assertEquals(trackGroup, selections[0].getTrackGroup());
streams[0] = stream;
streamResetFlags[0] = true;
}
return 0;
}
@Override
public long readDiscontinuity() {
assertTrue(preparedPeriod);
return C.TIME_UNSET;
}
@Override
public long getBufferedPositionUs() {
assertTrue(preparedPeriod);
return C.TIME_END_OF_SOURCE;
}
@Override
public long seekToUs(long positionUs) {
assertTrue(preparedPeriod);
assertEquals(0, positionUs);
return positionUs;
}
@Override
public long getNextLoadPositionUs() {
assertTrue(preparedPeriod);
return 0;
}
@Override
public boolean continueLoading(long positionUs) {
assertTrue(preparedPeriod);
return false;
}
}
/**
* Fake {@link SampleStream} that outputs a given {@link Format} then sets the end of stream flag
* on its input buffer.
*/
private static final class FakeSampleStream implements SampleStream {
private final Format format;
private boolean readFormat;
private boolean readEndOfStream;
public FakeSampleStream(Format format) {
this.format = format;
}
@Override
public boolean isReady() {
return true;
}
@Override
public int readData(FormatHolder formatHolder, DecoderInputBuffer buffer) {
Assertions.checkState(!readEndOfStream);
if (readFormat) {
buffer.setFlags(C.BUFFER_FLAG_END_OF_STREAM);
readEndOfStream = true;
return C.RESULT_BUFFER_READ;
}
formatHolder.format = format;
readFormat = true;
return C.RESULT_FORMAT_READ;
}
@Override
public void maybeThrowError() throws IOException {
// Do nothing.
}
@Override
public void skipToKeyframeBefore(long timeUs) {
// Do nothing.
}
}
/**
* Fake {@link Renderer} that supports any video format. The renderer verifies that it reads a
* given {@link Format} then a buffer with the end of stream flag set.
*/
private static final class FakeVideoRenderer extends BaseRenderer {
private final Format expectedFormat;
private boolean isEnded;
public FakeVideoRenderer(Format expectedFormat) {
super(C.TRACK_TYPE_VIDEO);
Assertions.checkArgument(MimeTypes.isVideo(expectedFormat.sampleMimeType));
this.expectedFormat = expectedFormat;
}
@Override
public void render(long positionUs, long elapsedRealtimeUs) throws ExoPlaybackException {
if (isEnded) {
return;
}
// Verify the format matches the expected format.
FormatHolder formatHolder = new FormatHolder();
readSource(formatHolder, null);
assertEquals(expectedFormat, formatHolder.format);
// Verify that we get an end-of-stream buffer.
DecoderInputBuffer buffer =
new DecoderInputBuffer(DecoderInputBuffer.BUFFER_REPLACEMENT_MODE_NORMAL);
readSource(null, buffer);
assertTrue(buffer.isEndOfStream());
isEnded = true;
}
@Override
public boolean isReady() {
return isEnded;
}
@Override
public boolean isEnded() {
return isEnded;
}
@Override
public int supportsFormat(Format format) throws ExoPlaybackException {
return MimeTypes.isVideo(format.sampleMimeType) ? FORMAT_HANDLED : FORMAT_UNSUPPORTED_TYPE;
}
}
}
| 30.601351 | 99 | 0.694046 |
321af5abdfeae33f3e00cbc1f7ee2f9447554984 | 1,080 | package net.george.alltestdemo;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import net.george.alltestdemo.adapter.PagerAdapter;
/**
* @author George
* @date 2018/1/9
* @email [email protected]
* @describe Android各种基本控件的测试Activity
*/
public class BasicComponentActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basic_component);
ViewPager viewPager = (ViewPager)findViewById(R.id.view_pager);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
TabLayout tabLayout = (TabLayout)findViewById(R.id.tab_layout);
// 必须在ViewPager setAdapter之后调用
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
}
}
| 32.727273 | 82 | 0.761111 |
10f2fd9631342f7d8b550f57a1c4f083df5f5055 | 219 | package swingdemo;
public class SwingImple
{
public static void main(String[] args)
{
System.out.println("Creating an Object of SwingDemo...");
SwingDemo obj = null;
obj = new SwingDemo();
}
}
| 15.642857 | 60 | 0.643836 |
321d1aa0c58428d8fc1810c1dcbb1216068dc7ec | 1,159 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFilextem/Templates/Classes/Class.java to edit this template
*/
package fxproject.filters.locals;
import fxproject.models.RawImage;
/**
*
* @author vixx_
*/
public class CircleFilter {
public static RawImage apply(RawImage img, int width, int height, int x1, int y1, int x2, int y2) {
float[] kernel = new float[width * height];
int centerX = width / 2, centerY = height / 2;
int ww = width * width, hh = height * height;
int r = ww * hh;
for (int y=0; y<height; y++) {
for (int x=0; x<width; x++) {
int xw = (x - centerX), yh = (y - centerY);
kernel[y * width + x] = (xw*xw*hh + yh*yh*ww <= r) ? 1.0f : 0.0f;
}
}
return KernelFilter.apply(img, kernel, width, height, x1, y1, x2, y2);
}
public static RawImage apply(RawImage img, int width, int height) {
RawImage another = CircleFilter.apply(img, width, height, 0, 0, img.width - 1, img.height - 1);
return another;
}
}
| 35.121212 | 103 | 0.593615 |
b4c018b7bce22a1c3eea7cf7db3be3e16f36e412 | 131 | package it.unibz.inf.ontop.iq.optimizer;
public interface PushUpBooleanExpressionOptimizer extends IntermediateQueryOptimizer{
}
| 21.833333 | 85 | 0.862595 |
5796f9c99b9a02fe2ab5cddddcfb60b7b4e480b6 | 2,633 | package jetbrains.mps.lang.behavior.typesystem;
/*Generated by MPS */
import jetbrains.mps.lang.typesystem.runtime.AbstractNonTypesystemRule_Runtime;
import jetbrains.mps.lang.typesystem.runtime.NonTypesystemRule_Runtime;
import org.jetbrains.mps.openapi.model.SNode;
import jetbrains.mps.typesystem.inference.TypeCheckingContext;
import jetbrains.mps.lang.typesystem.runtime.IsApplicableStatus;
import jetbrains.mps.lang.behavior.behavior.ConceptMethodDeclaration__BehaviorDescriptor;
import jetbrains.mps.errors.messageTargets.MessageTarget;
import jetbrains.mps.errors.messageTargets.NodeMessageTarget;
import jetbrains.mps.errors.IErrorReporter;
import jetbrains.mps.errors.BaseQuickFixProvider;
import org.jetbrains.mps.openapi.language.SAbstractConcept;
import org.jetbrains.mps.openapi.language.SConcept;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
public class check_MethodIsCorrectlyOverriden_NonTypesystemRule extends AbstractNonTypesystemRule_Runtime implements NonTypesystemRule_Runtime {
public check_MethodIsCorrectlyOverriden_NonTypesystemRule() {
}
public void applyRule(final SNode method, final TypeCheckingContext typeCheckingContext, IsApplicableStatus status) {
if (!((boolean) ConceptMethodDeclaration__BehaviorDescriptor.isCorrectlyOverriden_idhQYykEj.invoke(method))) {
{
final MessageTarget errorTarget = new NodeMessageTarget();
IErrorReporter _reporter_2309309498 = typeCheckingContext.reportTypeError(method, "Method signature doesn't match signature in the base concept", "r:f7f8a091-d98d-402d-85c4-5f05cb2b8c61(jetbrains.mps.lang.behavior.typesystem)", "1227262769261", null, errorTarget);
{
BaseQuickFixProvider intentionProvider = new BaseQuickFixProvider("jetbrains.mps.lang.behavior.typesystem.FixMethodSignature_QuickFix", "3834658221333161527", false);
intentionProvider.putArgument("conceptMethod", method);
_reporter_2309309498.addIntentionProvider(intentionProvider);
}
}
}
}
public SAbstractConcept getApplicableConcept() {
return CONCEPTS.ConceptMethodDeclaration$N0;
}
public IsApplicableStatus isApplicableAndPattern(SNode argument) {
return new IsApplicableStatus(argument.getConcept().isSubConceptOf(getApplicableConcept()), null);
}
public boolean overrides() {
return false;
}
private static final class CONCEPTS {
/*package*/ static final SConcept ConceptMethodDeclaration$N0 = MetaAdapterFactory.getConcept(0xaf65afd8f0dd4942L, 0x87d963a55f2a9db1L, 0x11d4348057eL, "jetbrains.mps.lang.behavior.structure.ConceptMethodDeclaration");
}
}
| 53.734694 | 272 | 0.816559 |
142012389695d7eae48fdd4a2346682d4227041a | 114 | package com.budget.wiz.skip.app.domain.value;
public enum BudgetStatus {
APPROVED, CANCELED, IN_PROCESS;
}
| 14.25 | 45 | 0.745614 |
d41e858a4a2fd8c332b563c7ebe01940d393ed21 | 2,963 | package net.robinfriedli.jxp.persist;
import java.io.File;
import java.util.List;
import java.util.Objects;
import org.slf4j.Logger;
import com.google.common.collect.Lists;
import net.robinfriedli.jxp.api.JxpBackend;
import net.robinfriedli.jxp.api.StaticXmlElementFactory;
import net.robinfriedli.jxp.api.UninitializedParent;
import net.robinfriedli.jxp.api.XmlElement;
import net.robinfriedli.jxp.queries.xpath.XQueryBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* Context implementation with focus on low memory usage. This context type only stores XmlElements in state CONCEPTION
* or DELETION during a Transaction until the next flush, meaning calls to #getElements or #query result in the XmlElement
* instances being instantiated. {@link Context#xPathQuery(String)} can be used in combination with this context type
* to only instantiate XmlElements based on the query result (see {@link XQueryBuilder} to build XPath queries).
* In combination with {@link Context#invokeSequential(int, Runnable)} this context allows for low memory usage when
* executing massive transactions.
*/
public class LazyContext extends AbstractContext {
private final XmlElement documentElement;
public LazyContext(JxpBackend backend, Document document, Logger logger) {
super(backend, document, logger);
documentElement = StaticXmlElementFactory.instantiateDocumentElement(this, false);
}
public LazyContext(JxpBackend backend, File file, Logger logger) {
super(backend, file, logger);
documentElement = StaticXmlElementFactory.instantiateDocumentElement(this, false);
}
@Override
public XmlElement getDocumentElement() {
return documentElement;
}
@Override
public List<XmlElement> getElements() {
return documentElement.getSubElements();
}
@Override
protected List<XmlElement> handleXPathResults(List<Element> results) {
List<XmlElement> elementInstances = Lists.newArrayList();
for (Element docElement : results) {
XmlElement xmlElement = StaticXmlElementFactory.instantiatePersistentXmlElement(docElement, this);
Node parentNode = docElement.getParentNode();
if (parentNode instanceof Element && !Objects.equals(parentNode, parentNode.getOwnerDocument().getDocumentElement())) {
xmlElement.internal().setParent(new UninitializedParent(this, (Element) parentNode, xmlElement));
}
elementInstances.add(xmlElement);
}
return elementInstances;
}
@Override
protected Context instantiate(JxpBackend jxpBackend, Document document, Logger logger) {
return new LazyContext(jxpBackend, document, logger);
}
@Override
protected Context instantiate(JxpBackend jxpBackend, File document, Logger logger) {
return new LazyContext(jxpBackend, document, logger);
}
}
| 37.506329 | 131 | 0.740466 |
db98ad4ad81e729eaf5169f005f24c0227b4208f | 3,336 | /**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.modules.interaction.web.entry;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.interaction.entity.entry.InteractionEntry;
import com.thinkgem.jeesite.modules.interaction.service.entry.InteractionEntryService;
/**
* 入职秀Controller
* @author 李金辉
* @version 2019-01-24
*/
@Controller
@RequestMapping(value = "${adminPath}/interaction/entry/interactionEntry")
public class InteractionEntryController extends BaseController {
@Autowired
private InteractionEntryService interactionEntryService;
@ModelAttribute
public InteractionEntry get(@RequestParam(required=false) String id) {
InteractionEntry entity = null;
if (StringUtils.isNotBlank(id)){
entity = interactionEntryService.get(id);
}
if (entity == null){
entity = new InteractionEntry();
}
return entity;
}
@RequiresPermissions("interaction:entry:interactionEntry:view")
@RequestMapping(value = {"list", ""})
public String list(InteractionEntry interactionEntry, HttpServletRequest request, HttpServletResponse response, Model model) {
Page<InteractionEntry> page = interactionEntryService.findPage(new Page<InteractionEntry>(request, response), interactionEntry);
model.addAttribute("page", page);
return "modules/interaction/entry/interactionEntryList";
}
@RequiresPermissions("interaction:entry:interactionEntry:view")
@RequestMapping(value = "form")
public String form(InteractionEntry interactionEntry, Model model) {
model.addAttribute("interactionEntry", interactionEntry);
return "modules/interaction/entry/interactionEntryForm";
}
@RequiresPermissions("interaction:entry:interactionEntry:edit")
@RequestMapping(value = "save")
public String save(InteractionEntry interactionEntry, Model model, RedirectAttributes redirectAttributes) {
if (!beanValidator(model, interactionEntry)){
return form(interactionEntry, model);
}
interactionEntryService.save(interactionEntry);
addMessage(redirectAttributes, "保存入职秀成功");
return "redirect:"+Global.getAdminPath()+"/interaction/entry/interactionEntry/?repage";
}
@RequiresPermissions("interaction:entry:interactionEntry:edit")
@RequestMapping(value = "delete")
public String delete(InteractionEntry interactionEntry, RedirectAttributes redirectAttributes) {
interactionEntryService.delete(interactionEntry);
addMessage(redirectAttributes, "删除入职秀成功");
return "redirect:"+Global.getAdminPath()+"/interaction/entry/interactionEntry/?repage";
}
} | 40.192771 | 131 | 0.805755 |
368472859ca4ffb3f7f43a414772438743e78021 | 110 | package com.vlad.newsapi4j.utils;
@FunctionalInterface
public interface Callback<T> {
void invoke(T t);
}
| 12.222222 | 33 | 0.754545 |
4786a478bc2311c0a3a1282c98ea5cac2cb67906 | 7,376 | /************************************************************************
*
* 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.odftoolkit.odfdom.incubator.search;
import java.util.Hashtable;
import java.util.Vector;
import org.odftoolkit.odfdom.pkg.OdfElement;
/**
* Abstract class Selection describe one of the matched results The selection
* can be recognized by the container mElement, the start mIndex of the text
* content of this mElement and the text content.
*
*/
public abstract class Selection {
private OdfElement mElement;
private int mIndex;
/**
* get the container mElement of this selection
* @return the container mElement
*/
public OdfElement getElement() {
return mElement;
}
/**
* get the start mIndex of the text content of the container mElement
* this is only meaningful for TextSelection. other type Selection
* will return 0.
* @return the start mIndex of the container mElement
*/
public int getIndex() {
return mIndex;
}
/**
* cut the current selection
* @throws InvalidNavigationException
*/
abstract public void cut() throws InvalidNavigationException;
/**
* paste the current selection at front of the specified position selection
* @param positionitem the position selection
* @throws InvalidNavigationException
*/
abstract public void pasteAtFrontOf(Selection positionitem) throws InvalidNavigationException;
/**
* paste the current selection at end of the specified position selection
* @param positionitem the position selection
* @throws InvalidNavigationException
*/
abstract public void pasteAtEndOf(Selection positionitem) throws InvalidNavigationException;
/**
* when a selected item has been delete, the selections after this deleted selection should be refresh
* because these selections mIndex will be changed
* @param deleteditem the deleted selection
*/
abstract protected void refreshAfterFrontalDelete(Selection deleteditem);
/**
* when a selected item has been inserted, the selection after the inserted item should be refresh
* because these selections mIndex will be changed
* @param inserteditem the inserted selection
*/
abstract protected void refreshAfterFrontalInsert(Selection inserteditem);
/**
* A quick method to update the mIndex of this selection
* @param offset the offset that the mIndex should be added
*/
abstract protected void refresh(int offset);
/**
* SelectionManager can manage all the selections that are returned to end users.
* This SelectionManager contains a repository of all selections, and will refresh the status/mIndex
* of selections after certain operation.
*/
static class SelectionManager {
static private Hashtable<OdfElement, Vector<Selection>> repository = new Hashtable<OdfElement, Vector<Selection>>();
/**
* Register the selection item
* @param item the selection item
*/
static public void registerItem(Selection item) {
OdfElement element = item.getElement();
if (repository.containsKey(element)) {
Vector<Selection> selections = repository.get(element);
int i = 0;
while (i < selections.size()) {
if (selections.get(i).getIndex() > item.getIndex()) {
selections.insertElementAt(item, i);
break;
}
i++;
}
if (i == selections.size()) {
selections.add(item);
}
} else {
Vector<Selection> al = new Vector<Selection>();
al.add(item);
repository.put(element, al);
}
}
/**
* Refresh the selections in repository after a item is cut.
* @param cutItem the cut item
*/
synchronized static public void refreshAfterCut(Selection cutItem) {
//travase the whole sub tree
OdfElement element = cutItem.getElement();
if (repository.containsKey(element)) {
Vector<Selection> selections = repository.get(element);
for (int i = 0; i < selections.size(); i++) {
if (selections.get(i).getIndex() > cutItem.getIndex()) {
selections.get(i).refreshAfterFrontalDelete(cutItem);
}
}
}
}
/**
* Refresh the selections in repository after a pastedAtFrontOf operation is called.
* @param item the pasted item
* @param positionItem the position item
*/
synchronized static public void refreshAfterPasteAtFrontOf(Selection item, Selection positionItem) {
//travase the whole sub tree
OdfElement element = positionItem.getElement();
if (repository.containsKey(element)) {
Vector<Selection> selections = repository.get(element);
for (int i = 0; i < selections.size(); i++) {
if (selections.get(i).getIndex() >= positionItem.getIndex()) {
selections.get(i).refreshAfterFrontalInsert(item);
}
}
}
}
/**
* Refresh the selections in repository after a pastedAtEndOf operation is called.
* @param item the pasted item
* @param positionItem the position item
*/
synchronized static public void refreshAfterPasteAtEndOf(Selection item, Selection positionItem) {
OdfElement element = positionItem.getElement();
int positionIndex;
if (positionItem instanceof TextSelection) {
positionIndex = positionItem.getIndex() + ((TextSelection) positionItem).getText().length();
} else {
positionIndex = positionItem.getIndex();
}
if (repository.containsKey(element)) {
Vector<Selection> selections = repository.get(element);
for (int i = 0; i < selections.size(); i++) {
if (selections.get(i).getIndex() >= positionIndex) {
selections.get(i).refreshAfterFrontalInsert(item);
}
}
}
}
/**
* Remove the selection from repository.
* @param item selection item
*/
static public void unregisterItem(Selection item) {
OdfElement element = item.getElement();
if (repository.containsKey(element)) {
Vector<Selection> selections = repository.get(element);
selections.remove(item);
}
}
/**
* A direct method to update all the selections contained in a mElement after a certain position.
* @param containerElement the container mElement
* @param offset the offset
* @param positionIndex the mIndex of a certain position
*/
synchronized static public void refresh(OdfElement containerElement, int offset, int positionIndex) {
if (repository.containsKey(containerElement)) {
Vector<Selection> selections = repository.get(containerElement);
for (int i = 0; i < selections.size(); i++) {
if (selections.get(i).getIndex() >= positionIndex) {
selections.get(i).refresh(offset);
}
}
}
}
private SelectionManager() {
}
}
}
| 32.782222 | 118 | 0.701871 |
dd30e3348452deb9e46fbc1fc5a60cf4357957bc | 650 | package mvi.diceapp.request;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.val;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Data
public class DiceRollResponse {
List<HitEntry> distribution;
@Data
@AllArgsConstructor
public static class HitEntry {
long sum;
int hits;
}
public static DiceRollResponse of(Map<Long, Integer> hitMap) {
val response = new DiceRollResponse();
response.distribution = new ArrayList<>();
hitMap.forEach((sum, hit) -> response.distribution.add(new HitEntry(sum, hit)));
return response;
}
}
| 21.666667 | 88 | 0.683077 |
37b12504ff7650161a8f43a7f962b5377956e889 | 797 | package edu.java.common;
public class ExampleInstanceof {
/**
* @param args
* the subclass of a superclass can change the class of the instance
* example:
* Object obj = new Integer(5);
* String str = (String)obj;
* while this would not cause a compile error but when the program actually running there will be a runtime error.
* To make the program robust, use a instance of to check before actually change the class of the instance.
* if (object instanceof String){
String str = (String)obj
}
* the instanceof can avoid ClassCastException
*
*/
public void testEncups(){
}
public static void main(String[] args) {
Object obj = new String();
if (obj instanceof String){
String str = (String)obj;
}
// TODO Auto-generated method stub
}
}
| 22.771429 | 115 | 0.685069 |
e6aa2aa503242cd1818aebb40fdee5222d2f876e | 903 | package io.cucumber.skeleton;
import io.cucumber.java.Before;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
public class StepDefinitions {
Belly belly;
@Before
public void setup(){
belly = new Belly();
}
@Given("I have {int} cukes in my belly")
public void I_have_cukes_in_my_belly(int cukes) {
belly.eat(cukes);
}
@When("I wait {int} hour")
public void i_wait_hour(Integer int1) throws InterruptedException {
// Write code here that turns the phrase above into concrete actions
Thread.sleep(int1);
}
@Then("my belly should growl")
public void my_belly_should_growl() {
// Write code here that turns the phrase above into concrete actions
System.out.println("This is how large my belly has grown after eating some cukes "+belly.grow());
}
}
| 25.8 | 105 | 0.673311 |
0c11e08b327a96483870081d1e311cfdf453d723 | 2,685 | package pl.java.scalatech.performance1;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import org.assertj.core.api.Assertions;
import org.hibernate.Session;
import org.hibernate.transform.AliasToEntityMapResultTransformer;
import org.hibernate.transform.Transformers;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;
import pl.java.scalatech.config.PropertiesLoader;
import pl.java.scalatech.domain.examplePerformance1.dto.CustomerSummary;
import pl.java.scalatech.repository.customer.CustomerRepo;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PropertiesLoader.class, JpaPerformanceOneConfig.class })
@ActiveProfiles(value = {"performance1","logger","dev"})
@Transactional
@Slf4j
@SqlDataCustomer
public class JpaPerformanceTransformerTest {
@Autowired
private CustomerRepo customerRepo;
@Autowired
private EntityManager em;
@Test
public void shouldBootstrap() {
Assertions.assertThat(customerRepo.count()).isEqualTo(6);
}
@Test
public void shouldTransformerMapWork() {
Session session = em.unwrap(Session.class);
List<Map> result = session.createQuery("Select c.id as id, c.name as name ,count(j) as countJob from Customer c join c.jobs j WHERE c.id = :id")
.setParameter("id", 5l)
.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE)
.list();
log.info("customer summary : {}",result);
for (Map map : result) {
Long id = (Long) map.get("id");
String name = (String) map.get("name");
long count = (long) map.get("countJob");
log.info("+++ id {} , name : {} , count : {}",id,name,count);
}
}
@Test
@Ignore
//TODO
public void shouldTransformerBeanWork() {
Session session = em.unwrap(Session.class);
CustomerSummary result = (CustomerSummary) session.createQuery("Select c.id as id, c.name as name ,count(j) as countJob from Customer c join c.jobs j WHERE c.id = :id")
.setParameter("id", 5l)
.setResultTransformer(Transformers.aliasToBean(CustomerSummary.class))
.uniqueResult();
log.info("customer summary : {}",result);
}
} | 36.283784 | 178 | 0.705028 |
9d8831cf25c715fc59cf00c88623950d549a771a | 1,207 | package org.gg.scoot.fixture;
import org.gg.scoot.entity.unit.BuildingEntity;
import org.gg.scoot.entity.unit.UnitEntity;
import org.gg.scoot.entity.unit.UnitOrBuildingBaseEntity;
import java.util.List;
import static org.gg.scoot.fixture.BuildingFixture.CIVILIZATIONS_ID;
public class UnitFixture {
public static final long ARCHER_ID = 4L;
public static UnitEntity archer() {
var archer = new UnitEntity();
archer.setId(ARCHER_ID);
archer.setAge(2);
archer.setInternalName("ARCHR");
archer.setName(HelpTextFixture.archerName());
archer.setHelpText(HelpTextFixture.archerHelpText());
archer.setHelpTextShort(HelpTextFixture.archerHelpTextShort());
archer.setWoodCost(25);
archer.setFoodCost(0);
archer.setStoneCost(0);
archer.setGoldCost(45);
archer.setMeleeArmor(0);
archer.setPierceArmor(0);
archer.setAttack(4);
archer.setHitPoints(30);
archer.setLineOfSight(6);
archer.setGarrisonCapacity(0);
archer.setUnitType(70);
archer.setEnabledForCivilizations(CIVILIZATIONS_ID);
archer.setTechs(List.of());
return archer;
}
}
| 30.175 | 71 | 0.686827 |
cc68751773b6dbd72f537e20d13f42da6c4809ef | 12,502 | package org.simpleflatmapper.jdbc;
import org.simpleflatmapper.jdbc.impl.JdbcKeySourceGetter;
import org.simpleflatmapper.map.MappingException;
import org.simpleflatmapper.map.SetRowMapper;
import org.simpleflatmapper.map.SourceFieldMapper;
import org.simpleflatmapper.map.MapperConfig;
import org.simpleflatmapper.map.MappingContext;
import org.simpleflatmapper.map.context.MappingContextFactory;
import org.simpleflatmapper.map.getter.ContextualGetterFactory;
import org.simpleflatmapper.map.getter.ContextualGetterFactoryAdapter;
import org.simpleflatmapper.map.mapper.ColumnDefinition;
import org.simpleflatmapper.map.mapper.DefaultSetRowMapperBuilder;
import org.simpleflatmapper.map.mapper.MapperBuilder;
import org.simpleflatmapper.map.property.FieldMapperColumnDefinition;
import org.simpleflatmapper.map.context.MappingContextFactoryBuilder;
import org.simpleflatmapper.map.mapper.KeyFactory;
import org.simpleflatmapper.map.mapper.MapperSourceImpl;
import org.simpleflatmapper.reflect.ReflectionService;
import org.simpleflatmapper.reflect.getter.GetterFactory;
import org.simpleflatmapper.util.BiFunction;
import org.simpleflatmapper.util.CheckedConsumer;
import org.simpleflatmapper.util.Function;
import org.simpleflatmapper.util.TypeReference;
import org.simpleflatmapper.reflect.meta.ClassMeta;
import org.simpleflatmapper.util.Enumerable;
import org.simpleflatmapper.util.UnaryFactory;
import org.simpleflatmapper.jdbc.impl.ResultSetEnumerable;
import java.lang.reflect.Type;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
//IFJAVA8_START
import java.util.stream.Stream;
//IFJAVA8_END
/**
* @param <T> the targeted type of the jdbcMapper
*/
public final class JdbcMapperBuilder<T> extends MapperBuilder<ResultSet, ResultSet, T, JdbcColumnKey, SQLException, SetRowMapper<ResultSet, ResultSet, T, SQLException>, JdbcMapper<T>, JdbcMapperBuilder<T>> {
private static final MapperSourceImpl<ResultSet, JdbcColumnKey> FIELD_MAPPER_SOURCE =
new MapperSourceImpl<ResultSet, JdbcColumnKey>(ResultSet.class, new ContextualGetterFactoryAdapter<ResultSet, JdbcColumnKey>(ResultSetGetterFactory.INSTANCE));
private static final KeyFactory<JdbcColumnKey> KEY_FACTORY = new KeyFactory<JdbcColumnKey>() {
@Override
public JdbcColumnKey newKey(String name, int i) {
return new JdbcColumnKey(name, i);
}
};
public static final Function<Object[], ColumnDefinition<JdbcColumnKey, ?>> COLUMN_DEFINITION_FACTORY = FieldMapperColumnDefinition.factory();
private final MappingContextFactoryBuilder<ResultSet, JdbcColumnKey> mappingContextFactoryBuilder;
/**
* Build a new JdbcMapperBuilder targeting the type specified by the TypeReference. The TypeReference
* allow you to provide a generic type with check of T<br>
* <code>new TypeReference<List<String>>() {}</code>
*
* @param target the TypeReference to the type T to map to
*/
public JdbcMapperBuilder(final TypeReference<T> target) {
this(target.getType());
}
/**
* Build a new JdbcMapperBuilder targeting the specified type.
*
* @param target the type
*/
public JdbcMapperBuilder(final Type target) {
this(target, ReflectionService.newInstance());
}
/**
* Build a new JdbcMapperBuilder targeting the specified type with the specified ReflectionService.
*
* @param target the type
* @param reflectService the ReflectionService
*/
public JdbcMapperBuilder(final Type target, ReflectionService reflectService) {
this(reflectService.<T>getClassMeta(target),
MapperConfig.<JdbcColumnKey, ResultSet>fieldMapperConfig(),
ResultSetGetterFactory.INSTANCE,
new JdbcMappingContextFactoryBuilder(!MapperConfig.<JdbcColumnKey, ResultSet>fieldMapperConfig().unorderedJoin()));
}
/**
* @param classMeta the meta for the target class.
* @param mapperConfig the mapperConfig.
* @param getterFactory the Getter factory.
* @param parentBuilder the parent builder, null if none.
*/
public JdbcMapperBuilder(
final ClassMeta<T> classMeta,
final MapperConfig<JdbcColumnKey, ResultSet> mapperConfig,
final GetterFactory<ResultSet, JdbcColumnKey> getterFactory,
final MappingContextFactoryBuilder<ResultSet, JdbcColumnKey> parentBuilder) {
this(classMeta, mapperConfig, new ContextualGetterFactoryAdapter<ResultSet, JdbcColumnKey>(getterFactory), parentBuilder);
}
/**
* @param classMeta the meta for the target class.
* @param mapperConfig the mapperConfig.
* @param getterFactory the Getter factory.
* @param parentBuilder the parent builder, null if none.
*/
public JdbcMapperBuilder(
final ClassMeta<T> classMeta,
final MapperConfig<JdbcColumnKey, ResultSet> mapperConfig,
final ContextualGetterFactory<? super ResultSet, JdbcColumnKey> getterFactory,
final MappingContextFactoryBuilder<ResultSet, JdbcColumnKey> parentBuilder) {
super(KEY_FACTORY,
new DefaultSetRowMapperBuilder<ResultSet, ResultSet, T, JdbcColumnKey, SQLException>(
classMeta,
parentBuilder,
mapperConfig,
FIELD_MAPPER_SOURCE.getterFactory(getterFactory),
KEY_FACTORY,
new ResultSetEnumerableFactory(),
JdbcKeySourceGetter.INSTANCE),
new BiFunction<SetRowMapper<ResultSet, ResultSet, T, SQLException>, List<JdbcColumnKey>, JdbcMapper<T>>() {
@Override
public JdbcMapper<T> apply(SetRowMapper<ResultSet, ResultSet, T, SQLException> setRowMapper, List<JdbcColumnKey> keys) {
return new JdbcMapperImpl<T>(setRowMapper, parentBuilder.build());
}
},
COLUMN_DEFINITION_FACTORY,
1 );
this.mappingContextFactoryBuilder = parentBuilder;
}
/**
* add a new mapping to the specified property with the specified index and the specified type.
*
* @param column the property name
* @param index the property index
* @param sqlType the property type, @see java.sql.Types
* @return the current builder
*/
public JdbcMapperBuilder<T> addMapping(final String column, final int index, final int sqlType) {
addMapping(column, index, sqlType, FieldMapperColumnDefinition.<JdbcColumnKey>identity());
return this;
}
/**
* add a new mapping to the specified property with the specified index, the specified type.
*
* @param column the property name
* @param index the property index
* @param sqlType the property type, @see java.sql.Types
* @param columnDefinition the property definition
* @return the current builder
*/
public JdbcMapperBuilder<T> addMapping(final String column, final int index, final int sqlType, FieldMapperColumnDefinition<JdbcColumnKey> columnDefinition) {
return addMapping(new JdbcColumnKey(column, index, sqlType), columnDefinition);
}
/**
* add a new mapping to the specified property with the specified index, the specified type.
*
* @param column the property name
* @param index the property index
* @param sqlType the property type, @see java.sql.Types
* @param properties the property properties
* @return the current builder
*/
public JdbcMapperBuilder<T> addMapping(final String column, final int index, final int sqlType, Object... properties) {
return addMapping(new JdbcColumnKey(column, index, sqlType), properties);
}
/**
* add the all the property present in the metaData
*
* @param metaData the metaDAta
* @return the current builder
* @throws SQLException when an error occurs getting the metaData
*/
public JdbcMapperBuilder<T> addMapping(final ResultSetMetaData metaData) throws SQLException {
for (int i = 1; i <= metaData.getColumnCount(); i++) {
addMapping(metaData.getColumnLabel(i), i, metaData.getColumnType(i));
}
return this;
}
public JdbcSourceFieldMapper<T> newSourceFieldMapper() {
return new JdbcSourceFieldMapperImpl<T>(super.sourceFieldMapper(), mappingContextFactoryBuilder.build());
}
private static class JdbcSourceFieldMapperImpl<T> implements JdbcSourceFieldMapper<T> {
private final SourceFieldMapper<ResultSet, T> sourceFieldMapper;
private final MappingContextFactory<? super ResultSet> mappingContextFactory;
private JdbcSourceFieldMapperImpl(SourceFieldMapper<ResultSet, T> sourceFieldMapper, MappingContextFactory<? super ResultSet> mappingContextFactory) {
this.sourceFieldMapper = sourceFieldMapper;
this.mappingContextFactory = mappingContextFactory;
}
@Override
public void mapTo(ResultSet source, T target, MappingContext<? super ResultSet> context) throws Exception {
sourceFieldMapper.mapTo(source, target, context);
}
@Override
public T map(ResultSet source, MappingContext<? super ResultSet> context) throws MappingException {
return sourceFieldMapper.map(source, context);
}
@Override
public T map(ResultSet source) throws MappingException {
return sourceFieldMapper.map(source, mappingContextFactory.newContext());
}
@Override
public MappingContext<? super ResultSet> newMappingContext(ResultSet resultSet) throws SQLException {
return mappingContextFactory.newContext();
}
}
private static class JdbcMapperImpl<T> implements JdbcMapper<T> {
private final SetRowMapper<ResultSet, ResultSet, T, SQLException> setRowMapper;
private final MappingContextFactory<? super ResultSet> mappingContextFactory;
private JdbcMapperImpl(SetRowMapper<ResultSet, ResultSet, T, SQLException> setRowMapper, MappingContextFactory<? super ResultSet> mappingContextFactory) {
this.setRowMapper = setRowMapper;
this.mappingContextFactory = mappingContextFactory;
}
@Override
public T map(ResultSet source) throws MappingException {
return setRowMapper.map(source);
}
@Override
public T map(ResultSet source, MappingContext<? super ResultSet> context) throws MappingException {
return setRowMapper.map(source, context);
}
@Override
public <H extends CheckedConsumer<? super T>> H forEach(ResultSet source, H handler) throws SQLException, MappingException {
return setRowMapper.forEach(source, handler);
}
@Override
public Iterator<T> iterator(ResultSet source) throws SQLException, MappingException {
return setRowMapper.iterator(source);
}
@Override
public Enumerable<T> enumerate(ResultSet source) throws SQLException, MappingException {
return setRowMapper.enumerate(source);
}
//IFJAVA8_START
@Override
public Stream<T> stream(ResultSet source) throws SQLException, MappingException {
return setRowMapper.stream(source);
}
//IFJAVA8_END
@Override
public MappingContext<? super ResultSet> newMappingContext(ResultSet resultSet) throws SQLException {
return mappingContextFactory.newContext();
}
@Override
public String toString() {
return "JdbcMapperImpl{" +
"setRowMapper=" + setRowMapper +
", mappingContextFactory=" + mappingContextFactory +
'}';
}
}
private static class ResultSetEnumerableFactory implements UnaryFactory<ResultSet, Enumerable<ResultSet>> {
@Override
public Enumerable<ResultSet> newInstance(ResultSet rows) {
return new ResultSetEnumerable(rows);
}
}
} | 42.815068 | 207 | 0.68877 |
eaeec77baaef7c80e6607e6fb5c4e95bb86aaaca | 27,555 | /*
Copyright � 1999 CERN - European Organization for Nuclear Research.
Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose
is hereby granted without fee, provided that the above copyright notice appear in all copies and
that both that copyright notice and this permission notice appear in supporting documentation.
CERN makes no representations about the suitability of this software for any purpose.
It is provided "as is" without expressed or implied warranty.
*/
package org.apache.mahout.math.matrix.doublealgo;
import org.apache.mahout.math.function.BinaryFunction;
import org.apache.mahout.math.function.Functions;
import org.apache.mahout.math.jet.random.engine.MersenneTwister;
import org.apache.mahout.math.jet.random.engine.RandomEngine;
import org.apache.mahout.math.jet.random.sampling.RandomSampler;
import org.apache.mahout.math.matrix.DoubleMatrix1D;
import org.apache.mahout.math.matrix.DoubleMatrix2D;
import org.apache.mahout.math.matrix.DoubleMatrix3D;
import org.apache.mahout.math.matrix.impl.DenseDoubleMatrix2D;
/** @deprecated until unit tests are in place. Until this time, this class/interface is unsupported. */
@Deprecated
public class Statistic {
/** Euclidean distance function; <tt>Sqrt(Sum( (x[i]-y[i])^2 ))</tt>. */
public static final VectorVectorFunction EUCLID = new VectorVectorFunction() {
public double apply(DoubleMatrix1D a, DoubleMatrix1D b) {
return Math.sqrt(a.aggregate(b, Functions.plus, Functions.chain(Functions.square, Functions.minus)));
}
};
/** Bray-Curtis distance function; <tt>Sum( abs(x[i]-y[i]) ) / Sum( x[i]+y[i] )</tt>. */
public static final VectorVectorFunction BRAY_CURTIS = new VectorVectorFunction() {
public double apply(DoubleMatrix1D a, DoubleMatrix1D b) {
return a.aggregate(b, Functions.plus, Functions.chain(Functions.abs, Functions.minus)) /
a.aggregate(b, Functions.plus, Functions.plus);
}
};
/** Canberra distance function; <tt>Sum( abs(x[i]-y[i]) / abs(x[i]+y[i]) )</tt>. */
public static final VectorVectorFunction CANBERRA = new VectorVectorFunction() {
private final BinaryFunction fun = new BinaryFunction() {
public double apply(double a, double b) {
return Math.abs(a - b) / Math.abs(a + b);
}
};
public double apply(DoubleMatrix1D a, DoubleMatrix1D b) {
return a.aggregate(b, Functions.plus, fun);
}
};
/** Maximum distance function; <tt>Max( abs(x[i]-y[i]) )</tt>. */
public static final VectorVectorFunction MAXIMUM = new VectorVectorFunction() {
public double apply(DoubleMatrix1D a, DoubleMatrix1D b) {
return a.aggregate(b, Functions.max, Functions.chain(Functions.abs, Functions.minus));
}
};
/** Manhattan distance function; <tt>Sum( abs(x[i]-y[i]) )</tt>. */
public static final VectorVectorFunction MANHATTAN = new VectorVectorFunction() {
public double apply(DoubleMatrix1D a, DoubleMatrix1D b) {
return a.aggregate(b, Functions.plus, Functions.chain(Functions.abs, Functions.minus));
}
};
/**
* Interface that represents a function object: a function that takes
* two argument vectors and returns a single value.
*/
/** @deprecated until unit tests are in place. Until this time, this class/interface is unsupported. */
@Deprecated
public interface VectorVectorFunction {
/**
* Applies a function to two argument vectors.
*
* @param x the first argument vector passed to the function.
* @param y the second argument vector passed to the function.
* @return the result of the function.
*/
double apply(DoubleMatrix1D x, org.apache.mahout.math.matrix.DoubleMatrix1D y);
}
/** Makes this class non instantiable, but still let's others inherit from it. */
private Statistic() {
}
/**
* Applies the given aggregation functions to each column and stores the results in a the result matrix.
* If matrix has shape <tt>m x n</tt>, then result must have shape <tt>aggr.length x n</tt>.
* Tip: To do aggregations on rows use dice views (transpositions), as in <tt>aggregate(matrix.viewDice(),aggr,result.viewDice())</tt>.
*
* @param matrix any matrix; a column holds the values of a given variable.
* @param aggr the aggregation functions to be applied to each column.
* @param result the matrix to hold the aggregation results.
* @return <tt>result</tt> (for convenience only).
* @see Formatter
* @see hep.aida.bin.BinFunction1D
* @see hep.aida.bin.BinFunctions1D
*
public static DoubleMatrix2D aggregate(DoubleMatrix2D matrix, hep.aida.bin.BinFunction1D[] aggr, DoubleMatrix2D result) {
DynamicBin1D bin = new DynamicBin1D();
double[] elements = new double[matrix.rows()];
org.apache.mahout.math.list.DoubleArrayList values = new DoubleArrayList(elements);
for (int column=matrix.columns(); --column >= 0; ) {
matrix.viewColumn(column).toArray(elements); // copy column into values
bin.clear();
bin.addAllOf(values);
for (int i=aggr.length; --i >= 0; ) {
result.set(i, column, aggr[i].apply(bin));
}
}
return result;
}
*/
/**
Fills all cell values of the given vector into a bin from which statistics measures can be retrieved efficiently.
Cells values are copied.
<br>
Tip: Use <tt>log.info(bin(vector))</tt> to print most measures computed by the bin. Example:
<table>
<td class="PRE">
<pre>
Size: 20000
Sum: 299858.02350278624
SumOfSquares: 5399184.154095971
Min: 0.8639113139711261
Max: 59.75331890541892
Mean: 14.992901175139313
RMS: 16.43043540825375
Variance: 45.17438077634358
Standard deviation: 6.721188940681818
Standard error: 0.04752598277592142
Geometric mean: 13.516615397064466
Product: Infinity
Harmonic mean: 11.995174297952191
Sum of inversions: 1667.337172700724
Skew: 0.8922838940067878
Kurtosis: 1.1915828121825598
Sum of powers(3): 1.1345828465808412E8
Sum of powers(4): 2.7251055344494686E9
Sum of powers(5): 7.367125643433887E10
Sum of powers(6): 2.215370909100143E12
Moment(0,0): 1.0
Moment(1,0): 14.992901175139313
Moment(2,0): 269.95920770479853
Moment(3,0): 5672.914232904206
Moment(4,0): 136255.27672247344
Moment(5,0): 3683562.8217169433
Moment(6,0): 1.1076854545500715E8
Moment(0,mean()): 1.0
Moment(1,mean()): -2.0806734113421045E-14
Moment(2,mean()): 45.172122057305664
Moment(3,mean()): 270.92018671421
Moment(4,mean()): 8553.8664869067
Moment(5,mean()): 153357.41712233616
Moment(6,mean()): 4273757.570142922
25%, 50% and 75% Quantiles: 10.030074811938091, 13.977982089912224,
18.86124362967137
quantileInverse(mean): 0.559163335012079
Distinct elements & frequencies not printed (too many).
</pre>
</td>
</table>
@param vector the vector to analyze.
@return a bin holding the statistics measures of the vector.
*
public static DynamicBin1D bin(DoubleMatrix1D vector) {
DynamicBin1D bin = new DynamicBin1D();
bin.addAllOf(DoubleFactory1D.dense.toList(vector));
return bin;
}
*/
/**
* Modifies the given covariance matrix to be a correlation matrix (in-place). The correlation matrix is a square,
* symmetric matrix consisting of nothing but correlation coefficients. The rows and the columns represent the
* variables, the cells represent correlation coefficients. The diagonal cells (i.e. the correlation between a
* variable and itself) will equal 1, for the simple reason that the correlation coefficient of a variable with itself
* equals 1. The correlation of two column vectors x and y is given by <tt>corr(x,y) = cov(x,y) /
* (stdDev(x)*stdDev(y))</tt> (Pearson's correlation coefficient). A correlation coefficient varies between -1 (for a
* perfect negative relationship) to +1 (for a perfect positive relationship). See the <A
* HREF="http://www.cquest.utoronto.ca/geog/ggr270y/notes/not05efg.html"> math definition</A> and <A
* HREF="http://www.stat.berkeley.edu/users/stark/SticiGui/Text/gloss.htm#correlation_coef"> another def</A>. Compares
* two column vectors at a time. Use dice views to compare two row vectors at a time.
*
* @param covariance a covariance matrix, as, for example, returned by method {@link #covariance(DoubleMatrix2D)}.
* @return the modified covariance, now correlation matrix (for convenience only).
*/
public static DoubleMatrix2D correlation(DoubleMatrix2D covariance) {
for (int i = covariance.columns(); --i >= 0;) {
for (int j = i; --j >= 0;) {
double stdDev1 = Math.sqrt(covariance.getQuick(i, i));
double stdDev2 = Math.sqrt(covariance.getQuick(j, j));
double cov = covariance.getQuick(i, j);
double corr = cov / (stdDev1 * stdDev2);
covariance.setQuick(i, j, corr);
covariance.setQuick(j, i, corr); // symmetric
}
}
for (int i = covariance.columns(); --i >= 0;) {
covariance.setQuick(i, i, 1);
}
return covariance;
}
/**
* Constructs and returns the covariance matrix of the given matrix. The covariance matrix is a square, symmetric
* matrix consisting of nothing but covariance coefficients. The rows and the columns represent the variables, the
* cells represent covariance coefficients. The diagonal cells (i.e. the covariance between a variable and itself)
* will equal the variances. The covariance of two column vectors x and y is given by <tt>cov(x,y) = (1/n) *
* Sum((x[i]-mean(x)) * (y[i]-mean(y)))</tt>. See the <A HREF="http://www.cquest.utoronto.ca/geog/ggr270y/notes/not05efg.html">
* math definition</A>. Compares two column vectors at a time. Use dice views to compare two row vectors at a time.
*
* @param matrix any matrix; a column holds the values of a given variable.
* @return the covariance matrix (<tt>n x n, n=matrix.columns</tt>).
*/
public static DoubleMatrix2D covariance(DoubleMatrix2D matrix) {
int rows = matrix.rows();
int columns = matrix.columns();
DoubleMatrix2D covariance = new DenseDoubleMatrix2D(columns, columns);
double[] sums = new double[columns];
DoubleMatrix1D[] cols = new DoubleMatrix1D[columns];
for (int i = columns; --i >= 0;) {
cols[i] = matrix.viewColumn(i);
sums[i] = cols[i].zSum();
}
for (int i = columns; --i >= 0;) {
for (int j = i + 1; --j >= 0;) {
double sumOfProducts = cols[i].zDotProduct(cols[j]);
double cov = (sumOfProducts - sums[i] * sums[j] / rows) / rows;
covariance.setQuick(i, j, cov);
covariance.setQuick(j, i, cov); // symmetric
}
}
return covariance;
}
/**
2-d OLAP cube operator; Fills all cells of the given vectors into the given histogram.
If you use hep.aida.ref.Converter.toString(histo) on the result, the OLAP cube of x-"column" vs. y-"column" , summing the weights "column" will be printed.
For example, aggregate sales by product by region.
<p>
Computes the distinct values of x and y, yielding histogram axes that capture one distinct value per bin.
Then fills the histogram.
<p>
Example output:
<table>
<td class="PRE">
<pre>
Cube:
Entries=5000, ExtraEntries=0
MeanX=4.9838, RmsX=NaN
MeanY=2.5304, RmsY=NaN
xAxis: Min=0, Max=10, Bins=11
yAxis: Min=0, Max=5, Bins=6
Heights:
| X
| 0 1 2 3 4 5 6 7 8 9 10 | Sum
----------------------------------------------------------
Y 5 | 30 53 51 52 57 39 65 61 55 49 22 | 534
4 | 43 106 112 96 92 94 107 98 98 110 47 | 1003
3 | 39 134 87 93 102 103 110 90 114 98 51 | 1021
2 | 44 81 113 96 101 86 109 83 111 93 42 | 959
1 | 54 94 103 99 115 92 98 97 103 90 44 | 989
0 | 24 54 52 44 42 56 46 47 56 53 20 | 494
----------------------------------------------------------
Sum | 234 522 518 480 509 470 535 476 537 493 226 |
</pre>
</td>
</table>
@return the histogram containing the cube.
@throws IllegalArgumentException if <tt>x.size() != y.size() || y.size() != weights.size()</tt>.
*
public static hep.aida.IHistogram2D cube(DoubleMatrix1D x, DoubleMatrix1D y, DoubleMatrix1D weights) {
if (x.size() != y.size() || y.size() != weights.size()) throw new IllegalArgumentException("vectors must have same size");
double epsilon = 1.0E-9;
org.apache.mahout.math.list.DoubleArrayList distinct = new DoubleArrayList();
double[] vals = new double[x.size()];
org.apache.mahout.math.list.DoubleArrayList sorted = new DoubleArrayList(vals);
// compute distinct values of x
x.toArray(vals); // copy x into vals
sorted.sort();
org.apache.mahout.math.jet.stat.Descriptive.frequencies(sorted, distinct, null);
// since bins are right-open [from,to) we need an additional dummy bin so that the last distinct value does not fall into the overflow bin
if (distinct.size()>0) distinct.add(distinct.get(distinct.size()-1) + epsilon);
distinct.trimToSize();
hep.aida.IAxis xaxis = new hep.aida.ref.VariableAxis(distinct.elements());
// compute distinct values of y
y.toArray(vals);
sorted.sort();
org.apache.mahout.math.jet.stat.Descriptive.frequencies(sorted, distinct, null);
// since bins are right-open [from,to) we need an additional dummy bin so that the last distinct value does not fall into the overflow bin
if (distinct.size()>0) distinct.add(distinct.get(distinct.size()-1) + epsilon);
distinct.trimToSize();
hep.aida.IAxis yaxis = new hep.aida.ref.VariableAxis(distinct.elements());
hep.aida.IHistogram2D histo = new hep.aida.ref.Histogram2D("Cube",xaxis,yaxis);
return histogram(histo,x,y,weights);
}
*/
/**
3-d OLAP cube operator; Fills all cells of the given vectors into the given histogram.
If you use hep.aida.ref.Converter.toString(histo) on the result, the OLAP cube of x-"column" vs. y-"column" vs. z-"column", summing the weights "column" will be printed.
For example, aggregate sales by product by region by time.
<p>
Computes the distinct values of x and y and z, yielding histogram axes that capture one distinct value per bin.
Then fills the histogram.
@return the histogram containing the cube.
@throws IllegalArgumentException if <tt>x.size() != y.size() || x.size() != z.size() || x.size() != weights.size()</tt>.
*
public static hep.aida.IHistogram3D cube(DoubleMatrix1D x, DoubleMatrix1D y, DoubleMatrix1D z, DoubleMatrix1D weights) {
if (x.size() != y.size() || x.size() != z.size() || x.size() != weights.size()) throw new IllegalArgumentException("vectors must have same size");
double epsilon = 1.0E-9;
org.apache.mahout.math.list.DoubleArrayList distinct = new DoubleArrayList();
double[] vals = new double[x.size()];
org.apache.mahout.math.list.DoubleArrayList sorted = new DoubleArrayList(vals);
// compute distinct values of x
x.toArray(vals); // copy x into vals
sorted.sort();
org.apache.mahout.math.jet.stat.Descriptive.frequencies(sorted, distinct, null);
// since bins are right-open [from,to) we need an additional dummy bin so that the last distinct value does not fall into the overflow bin
if (distinct.size()>0) distinct.add(distinct.get(distinct.size()-1) + epsilon);
distinct.trimToSize();
hep.aida.IAxis xaxis = new hep.aida.ref.VariableAxis(distinct.elements());
// compute distinct values of y
y.toArray(vals);
sorted.sort();
org.apache.mahout.math.jet.stat.Descriptive.frequencies(sorted, distinct, null);
// since bins are right-open [from,to) we need an additional dummy bin so that the last distinct value does not fall into the overflow bin
if (distinct.size()>0) distinct.add(distinct.get(distinct.size()-1) + epsilon);
distinct.trimToSize();
hep.aida.IAxis yaxis = new hep.aida.ref.VariableAxis(distinct.elements());
// compute distinct values of z
z.toArray(vals);
sorted.sort();
org.apache.mahout.math.jet.stat.Descriptive.frequencies(sorted, distinct, null);
// since bins are right-open [from,to) we need an additional dummy bin so that the last distinct value does not fall into the overflow bin
if (distinct.size()>0) distinct.add(distinct.get(distinct.size()-1) + epsilon);
distinct.trimToSize();
hep.aida.IAxis zaxis = new hep.aida.ref.VariableAxis(distinct.elements());
hep.aida.IHistogram3D histo = new hep.aida.ref.Histogram3D("Cube",xaxis,yaxis,zaxis);
return histogram(histo,x,y,z,weights);
}
*/
/**
* Constructs and returns the distance matrix of the given matrix. The distance matrix is a square, symmetric matrix
* consisting of nothing but distance coefficients. The rows and the columns represent the variables, the cells
* represent distance coefficients. The diagonal cells (i.e. the distance between a variable and itself) will be zero.
* Compares two column vectors at a time. Use dice views to compare two row vectors at a time.
*
* @param matrix any matrix; a column holds the values of a given variable (vector).
* @param distanceFunction (EUCLID, CANBERRA, ..., or any user defined distance function operating on two vectors).
* @return the distance matrix (<tt>n x n, n=matrix.columns</tt>).
*/
public static DoubleMatrix2D distance(DoubleMatrix2D matrix, VectorVectorFunction distanceFunction) {
int columns = matrix.columns();
DoubleMatrix2D distance = new DenseDoubleMatrix2D(columns, columns);
// cache views
DoubleMatrix1D[] cols = new DoubleMatrix1D[columns];
for (int i = columns; --i >= 0;) {
cols[i] = matrix.viewColumn(i);
}
// work out all permutations
for (int i = columns; --i >= 0;) {
for (int j = i; --j >= 0;) {
double d = distanceFunction.apply(cols[i], cols[j]);
distance.setQuick(i, j, d);
distance.setQuick(j, i, d); // symmetric
}
}
return distance;
}
/**
* Constructs and returns a sampling view with a size of <tt>round(matrix.size() * fraction)</tt>. Samples "without
* replacement" from the uniform distribution.
*
* @param matrix any matrix.
* @param fraction the percentage of rows to be included in the view.
* @param randomGenerator a uniform random number generator; set this parameter to <tt>null</tt> to use a default
* generator seeded with the current time.
* @return the sampling view.
* @throws IllegalArgumentException if <tt>! (0 <= rowFraction <= 1 && 0 <= columnFraction <= 1)</tt>.
* @see org.apache.mahout.math.jet.random.sampling.RandomSampler
*/
public static DoubleMatrix1D viewSample(DoubleMatrix1D matrix, double fraction, RandomEngine randomGenerator) {
// check preconditions and allow for a little tolerance
double epsilon = 1.0e-09;
if (fraction < 0 - epsilon || fraction > 1 + epsilon) {
throw new IllegalArgumentException();
}
if (fraction < 0) {
fraction = 0;
}
if (fraction > 1) {
fraction = 1;
}
// random generator seeded with current time
if (randomGenerator == null) {
randomGenerator = new MersenneTwister((int) System.currentTimeMillis());
}
int ncols = (int) Math.round(matrix.size() * fraction);
int max = ncols;
long[] selected = new long[max]; // sampler works on long's, not int's
// sample
int n = ncols;
int N = matrix.size();
RandomSampler.sample(n, N, n, 0, selected, 0, randomGenerator);
int[] selectedCols = new int[n];
for (int i = 0; i < n; i++) {
selectedCols[i] = (int) selected[i];
}
return matrix.viewSelection(selectedCols);
}
/**
* Constructs and returns a sampling view with <tt>round(matrix.rows() * rowFraction)</tt> rows and
* <tt>round(matrix.columns() * columnFraction)</tt> columns. Samples "without replacement". Rows and columns are
* randomly chosen from the uniform distribution. Examples: <table border="1" cellspacing="0"> <tr valign="top"
* align="center"> <td> <div align="left"><tt>matrix</tt></div> </td> <td> <div align="left"><tt>rowFraction=0.2<br>
* columnFraction=0.2</tt></div> </td> <td> <div align="left"><tt>rowFraction=0.2<br> columnFraction=1.0 </tt></div>
* </td> <td> <div align="left"><tt>rowFraction=1.0<br> columnFraction=0.2 </tt></div> </td> </tr> <tr valign="top">
* <td><tt> 10 x 10 matrix<br> 1 2 3 4 5 6 7 8 9 10<br>
* 11 12 13 14 15 16 17 18 19 20<br>
* 21 22 23 24 25 26 27 28 29 30<br>
* 31 32 33 34 35 36 37 38 39 40<br>
* 41 42 43 44 45 46 47 48 49 50<br>
* 51 52 53 54 55 56 57 58 59 60<br>
* 61 62 63 64 65 66 67 68 69 70<br>
* 71 72 73 74 75 76 77 78 79 80<br>
* 81 82 83 84 85 86 87 88 89 90<br>
* 91 92 93 94 95 96 97 98 99 100 </tt> </td> <td><tt>
* 2 x 2 matrix<br> 43 50<br> 53 60 </tt></td> <td><tt> 2 x 10 matrix<br>
* 41 42 43 44 45 46 47 48 49 50<br>
* 91 92 93 94 95 96 97 98 99 100 </tt> </td> <td><tt>
* 10 x 2 matrix<br> 4 8<br> 14 18<br> 24 28<br> 34 38<br>
* 44 48<br> 54 58<br> 64 68<br> 74 78<br> 84 88<br> 94 98 </tt> </td> </tr> </table>
*
* @param matrix any matrix.
* @param rowFraction the percentage of rows to be included in the view.
* @param columnFraction the percentage of columns to be included in the view.
* @param randomGenerator a uniform random number generator; set this parameter to <tt>null</tt> to use a default
* generator seeded with the current time.
* @return the sampling view.
* @throws IllegalArgumentException if <tt>! (0 <= rowFraction <= 1 && 0 <= columnFraction <= 1)</tt>.
* @see org.apache.mahout.math.jet.random.sampling.RandomSampler
*/
public static DoubleMatrix2D viewSample(DoubleMatrix2D matrix, double rowFraction, double columnFraction,
RandomEngine randomGenerator) {
// check preconditions and allow for a little tolerance
double epsilon = 1.0e-09;
if (rowFraction < 0 - epsilon || rowFraction > 1 + epsilon) {
throw new IllegalArgumentException();
}
if (rowFraction < 0) {
rowFraction = 0;
}
if (rowFraction > 1) {
rowFraction = 1;
}
if (columnFraction < 0 - epsilon || columnFraction > 1 + epsilon) {
throw new IllegalArgumentException();
}
if (columnFraction < 0) {
columnFraction = 0;
}
if (columnFraction > 1) {
columnFraction = 1;
}
// random generator seeded with current time
if (randomGenerator == null) {
randomGenerator = new MersenneTwister((int) System.currentTimeMillis());
}
int nrows = (int) Math.round(matrix.rows() * rowFraction);
int ncols = (int) Math.round(matrix.columns() * columnFraction);
int max = Math.max(nrows, ncols);
long[] selected = new long[max]; // sampler works on long's, not int's
// sample rows
int n = nrows;
int N = matrix.rows();
RandomSampler.sample(n, N, n, 0, selected, 0, randomGenerator);
int[] selectedRows = new int[n];
for (int i = 0; i < n; i++) {
selectedRows[i] = (int) selected[i];
}
// sample columns
n = ncols;
N = matrix.columns();
RandomSampler.sample(n, N, n, 0, selected, 0, randomGenerator);
int[] selectedCols = new int[n];
for (int i = 0; i < n; i++) {
selectedCols[i] = (int) selected[i];
}
return matrix.viewSelection(selectedRows, selectedCols);
}
/**
* Constructs and returns a sampling view with <tt>round(matrix.slices() * sliceFraction)</tt> slices and
* <tt>round(matrix.rows() * rowFraction)</tt> rows and <tt>round(matrix.columns() * columnFraction)</tt> columns.
* Samples "without replacement". Slices, rows and columns are randomly chosen from the uniform distribution.
*
* @param matrix any matrix.
* @param sliceFraction the percentage of slices to be included in the view.
* @param rowFraction the percentage of rows to be included in the view.
* @param columnFraction the percentage of columns to be included in the view.
* @param randomGenerator a uniform random number generator; set this parameter to <tt>null</tt> to use a default
* generator seeded with the current time.
* @return the sampling view.
* @throws IllegalArgumentException if <tt>! (0 <= sliceFraction <= 1 && 0 <= rowFraction <= 1 && 0 <= columnFraction
* <= 1)</tt>.
* @see org.apache.mahout.math.jet.random.sampling.RandomSampler
*/
public static DoubleMatrix3D viewSample(DoubleMatrix3D matrix, double sliceFraction, double rowFraction,
double columnFraction, RandomEngine randomGenerator) {
// check preconditions and allow for a little tolerance
double epsilon = 1.0e-09;
if (sliceFraction < 0 - epsilon || sliceFraction > 1 + epsilon) {
throw new IllegalArgumentException();
}
if (sliceFraction < 0) {
sliceFraction = 0;
}
if (sliceFraction > 1) {
sliceFraction = 1;
}
if (rowFraction < 0 - epsilon || rowFraction > 1 + epsilon) {
throw new IllegalArgumentException();
}
if (rowFraction < 0) {
rowFraction = 0;
}
if (rowFraction > 1) {
rowFraction = 1;
}
if (columnFraction < 0 - epsilon || columnFraction > 1 + epsilon) {
throw new IllegalArgumentException();
}
if (columnFraction < 0) {
columnFraction = 0;
}
if (columnFraction > 1) {
columnFraction = 1;
}
// random generator seeded with current time
if (randomGenerator == null) {
randomGenerator = new MersenneTwister((int) System.currentTimeMillis());
}
int nslices = (int) Math.round(matrix.slices() * sliceFraction);
int nrows = (int) Math.round(matrix.rows() * rowFraction);
int ncols = (int) Math.round(matrix.columns() * columnFraction);
int max = Math.max(nslices, Math.max(nrows, ncols));
long[] selected = new long[max]; // sampler works on long's, not int's
// sample slices
int n = nslices;
int N = matrix.slices();
RandomSampler.sample(n, N, n, 0, selected, 0, randomGenerator);
int[] selectedSlices = new int[n];
for (int i = 0; i < n; i++) {
selectedSlices[i] = (int) selected[i];
}
// sample rows
n = nrows;
N = matrix.rows();
RandomSampler.sample(n, N, n, 0, selected, 0, randomGenerator);
int[] selectedRows = new int[n];
for (int i = 0; i < n; i++) {
selectedRows[i] = (int) selected[i];
}
// sample columns
n = ncols;
N = matrix.columns();
RandomSampler.sample(n, N, n, 0, selected, 0, randomGenerator);
int[] selectedCols = new int[n];
for (int i = 0; i < n; i++) {
selectedCols[i] = (int) selected[i];
}
return matrix.viewSelection(selectedSlices, selectedRows, selectedCols);
}
}
| 44.659643 | 177 | 0.679477 |
025519a9799fd526354fc88a9deca81336ab5602 | 1,031 | package AllAboutArrays;
import java.util.Arrays;
public class ModifyingArrayElements {
public static void main(String[] args) {
// Using the provided 2D array
int[][] intMatrix = {
{1, 1, 1, 1, 1},
{2, 4, 6, 8, 0},
{9, 8, 7, 6, 5}
};
// Replace the number 4 in the 2D array with the number 0
intMatrix[1][1] = 0;
// Declare and initialize a new empty 2x2 integer 2D array called subMatrix
int[][] subMatrix = new int[2][2];
// Using 4 lines of code, multiply each of the elements in the 2x2 top left corner of intMatrix by 5 and store the results in the subMatrix you created. Afterwards, uncomment the provided print statement below.
subMatrix[0][0] = intMatrix[0][0]*5;
subMatrix[0][1] = intMatrix[0][1]*5;
subMatrix[1][0] = intMatrix[1][0]*5;
subMatrix[1][1] = intMatrix[1][1]*5;
System.out.println(Arrays.deepToString(subMatrix));
}
}
| 36.821429 | 219 | 0.57517 |
cff99d3e267090f3b5970919f17b9be53e976545 | 91 | package com.cloud.model.enumeration;
public enum OptimiseFor {
Generic,
Windows
}
| 13 | 36 | 0.725275 |
6bc6f93e242c537c131fa5270d293cf077614e09 | 2,327 | package org.acm.sviet.schedulerama.hod.tabs;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import org.acm.sviet.schedulerama.R;
import org.acm.sviet.schedulerama.adapters.CourseAdapter;
import org.acm.sviet.schedulerama.interfaces.Refresh;
import org.acm.sviet.schedulerama.models.Course;
import org.acm.sviet.schedulerama.utility.ApiUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import cz.msebera.android.httpclient.Header;
/**
* Created by Anurag on 09-02-2016.
*
* placeholder fragment for course list view.
*/
public class CourseViewPlaceholderFragment extends Fragment{
private RecyclerView courseRecycleView;
private ArrayList<Course> courses;
private CourseAdapter courseAdapter;
private final String TAG = "/CourseViewFragment";
public CourseViewPlaceholderFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_course_view,container,false);
courseRecycleView = (RecyclerView) rootView.findViewById(R.id.courseListRecycleView);
getCourses();
courseRecycleView.setLayoutManager(new LinearLayoutManager(getActivity()));
return rootView;
}
private void getCourses(){
ApiUtil.sync(
//context for any UI response.
getActivity(),
//interface the view to refresh as per needed.
new Refresh() {
@Override
public void callback() {
getCourses();
}
},
//task type
ApiUtil.TASK.GET_COURSES,
//view to adapt
courseRecycleView);
}
}
| 29.0875 | 103 | 0.702621 |
9e81f805eb5fa80e2b1d8edb4fa37f4c4ca53f61 | 993 | package com.cqust.pojo;
import java.util.Date;
public class TStoretuisong {
private Integer id;
private Integer storeid;
private String storename;
private Date tstime;
private String tstext;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getStoreid() {
return storeid;
}
public void setStoreid(Integer storeid) {
this.storeid = storeid;
}
public String getStorename() {
return storename;
}
public void setStorename(String storename) {
this.storename = storename == null ? null : storename.trim();
}
public Date getTstime() {
return tstime;
}
public void setTstime(Date tstime) {
this.tstime = tstime;
}
public String getTstext() {
return tstext;
}
public void setTstext(String tstext) {
this.tstext = tstext == null ? null : tstext.trim();
}
} | 18.054545 | 69 | 0.599194 |
d8602acd73f66a0890f60df6e0d2e403630a5fa5 | 681 | package edu.planon.lib.client.common.dto;
import java.io.Serializable;
import java.util.Arrays;
import org.apache.wicket.util.lang.Bytes;
public class DownloadFile implements Serializable {
private static final long serialVersionUID = 1L;
private final String fileName;
private final byte[] byteArr;
public DownloadFile(String fileName, byte[] byteArr) {
this.fileName = fileName;
this.byteArr = Arrays.copyOf(byteArr, byteArr.length);
}
public String getFileName() {
return this.fileName;
}
public byte[] getByteArr() {
return Arrays.copyOf(this.byteArr, this.byteArr.length);
}
public Bytes length() {
return Bytes.bytes(this.byteArr.length);
}
}
| 22.7 | 58 | 0.74743 |
525c4cf4b24d486c2e0f9c0b6ce266a919339ec9 | 667 | package ru.atom.enums;
/**
* Created by sergey on 2/28/17.
*/
public enum Gender {
Male,
Female,
Other;
/**
* Check couple.
*
* @param country - target country
* @param partner - available partner
* @return legal status
*/
public boolean isLegalCouple(Country country, Gender partner) {
switch (country) {
case Russia:
return this != partner
&& this != Other
&& partner != Other;
case Netherlands:
case USA:
return true;
default:
return false;
}
}
} | 21.516129 | 67 | 0.473763 |
511fc6598e4b3550d9cfa788d09ac03b16db13c6 | 1,554 | /*
* 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.flume.channel;
/**
* Enumeration of built in channel selector types available in the system.
*/
public enum ChannelSelectorType {
/**
* Place holder for custom channel selectors not part of this enumeration.
*/
OTHER(null),
/**
* Replicating channel selector.
*/
REPLICATING(ReplicatingChannelSelector.class.getName()),
/**
* Multiplexing channel selector.
*/
MULTIPLEXING(MultiplexingChannelSelector.class.getName());
private final String channelSelectorClassName;
private ChannelSelectorType(String channelSelectorClassName) {
this.channelSelectorClassName = channelSelectorClassName;
}
public String getChannelSelectorClassName() {
return channelSelectorClassName;
}
}
| 30.470588 | 76 | 0.749678 |
de93db492a4fb5cf2058385f2484cc59dc69f8e1 | 13,240 | /**
* DescriptionFacadeImpl.java
* Copyright James Dempsey, 2011
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Created on 06/10/2011 7:59:35 PM
*
* $Id$
*/
package pcgen.gui2.facade;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import pcgen.cdom.enumeration.BiographyField;
import pcgen.cdom.enumeration.StringKey;
import pcgen.core.ChronicleEntry;
import pcgen.core.NoteItem;
import pcgen.core.PlayerCharacter;
import pcgen.core.display.CharacterDisplay;
import pcgen.facade.core.ChronicleEntryFacade;
import pcgen.facade.util.DefaultReferenceFacade;
import pcgen.facade.core.DescriptionFacade;
import pcgen.facade.core.NoteFacade;
import pcgen.facade.util.ReferenceFacade;
import pcgen.facade.util.DefaultListFacade;
import pcgen.facade.util.ListFacade;
import pcgen.system.LanguageBundle;
/**
* The Class <code>DescriptionFacadeImpl</code> is an implementation of
* the DescriptionFacade interface for the new user interface. It is
* intended to provide a full implementation of the new ui/core
* interaction layer.
*
* <br/>
* Last Editor: $Author$
* Last Edited: $Date$
*
* @author James Dempsey <[email protected]>
* @version $Revision$
*/
public class DescriptionFacadeImpl implements DescriptionFacade
{
/** Name of the Biography node. */
private static final String NOTE_NAME_BIO = LanguageBundle
.getString("in_bio"); //$NON-NLS-1$
/** Name of the Description node. */
private static final String NOTE_NAME_DESCRIP = LanguageBundle
.getString("in_descrip"); //$NON-NLS-1$
/** Name of the Companions notes node. */
private static final String NOTE_NAME_COMPANION = LanguageBundle
.getString("in_companions"); //$NON-NLS-1$
/** Name of the Other Assets notes node. */
private static final String NOTE_NAME_OTHER_ASSETS = LanguageBundle
.getString("in_otherAssets"); //$NON-NLS-1$
/** Name of the Magic Item notes node. */
private static final String NOTE_NAME_MAGIC_ITEMS = LanguageBundle
.getString("in_magicItems"); //$NON-NLS-1$
/** Name of the DM Notes node. */
private static final String NOTE_NAME_GM_NOTES = LanguageBundle
.getString("in_gmNotes"); //$NON-NLS-1$
private final PlayerCharacter theCharacter;
private final CharacterDisplay charDisplay;
private DefaultListFacade<ChronicleEntryFacade> chronicleEntries;
private DefaultListFacade<NoteFacade> notes;
private DefaultReferenceFacade<String> birthday;
private DefaultReferenceFacade<String> location;
private DefaultReferenceFacade<String> city;
private DefaultReferenceFacade<String> region;
private DefaultReferenceFacade<String> birthplace;
private DefaultReferenceFacade<String> personalityTrait1;
private DefaultReferenceFacade<String> personalityTrait2;
private DefaultReferenceFacade<String> phobias;
private DefaultReferenceFacade<String> interests;
private DefaultReferenceFacade<String> catchPhrase;
private DefaultReferenceFacade<String> hairStyle;
private DefaultReferenceFacade<String> speechPattern;
private DefaultListFacade<BiographyField> customBiographyFields;
/**
* Create a new DescriptionFacadeImpl instance for the character.
* @param pc The character.
*/
public DescriptionFacadeImpl(PlayerCharacter pc)
{
theCharacter = pc;
charDisplay = pc.getDisplay();
chronicleEntries = new DefaultListFacade<ChronicleEntryFacade>();
for (ChronicleEntryFacade entry : charDisplay.getChronicleEntries())
{
chronicleEntries.addElement(entry);
}
notes = new DefaultListFacade<NoteFacade>();
addDefaultNotes();
for (NoteItem item : charDisplay.getNotesList())
{
notes.addElement(item);
}
birthday = new DefaultReferenceFacade<String>(charDisplay.getSafeStringFor(StringKey.BIRTHDAY));
location = new DefaultReferenceFacade<String>(charDisplay.getSafeStringFor(StringKey.LOCATION));
city = new DefaultReferenceFacade<String>(charDisplay.getSafeStringFor(StringKey.RESIDENCE));
region = new DefaultReferenceFacade<String>(charDisplay.getRegionString());
birthplace = new DefaultReferenceFacade<String>(charDisplay.getSafeStringFor(StringKey.BIRTHPLACE));
personalityTrait1 = new DefaultReferenceFacade<String>(charDisplay.getSafeStringFor(StringKey.TRAIT1));
personalityTrait2 = new DefaultReferenceFacade<String>(charDisplay.getSafeStringFor(StringKey.TRAIT2));
phobias = new DefaultReferenceFacade<String>(charDisplay.getSafeStringFor(StringKey.PHOBIAS));
interests = new DefaultReferenceFacade<String>(charDisplay.getSafeStringFor(StringKey.INTERESTS));
catchPhrase = new DefaultReferenceFacade<String>(charDisplay.getSafeStringFor(StringKey.CATCH_PHRASE));
hairStyle = new DefaultReferenceFacade<String>(charDisplay.getSafeStringFor(StringKey.HAIR_STYLE));
speechPattern = new DefaultReferenceFacade<String>(charDisplay.getSafeStringFor(StringKey.SPEECH_TENDENCY));
customBiographyFields = new DefaultListFacade<BiographyField>();
addCharacterCustomFields();
}
private void addDefaultNotes()
{
notes.addElement(createDefaultNote(NOTE_NAME_BIO, charDisplay.getBio()));
notes.addElement(createDefaultNote(NOTE_NAME_DESCRIP, charDisplay.getDescription()));
notes.addElement(createDefaultNote(NOTE_NAME_COMPANION,
charDisplay.getSafeStringFor(StringKey.MISC_COMPANIONS)));
notes.addElement(createDefaultNote(NOTE_NAME_OTHER_ASSETS,
charDisplay.getSafeStringFor(StringKey.MISC_ASSETS)));
notes.addElement(createDefaultNote(NOTE_NAME_MAGIC_ITEMS,
charDisplay.getSafeStringFor(StringKey.MISC_MAGIC)));
notes.addElement(createDefaultNote(NOTE_NAME_GM_NOTES,
charDisplay.getSafeStringFor(StringKey.MISC_GM)));
}
/**
* @param noteNameBio
* @param bio
* @return
*/
private NoteFacade createDefaultNote(String noteName, String value)
{
NoteItem note = new NoteItem(0, -1, noteName, value);
note.setRequired(true);
return note;
}
/**
* Add any custom biography fields already registered for the character.
*/
private void addCharacterCustomFields()
{
for (BiographyField field : EnumSet.range(BiographyField.SPEECH_PATTERN, BiographyField.CATCH_PHRASE))
{
if (StringUtils.isNotEmpty(getBiographyField(field).getReference()))
{
customBiographyFields.addElement(field);
}
}
}
/* (non-Javadoc)
* @see pcgen.core.facade.DescriptionFacade#createChronicleEntry()
*/
@Override
public ChronicleEntryFacade createChronicleEntry()
{
ChronicleEntry chronicleEntry = new ChronicleEntry();
theCharacter.addChronicleEntry(chronicleEntry);
chronicleEntries.addElement(chronicleEntry);
return chronicleEntry;
}
/* (non-Javadoc)
* @see pcgen.core.facade.DescriptionFacade#removeChronicleEntry(pcgen.core.ChronicleEntry)
*/
@Override
public void removeChronicleEntry(ChronicleEntryFacade chronicleEntry)
{
if (chronicleEntry instanceof ChronicleEntry)
{
theCharacter.removeChronicleEntry((ChronicleEntry) chronicleEntry);
}
chronicleEntries.removeElement(chronicleEntry);
}
/* (non-Javadoc)
* @see pcgen.core.facade.DescriptionFacade#getChronicleEntries()
*/
@Override
public ListFacade<ChronicleEntryFacade> getChronicleEntries()
{
return chronicleEntries;
}
/**
* {@inheritDoc}
*/
@Override
public ListFacade<NoteFacade> getNotes()
{
return notes;
}
/**
* {@inheritDoc}
*/
@Override
public void setNote(NoteFacade note, String text)
{
if (note == null || !(note instanceof NoteItem))
{
return;
}
NoteItem noteItem = (NoteItem) note;
noteItem.setValue(text);
if (noteItem.isRequired())
{
String noteName = noteItem.getName();
if (NOTE_NAME_BIO.equals(noteName))
{
theCharacter.setBio(text);
}
else if (NOTE_NAME_DESCRIP.equals(noteName))
{
theCharacter.setDescription(text);
}
else if (NOTE_NAME_COMPANION.equals(noteName))
{
theCharacter.setStringFor(StringKey.MISC_COMPANIONS, text);
}
else if (NOTE_NAME_OTHER_ASSETS.equals(noteName))
{
theCharacter.setStringFor(StringKey.MISC_ASSETS, text);
}
else if (NOTE_NAME_MAGIC_ITEMS.equals(noteName))
{
theCharacter.setStringFor(StringKey.MISC_MAGIC, text);
}
else if (NOTE_NAME_GM_NOTES.equals(noteName))
{
theCharacter.setStringFor(StringKey.MISC_GM, text);
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void renameNote(NoteFacade note, String newName)
{
if (note == null || !(note instanceof NoteItem) || note.isRequired())
{
return;
}
NoteItem noteItem = (NoteItem) note;
noteItem.setName(newName);
notes.modifyElement(noteItem);
}
/**
* {@inheritDoc}
*/
@Override
public void deleteNote(NoteFacade note)
{
if (note == null || !(note instanceof NoteItem) || note.isRequired())
{
return;
}
theCharacter.removeNote((NoteItem) note);
notes.removeElement(note);
}
/**
* {@inheritDoc}
*/
@Override
public void addNewNote()
{
int parentId = -1;
int newNodeId = 0;
for (NoteItem currItem : charDisplay.getNotesList())
{
if (currItem.getId() > newNodeId)
{
newNodeId = currItem.getId();
}
}
++newNodeId;
Set<String> names = new HashSet<String>();
for (NoteFacade note : notes)
{
names.add(note.getName());
}
String baseName = LanguageBundle.getString("in_newItem"); //$NON-NLS-1$
String name = baseName;
int num = 0;
while (names.contains(name))
{
num++;
name = baseName + " " + num; //$NON-NLS-1$
}
NoteItem note =
new NoteItem(newNodeId, parentId, name, LanguageBundle
.getString("in_newValue")); //$NON-NLS-1$
theCharacter.addNotesItem(note);
notes.addElement(note);
}
/**
* {@inheritDoc}
*/
@Override
public ReferenceFacade<String> getBiographyField(BiographyField field)
{
switch (field)
{
case SPEECH_PATTERN:
return speechPattern;
case BIRTHDAY:
return birthday;
case LOCATION:
return location;
case CITY:
return city;
case REGION:
return region;
case BIRTHPLACE:
return birthplace;
case PERSONALITY_TRAIT_1:
return personalityTrait1;
case PERSONALITY_TRAIT_2:
return personalityTrait2;
case PHOBIAS:
return phobias;
case INTERESTS:
return interests;
case CATCH_PHRASE:
return catchPhrase;
case HAIR_STYLE:
return hairStyle;
default:
throw new UnsupportedOperationException("The field " + field //$NON-NLS-1$
+ " must use a dedicated getter."); //$NON-NLS-1$
}
}
/**
* {@inheritDoc}
*/
@Override
public void setBiographyField(BiographyField field, String newValue)
{
switch (field)
{
case SPEECH_PATTERN:
speechPattern.setReference(newValue);
theCharacter.setSpeechTendency(newValue);
break;
case BIRTHDAY:
birthday.setReference(newValue);
theCharacter.setBirthday(newValue);
break;
case LOCATION:
location.setReference(newValue);
theCharacter.setLocation(newValue);
break;
case CITY:
city.setReference(newValue);
theCharacter.setResidence(newValue);
break;
case BIRTHPLACE:
birthplace.setReference(newValue);
theCharacter.setBirthplace(newValue);
break;
case PERSONALITY_TRAIT_1:
personalityTrait1.setReference(newValue);
theCharacter.setTrait1(newValue);
break;
case PERSONALITY_TRAIT_2:
personalityTrait2.setReference(newValue);
theCharacter.setTrait2(newValue);
break;
case PHOBIAS:
phobias.setReference(newValue);
theCharacter.setPhobias(newValue);
break;
case INTERESTS:
interests.setReference(newValue);
theCharacter.setInterests(newValue);
break;
case CATCH_PHRASE:
catchPhrase.setReference(newValue);
theCharacter.setCatchPhrase(newValue);
break;
case HAIR_STYLE:
hairStyle.setReference(newValue);
theCharacter.setHairStyle(newValue);
break;
case REGION:
throw new UnsupportedOperationException("The field " + field //$NON-NLS-1$
+ " cannot be set from the UI."); //$NON-NLS-1$
default:
throw new UnsupportedOperationException("The field " + field //$NON-NLS-1$
+ " must use a dedicated setter."); //$NON-NLS-1$
}
}
/**
* {@inheritDoc}
*/
@Override
public ListFacade<BiographyField> getCustomBiographyFields()
{
return customBiographyFields;
}
/**
* {@inheritDoc}
*/
@Override
public void addCustomBiographyField(BiographyField field)
{
customBiographyFields.addElement(field);
}
/**
* {@inheritDoc}
*/
@Override
public void removeCustomBiographyField(BiographyField field)
{
customBiographyFields.removeElement(field);
}
}
| 27.355372 | 110 | 0.740861 |
08c2d5888e1b8c6afdd067badf16c98e09be8c10 | 8,875 | package com.qugengting.audio;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.io.IOException;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;
public class PlayActivity extends Activity {
private static final String TAG = PlayActivity.class.getSimpleName();
private boolean isPrepare = false;
private static int duration;//音频总长度
private static int currentPosition;//当前进度
private static int status; //0初始状态,1暂停,2播放,3播放完成
private SeekBar seekBar;
private static String PATH = "";
private TextView tvCurrent;
private TextView tvDuration;
public static TextView tvName;
public static TextView tvArtist;
private ImageButton btnPlay;
private LinearLayout playview;
public static ImageView logoview;
private ImageButton btn_next;
private ImageButton btn_last;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
EventBus.getDefault().register(this);
Intent i = getIntent();//获取相关的intent
PATH="http://112.74.49.205:8085/musicList/";
seekBar = findViewById(R.id.seekBar);
tvCurrent = findViewById(R.id.tv_current);
tvDuration = findViewById(R.id.tv_duration);
btnPlay = findViewById(R.id.btn_play);
playview = findViewById(R.id.play_view);
logoview= findViewById(R.id.tv_logo);
tvName=findViewById(R.id.tv_name);
tvArtist=findViewById(R.id.tv_artist);
btn_next=findViewById(R.id.btn_next);
btn_last=findViewById(R.id.btn_last);
if (i.getStringExtra("ischange")!=null)
{
seekBar.setMax(ListActivity.duration);
tvDuration.setText(getTime(ListActivity.duration));
tvCurrent.setText(getTime(seekBar.getProgress()));
byte buf[] = i.getByteArrayExtra("bitmap");
Bitmap photo_bmp = BitmapFactory.decodeByteArray(buf, 0, buf.length);
logoview.setImageBitmap(photo_bmp);
tvArtist.setText(i.getStringExtra("artist"));
tvName.setText(i.getStringExtra("songname"));
btnPlay.setBackground(getDrawable(R.drawable.stop));
}
else
{
PATH+=i.getStringExtra("filename");
Log.e("test songPath",PATH);
ListActivity.myBinder.getRingDuring(PATH);
}
btn_last.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ListActivity.myBinder.last();
}
});
btn_next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ListActivity.myBinder.next();
}
});
btnPlay.setEnabled(true);
btnPlay.setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onClick(View v) {
Log.e(TAG, "is test msg ");
Log.e("test status", String.valueOf(status));
if (status==2) {
status=1;
btnPlay.setBackground(getDrawable(R.drawable.play));
ListActivity.myBinder.pause();
} else {
ListActivity.myBinder.moveon();
status=2;
btnPlay.setBackground(getDrawable(R.drawable.stop));
}
}
});
// loadingCover(PATH);
seekBar.setProgress(0);//设置进度为0
seekBar.setSecondaryProgress(0);//设置缓冲进度为0
seekBar.setEnabled(true);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onProgressChanged(SeekBar mSeekBar, int progress, boolean fromUser) {
tvCurrent.setText(getTime(mSeekBar.getProgress()));
if (progress!=0 && status==2)
btnPlay.setBackground(getDrawable(R.drawable.stop));
else
if(status==1)
btnPlay.setBackground(getDrawable(R.drawable.play));
}
@Override
public void onStartTrackingTouch(SeekBar mSeekBar) {
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onStopTrackingTouch(SeekBar mSeekBar) {
if (status==2) {
ListActivity.myBinder.seekToPosition(mSeekBar.getProgress());
// mediaPlayer.seekTo(mSeekBar.getProgress());
tvCurrent.setText(getTime(mSeekBar.getProgress()));
} else {
if (status==1) {
status=2;
ListActivity.myBinder.seekToPosition(mSeekBar.getProgress());
// mediaPlayer.seekTo(mSeekBar.getProgress());
tvCurrent.setText(getTime(mSeekBar.getProgress()));
ListActivity.myBinder.moveon();
btnPlay.setBackground(getDrawable(R.drawable.stop));
// btnPlay.setText("暂停");
}
}
}
});
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Subscribe(threadMode = ThreadMode.MAIN) //3.0之后,需要加注解
public void onEventMainThread(UpdateUI updateUI) {
int flag = updateUI.getState();
Log.d("音频状态", status + " ---- " + flag);
//【3】设置进度
if (flag == 1) {//准备完成,获取音频长度
duration = (int) updateUI.getData();
Log.d(TAG, "总长度" + duration);
//设置总长度
seekBar.setMax(duration);
tvDuration.setText(getTime(duration));
ListActivity.myBinder.play();
status=2;
} else if (flag == 2) {//播放完成
Log.d(TAG, "播放完成~");
btnPlay.setBackground(getDrawable(R.drawable.play));
status = 3;//已完成
//重置信息
seekBar.setProgress(0);
tvCurrent.setText("00:00");
// button.setText("重新播放");
// updateNotification(3);
} else if (flag == 3) {//更新进度
if (status == 3)//避免播放完成通知与线程通知冲突
return;
currentPosition = (int) updateUI.getData();
Log.d(TAG, "当前进度" + currentPosition);
//设置进度
tvCurrent.setText(getTime(currentPosition));
seekBar.setProgress(currentPosition);
} else if (flag == 1024)
{
status= (int) updateUI.getData();
}else if (flag==1001)
{
Log.e("test1111111","");
String songname= (String) updateUI.getData();
tvName.setText(songname);
}else if (flag==1002)
{
String artist= (String) updateUI.getData();
tvArtist.setText(artist);
}else if (flag==1003)
{
Bitmap bitmap= updateUI.getBitmap();
logoview.setImageBitmap(bitmap);
}
}
private String getTime(int duration) {
int i = duration / 1000;
int h = i / (60 * 60);
String sh;
if (h == 0) {
sh = "00";
} else {
sh = String.valueOf(h);
}
int m = i / 60 % 60;
String sm;
if (m == 0) {
sm = "00";
} else {
sm = String.valueOf(m);
if (sm.length() == 1) {
sm = "0" + sm;
}
}
int s = i % 60;
String ss;
if (s == 0) {
ss = "00";
} else {
ss = String.valueOf(s);
if (ss.length() == 1) {
ss = "0" + ss;
}
}
return sm + ":" + ss;
}
}
| 29.098361 | 93 | 0.567775 |
1602f6b70d6b16d8f9dcf7aca457b51b1698535b | 1,541 | package com.adriencadet.downthere.models.bll.jobs;
import com.adriencadet.downthere.ApplicationConfiguration;
import com.adriencadet.downthere.models.bll.serializers.IPictureBLLDTOSerializer;
import com.adriencadet.downthere.models.bll.serializers.ITextFileBLLDTOSerializer;
import com.adriencadet.downthere.models.dao.IPictureDAO;
import com.adriencadet.downthere.models.dao.ITextFileDAO;
import com.adriencadet.downthere.models.services.downthereserver.IDownthereService;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
/**
* BLLJobsFactory
* <p>
*/
@Module
public class BLLJobsFactory {
@Provides
@Singleton
public ListPicturesByDateDescJob provideListPicturesByDateDescJob(
ApplicationConfiguration configuration,
IDownthereService server,
IPictureDAO pictureDAO,
IPictureBLLDTOSerializer serializer) {
return new ListPicturesByDateDescJob(configuration, server, pictureDAO, serializer);
}
@Provides
@Singleton
public ListTextFilesByDateDescJob provideListTextFilesByDateDescJob(
ApplicationConfiguration configuration,
IDownthereService server,
ITextFileDAO textFileDAO,
ITextFileBLLDTOSerializer serializer) {
return new ListTextFilesByDateDescJob(configuration, server, textFileDAO, serializer);
}
@Provides
@Singleton
public GetTextFileContentJob provideGetTextFileContentJob(
IDownthereService server) {
return new GetTextFileContentJob(server);
}
}
| 32.104167 | 94 | 0.779364 |
9cb271cb104c16d1208fa8ba0f39bbf79c22a8b0 | 2,420 | package com.levi9.rxnuclearbinding.adapters;
import android.databinding.DataBindingUtil;
import android.support.annotation.UiThread;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.levi9.rxnuclearbinding.R;
import com.levi9.rxnuclearbinding.databinding.ListItemBinding;
import com.levi9.rxnuclearbinding.models.Repo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class RepoAdapter extends RecyclerView.Adapter<RepoAdapter.ViewHolder> {
private final View empty;
private List<Repo> repos = new ArrayList<>();
public RepoAdapter(final View empty) {
this.empty = empty;
}
@Override
public RepoAdapter.ViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
final LayoutInflater inflater = LayoutInflater.from(parent.getContext());
final ListItemBinding binding = DataBindingUtil.inflate(inflater, R.layout.list_item, parent, false);
return new ViewHolder(binding.getRoot(), binding);
}
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final Repo repo = this.repos.get(position);
holder.bind(repo);
}
@Override
public int getItemCount() {
return repos.size();
}
@Override
public void onViewRecycled(ViewHolder holder) {
super.onViewRecycled(holder);
}
private void dataSetChanged() {
this.notifyDataSetChanged();
this.empty.setVisibility(this.getItemCount() == 0 ? View.VISIBLE : View.GONE);
}
@UiThread
public void addItem(final Repo repo) {
this.repos.add(repo);
this.dataSetChanged();
}
@UiThread
public void addItems(final Repo[] repos) {
this.repos.addAll(Arrays.asList(repos));
this.dataSetChanged();
}
@UiThread
public void clearItems() {
this.repos.clear();
this.dataSetChanged();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private final ListItemBinding binding;
public ViewHolder(final View view, final ListItemBinding binding) {
super(view);
this.binding = binding;
}
@UiThread
public void bind(final Repo repo) {
this.binding.setRepo(repo);
}
}
} | 27.816092 | 109 | 0.684711 |
83730266d26f969991135945586087fd35d4122e | 698 | package ru.gbooking.apiv2;
import java.io.IOException;
import com.fasterxml.jackson.annotation.*;
public enum FieldElement {
EMAIL, NAME, SURNAME;
@JsonValue
public String toValue() {
switch (this) {
case EMAIL: return "email";
case NAME: return "name";
case SURNAME: return "surname";
}
return null;
}
@JsonCreator
public static FieldElement forValue(String value) throws IOException {
if (value.equals("email")) return EMAIL;
if (value.equals("name")) return NAME;
if (value.equals("surname")) return SURNAME;
throw new IOException("Cannot deserialize FieldElement");
}
}
| 25.851852 | 74 | 0.624642 |
2dc0b70e13130acee91ad56a85071ee72080c001 | 1,799 | package com.deliveredtechnologies.rulebook;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
/**
* Tests for {@link Fact}.
*/
public class FactTest {
@Test
public void factsCanBeCreatedFromOtherFacts() {
Fact<String> fact1 = new Fact<String>("fact1", "Fact One");
Fact<String> fact2 = new Fact<String>(fact1);
Assert.assertEquals(fact1, fact2);
}
@Test
public void settingFactNameShouldChangeTheName() {
Fact<String> fact = new Fact<String>("name", "value");
fact.setName("newName");
Assert.assertEquals("newName", fact.getName());
}
@Test
public void equivalentFactsShouldHaveTheSametHashCode() {
Fact<String> fact1 = new Fact<String>("fact1", "Fact One");
Fact<String> fact2 = new Fact<String>("fact1", "Fact One");
Fact<Double> fact3 = new Fact<Double>("fact2", 1.25);
Fact<Double> fact4 = new Fact<Double>("fact2", 1.25);
Assert.assertEquals(fact3, fact4);
Assert.assertEquals(fact1, fact2);
Assert.assertEquals(fact1.hashCode(), fact2.hashCode());
Assert.assertEquals(fact3.hashCode(), fact4.hashCode());
Assert.assertNotEquals(fact1, fact3);
}
@Test
public void nonFactObjectsShouldNotEqualFactObjects() {
Fact<String> fact = new Fact<>("another", "fact");
NameValueReferable obj = Mockito.mock(NameValueReferable.class);
Mockito.when(obj.getName()).thenReturn("another");
Mockito.when(obj.getValue()).thenReturn("fact");
Assert.assertNotEquals(fact, "anotherfact");
Assert.assertNotEquals(fact, obj);
}
@Test
public void factsThatHaveTheSameNameAndDifferentValuesAreNotEqual() {
Fact<String> fact1 = new Fact<>("fact", "value1");
Fact<String> fact2 = new Fact<>("fact", "value2");
Assert.assertNotEquals(fact1, fact2);
}
}
| 28.555556 | 71 | 0.689828 |
60c5a85945490752de1ec6157919a74fd6206453 | 1,079 | package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 订单更新接口
*
* @author auto create
* @since 1.0, 2019-08-29 11:17:41
*/
public class AlipayEcoMycarParkingOrderUpdateModel extends AlipayObject {
private static final long serialVersionUID = 1216846518224442959L;
/**
* 支付宝支付流水号,系统唯一
*/
@ApiField("order_no")
private String orderNo;
/**
* 用户停车订单状态,0:成功,1:失败
*/
@ApiField("order_status")
private String orderStatus;
/**
* 停车缴费支付宝用户的ID,请ISV保证用户ID的正确性,以免导致用户在停车平台查询不到相关的订单信息
*/
@ApiField("user_id")
private String userId;
public String getOrderNo() {
return this.orderNo;
}
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
public String getOrderStatus() {
return this.orderStatus;
}
public void setOrderStatus(String orderStatus) {
this.orderStatus = orderStatus;
}
public String getUserId() {
return this.userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
}
| 19.267857 | 74 | 0.68582 |
de1b01368af5bd4a359f10a67fcea38fa7e056d3 | 3,953 | package io.joyrpc.transport.http2;
/*-
* #%L
* joyrpc
* %%
* Copyright (C) 2019 joyrpc.io
* %%
* 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.
* #L%
*/
import io.joyrpc.transport.http.HttpHeaders;
import io.joyrpc.transport.http.HttpMethod;
import static io.joyrpc.transport.http2.Http2Headers.PseudoHeaderName.*;
/**
* @date: 2019/4/12
*/
public interface Http2Headers extends HttpHeaders {
enum PseudoHeaderName {
/**
* {@code :method}.
*/
METHOD(":method"),
/**
* {@code :scheme}.
*/
SCHEME(":scheme"),
/**
* {@code :authority}.
*/
AUTHORITY(":authority"),
/**
* {@code :path}.
*/
PATH(":path"),
/**
* {@code :status}.
*/
STATUS(":status");
private String value;
PseudoHeaderName(String value) {
this.value = value;
}
public String value() {
return value;
}
}
/**
* 获取 method
*
* @return HttpMethod
*/
default HttpMethod method() {
Object methodName = get(METHOD.value);
return methodName == null ? HttpMethod.POST : HttpMethod.valueOf(methodName.toString());
}
/**
* 设置 method
*
* @param method HttpMethod
* @return Http2Headers
*/
default Http2Headers method(HttpMethod method) {
set(METHOD.value, method.name());
return this;
}
/**
* 设置 method
*
* @param method method
* @return Http2Headers
*/
default Http2Headers method(CharSequence method) {
set(METHOD.value, method);
return this;
}
/**
* 获取 path
*
* @return String
*/
default CharSequence path() {
Object path = get(PATH.value);
return path == null ? "/" : path.toString();
}
/**
* 设置path
*
* @param path path
* @return Http2Headers
*/
default Http2Headers path(CharSequence path) {
set(PATH.value, path);
return this;
}
/**
* 获取 status
*
* @return CharSequence
*/
default CharSequence status() {
Object status = get(STATUS.value);
return status == null ? "200" : status.toString();
}
/**
* 设置status
*
* @param status CharSequence
* @return Http2Headers
*/
default Http2Headers status(CharSequence status) {
set(STATUS.value, status);
return this;
}
/**
* 获取 scheme
*
* @return CharSequence
*/
default CharSequence scheme() {
Object scheme = get(SCHEME.value);
return scheme == null ? null : scheme.toString();
}
/**
* 设置 scheme
*
* @param scheme CharSequence
* @return Http2Headers
*/
default Http2Headers scheme(CharSequence scheme) {
set(SCHEME.value, scheme);
return this;
}
/**
* 获取 authority
*
* @return CharSequence
*/
default CharSequence authority() {
Object authority = get(AUTHORITY.value);
return authority == null ? null : authority.toString();
}
/**
* 设置 authority
*
* @param authority CharSequence
* @return Http2Headers
*/
default Http2Headers authority(CharSequence authority) {
set(AUTHORITY.value, authority);
return this;
}
}
| 20.805263 | 96 | 0.55578 |
1ff9bb71eb5fa72c460de96c9ebe9aa524879479 | 990 | package calendar;
import util.Dorminhoco;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Locale;
import java.util.TimeZone;
/**
* @author [email protected] @created on 19/01/2021
*/
public class ChronometroJava9 {
public static void main(String[] args) {
LocalDateTime inicio = LocalDateTime.now(ZoneId.of("America/Sao_Paulo"));
Dorminhoco.durma(3000L);
LocalDateTime fim = LocalDateTime.now(ZoneId.of("America/Sao_Paulo"));
Duration duracao = Duration.between(inicio, fim);
System.out.println(duracao);
/* Java > 9 */
// String hmsm = String.format("%02d:%02d:%02d:%03d",
// duracao.toHoursPart(),
// duracao.toMinutesPart(),
// duracao.toSecondsPart(),
// duracao.toMillisPart());
//
// System.out.printf(hmsm);
}
}
| 24.75 | 81 | 0.643434 |
17a568bb53bf8ac663c0274348bdcf43b86c3628 | 3,355 | package org.anddev.andengine.opengl.texture.region;
import org.anddev.andengine.opengl.texture.*;
import org.anddev.andengine.opengl.texture.region.buffer.*;
public class TiledTextureRegion extends BaseTextureRegion
{
private int mCurrentTileColumn;
private int mCurrentTileRow;
private final int mTileColumns;
private final int mTileCount;
private final int mTileRows;
public TiledTextureRegion(final Texture texture, final int n, final int n2, final int n3, final int n4, final int mTileColumns, final int mTileRows) {
super(texture, n, n2, n3, n4);
this.mTileColumns = mTileColumns;
this.mTileRows = mTileRows;
this.mTileCount = this.mTileColumns * this.mTileRows;
this.mCurrentTileColumn = 0;
this.mCurrentTileRow = 0;
this.initTextureBuffer();
}
public TiledTextureRegion clone() {
final TiledTextureRegion tiledTextureRegion = new TiledTextureRegion(this.mTexture, this.getTexturePositionX(), this.getTexturePositionY(), this.getWidth(), this.getHeight(), this.mTileColumns, this.mTileRows);
tiledTextureRegion.setCurrentTileIndex(this.mCurrentTileColumn, this.mCurrentTileRow);
return tiledTextureRegion;
}
public int getCurrentTileColumn() {
return this.mCurrentTileColumn;
}
public int getCurrentTileIndex() {
return this.mCurrentTileRow * this.mTileColumns + this.mCurrentTileColumn;
}
public int getCurrentTileRow() {
return this.mCurrentTileRow;
}
@Override
public TiledTextureRegionBuffer getTextureBuffer() {
return (TiledTextureRegionBuffer)this.mTextureRegionBuffer;
}
public float getTexturePositionOfCurrentTileX() {
return super.getTexturePositionX() + this.mCurrentTileColumn * this.getTileWidth();
}
public float getTexturePositionOfCurrentTileY() {
return super.getTexturePositionY() + this.mCurrentTileRow * this.getTileHeight();
}
public int getTileCount() {
return this.mTileCount;
}
public int getTileHeight() {
return super.getHeight() / this.mTileRows;
}
public int getTileWidth() {
return super.getWidth() / this.mTileColumns;
}
@Override
protected void initTextureBuffer() {
if (this.mTileRows != 0 && this.mTileColumns != 0) {
super.initTextureBuffer();
}
}
public void nextTile() {
this.setCurrentTileIndex((1 + this.getCurrentTileIndex()) % this.getTileCount());
}
@Override
protected TiledTextureRegionBuffer onCreateTextureRegionBuffer() {
return new TiledTextureRegionBuffer(this, 35044);
}
public void setCurrentTileIndex(final int n) {
if (n < this.mTileCount) {
final int mTileColumns = this.mTileColumns;
this.setCurrentTileIndex(n % mTileColumns, n / mTileColumns);
}
}
public void setCurrentTileIndex(final int mCurrentTileColumn, final int mCurrentTileRow) {
if (mCurrentTileColumn != this.mCurrentTileColumn || mCurrentTileRow != this.mCurrentTileRow) {
this.mCurrentTileColumn = mCurrentTileColumn;
this.mCurrentTileRow = mCurrentTileRow;
super.updateTextureRegionBuffer();
}
}
}
| 34.234694 | 218 | 0.677496 |
ac0339e277a50d32f99c78aa49b84027806f047e | 1,002 | package com.smatechnologies.opcon.command.api.interfaces;
import java.util.List;
import com.smatechnologies.opcon.command.api.arguments.OpConCliArguments;
import com.smatechnologies.opcon.command.api.modules.JobLogData;
import com.smatechnologies.opcon.restapiclient.api.OpconApi;
import com.smatechnologies.opcon.restapiclient.model.dailyjob.DailyJob;
public interface IJob {
public Integer jobActionRequest(OpconApi opconApi, OpConCliArguments _OpConCliArguments) throws Exception;
public Integer jobAddRequest(OpconApi opconApi, OpConCliArguments _OpConCliArguments) throws Exception;
public List<JobLogData> getJobLog(OpconApi opconApi, OpConCliArguments _OpConCliArguments) throws Exception;
public List<JobLogData> getJobLogByDailyJob(OpconApi opconApi, DailyJob dailyJob) throws Exception;
public DailyJob getDailyJobByName(OpconApi opconApi, OpConCliArguments _OpConCliArguments) throws Exception;
public DailyJob getDailyJobById(OpconApi opconApi, String jobId) throws Exception;
}
| 50.1 | 109 | 0.858283 |
02692ad020c8c11e5f1e9027f07108f2b6cab531 | 4,543 | /*
* 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.dromara.hmily.xa.core;
import javax.transaction.xa.XAException;
import java.util.HashMap;
import java.util.Map;
/**
* HmliyXaException .
*
* @author sixh chenbin
*/
public class HmilyXaException extends XAException {
public static final int UNKNOWN = 1000;
private static final Map<Integer, String> ERROR_CODES = new HashMap<>();
static {
//XA_RBBASE,XA_RBROLLBACK
ERROR_CODES.put(XAException.XA_RBROLLBACK, "the XaResource indicates that the rollback was caused by an unspecified reason.");
ERROR_CODES.put(XAException.XA_RBCOMMFAIL, "the XaResource indicates that the rollback was caused by a communication failure.");
ERROR_CODES.put(XAException.XA_RBDEADLOCK, "the XaResource a deadlock was detected.");
ERROR_CODES.put(XAException.XA_RBINTEGRITY, "the XaResource a condition that violates the integrity of the resource was detected.");
ERROR_CODES.put(XAException.XA_RBOTHER, "the XaResource the resource manager rolled back the transaction branch for a reason not on this list.");
ERROR_CODES.put(XAException.XA_RBPROTO, "the XaResource a protocol error occurred in the resource manager.");
ERROR_CODES.put(XAException.XA_RBTIMEOUT, "the XaResource a transaction branch took too long.");
//XA_RBTRANSIENT,XA_RBEND
ERROR_CODES.put(XAException.XA_RBTRANSIENT, "the XaResource may retry the transaction branch.");
ERROR_CODES.put(XAException.XA_NOMIGRATE, "the XaResource resumption must occur where the suspension occurred.");
ERROR_CODES.put(XAException.XA_HEURHAZ, "the XaResource the transaction branch may have been heuristically completed");
ERROR_CODES.put(XAException.XA_HEURCOM, "the XaResource the transaction branch has been heuristically committed.");
ERROR_CODES.put(XAException.XA_HEURRB, "the XaResource the transaction branch has been heuristically rolled back.");
ERROR_CODES.put(XAException.XA_HEURMIX, "the XaResource the transaction branch has been heuristically committed and rolled back.");
ERROR_CODES.put(XAException.XA_RETRY, "the XaResource routine returned with no effect and may be reissued.");
ERROR_CODES.put(XAException.XA_RDONLY, "the XaResource the transaction branch was read-only and has been committed.");
ERROR_CODES.put(XAException.XAER_ASYNC, "the XaResource there is an asynchronous operation already outstanding.");
ERROR_CODES.put(XAException.XAER_RMERR, "the XaResource a resource manager error has occurred in the transaction branch.");
ERROR_CODES.put(XAException.XAER_NOTA, "the XaResource the XID is not valid.");
ERROR_CODES.put(XAException.XAER_INVAL, "the XaResource invalid arguments were given.");
ERROR_CODES.put(XAException.XAER_PROTO, "the XaResource routine was invoked in an inproper context.");
ERROR_CODES.put(XAException.XAER_RMFAIL, "the XaResource resource manager is unavailable.");
ERROR_CODES.put(XAException.XAER_DUPID, "the XaResource the XID already exists.");
ERROR_CODES.put(XAException.XAER_OUTSIDE, "the XaResource the resource manager is doing work outside a global transaction.");
}
/**
* Instantiates a new Hmliy xa exception.
*
* @param errorCode the error code
*/
public HmilyXaException(final int errorCode) {
super(errorCode);
}
/**
* Gets message.
*
* @param xaException the xa exception
* @return the message
*/
public static String getMessage(final XAException xaException) {
int errorCode = xaException.errorCode;
String s = ERROR_CODES.get(errorCode);
return "errorCode:" + errorCode + ":" + s;
}
}
| 52.825581 | 153 | 0.736298 |
d54f3539a4a490af418667145f1bfb1530e24b68 | 238 | package com.sys.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/comment")
public class CommentController {
}
| 18.307692 | 62 | 0.823529 |
60d493705bfa8e9afb34daf2f7a6499deb9894e5 | 4,338 | package com.liveaction.google.hashcode2019.model;
import com.google.common.collect.Sets;
import com.liveaction.google.hashcode2019.input.Input;
import com.liveaction.google.hashcode2019.output.writer.OutputWriter;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Set;
public class SolverTest {
// @Test
// public void shouldIndex() {
// ImmutableList<Photo> tested = ImmutableList.of(new Photo(0, ImmutableSet.of("tag1"), true),
// new Photo(1, ImmutableSet.of("tag1", "tag2"), true),
// new Photo(2, ImmutableSet.of("tag2"), true));
// Collection<IndexedPhoto> indexed = Solver.indexPhoto(tested);
// Assertions.assertThat(indexed)
// .extracting(ip -> ip.tags)
// .containsOnly(ImmutableSet.of(0), ImmutableSet.of(0, 1), ImmutableSet.of(1));
// }
@Test
public void solve() throws IOException {
Solver solver = new Solver();
Path path = Paths.get("a_example.txt");
Input input = Input.fromFile(path);
List<Slide> solve = solver.solve(input.getPhotos(), 1000 ,1000);
System.out.println(solve);
OutputWriter.writeOutput(solve, path);
System.out.println(Solver.score(solve));
}
@Test
public void solveB() throws IOException {
Solver solver = new Solver();
Path path = Paths.get("b_lovely_landscapes.txt");
Input input = Input.fromFile(path);
List<Slide> solve = solver.solve(input.getPhotos(), 50, 50);
System.out.println(solve);
System.out.println(Solver.score(solve));
OutputWriter.writeOutput(solve, path);
}
@Test
public void showB() throws IOException {
Solver solver = new Solver();
Path path = Paths.get("b_lovely_landscapes.txt");
Input input = Input.fromFile(path);
Set<Photo> photos = input.getPhotos();
new TagMapping(photos);
Set<String> tags = Sets.newHashSet();
int count = 0;
for (Photo photo : photos) {
for (String tag : photo.tags) {
tags.add(tag);
count++;
}
}
System.out.println("count "+count);
System.out.println("tag size "+tags.size());
}
@Test
public void solveC() throws IOException {
Solver solver = new Solver();
Path path = Paths.get("c_memorable_moments.txt");
Input input = Input.fromFile(path);
List<Slide> solve = solver.solve(input.getPhotos(), 50 ,50);
System.out.println(solve);
System.out.println(Solver.score(solve));
OutputWriter.writeOutput(solve, path);
}
@Test
public void solveD() throws IOException {
Solver solver = new Solver();
Path path = Paths.get("d_pet_pictures.txt");
Input input = Input.fromFile(path);
List<Slide> solve = solver.solve(input.getPhotos(),50, 50);
System.out.println(solve);
System.out.println(Solver.score(solve));
OutputWriter.writeOutput(solve, path);
}
@Test
public void solveE() throws IOException {
Solver solver = new Solver();
Path path = Paths.get("e_shiny_selfies.txt");
Input input = Input.fromFile(path);
List<Slide> solve = solver.solve(input.getPhotos(),50 ,50);
System.out.println(solve);
System.out.println(Solver.score(solve));
OutputWriter.writeOutput(solve, path);
}
// @Test
// public void shouldMergeVerticals() {
// int tag1 = 0;
// int tag2 = 1;
// int tag3 = 2;
// int tag4 = 3;
// int tag5 = 4;
// IndexedPhoto p1 = new IndexedPhoto(0, ImmutableSet.of(tag1, tag2), false);
// IndexedPhoto p2 = new IndexedPhoto(1, ImmutableSet.of(tag2, tag3), false);
// IndexedPhoto p3 = new IndexedPhoto(2, ImmutableSet.of(tag4, tag5), false);
// IndexedPhoto p4 = new IndexedPhoto(3, ImmutableSet.of(tag1), false);
// ImmutableList<IndexedPhoto> photos = ImmutableList.of(p1, p2, p3, p4);
// List<Slide> actual = Solver.mergeVerticalsPhoto(photos);
// Assertions.assertThat(actual)
// .containsOnly(new Slide(p1, p3), new Slide(p2, p4));
// }
} | 32.863636 | 101 | 0.611803 |
405e8478886b458de77d88205dde56b165616733 | 574 | package com.fishercoder;
import com.fishercoder.common.classes.Point;
import com.fishercoder.solutions._149;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class _149Test {
private static _149.Solution1 solution1;
private static Point[] points;
@BeforeClass
public static void setup() {
solution1 = new _149.Solution1();
}
@Test
public void test1() {
points = new Point[] {new Point(0, 0), new Point(1, 65536), new Point(65536, 0)};
assertEquals(2, solution1.maxPoints(points));
}
}
| 22.96 | 85 | 0.724739 |
cfeb8f553652e9ffaba7cbac30d879178328da87 | 3,964 | /*
* Copyright 2016 peter.
*
* 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 onl.area51.httpd.service;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.spi.CDI;
import javax.inject.Inject;
import org.apache.http.config.SocketConfig;
import onl.area51.httpd.HttpServer;
import onl.area51.httpd.HttpServerBuilder;
import onl.area51.kernel.CommandArguments;
import uk.trainwatch.util.config.Configuration;
import uk.trainwatch.util.config.ConfigurationService;
import onl.area51.httpd.action.Actions;
@ApplicationScoped
public class HttpService
{
private static final Logger LOG = Logger.getGlobal();
@Inject
private ConfigurationService configurationService;
private Configuration httpdConfig;
private HttpServer server;
private int port;
private String serverInfo;
/**
* Instantiate this bean on startup.
*
* @param args
*/
public void boot( @Observes CommandArguments args )
{
// Nothing to do here, it's presence ensures the bean is instantiated by CDI
}
@PostConstruct
void start()
{
httpdConfig = configurationService.getConfiguration( "httpd" );
port = httpdConfig.getInt( "port", 8080 );
serverInfo = httpdConfig.getString( "serverInfo", "Area51/1.1" );
LOG.log( Level.INFO, () -> "Creating http server " + serverInfo + " on port " + port );
HttpServerBuilder serverBuilder = HttpServerBuilder.builder()
// HTTP Server config
.setSocketConfig( SocketConfig.custom()
.setSoTimeout( httpdConfig.getInt( "socket.soTimeout", 15000 ) )
.setTcpNoDelay( httpdConfig.getBoolean( "socket.tcpNoDelay", true ) )
.build() )
.setListenerPort( port )
.setServerInfo( serverInfo )
.setSslContext( null )
.setExceptionLogger( ex -> LOG.log( Level.SEVERE, null, ex ) )
.shutdown( httpdConfig.getLong( "shutdown.time", 5L ), httpdConfig.getEnum( "shutdown.unit", TimeUnit.class, TimeUnit.SECONDS ) );
// Default global action is to serve resources
Actions.registerClassResourceHandler( serverBuilder, HttpService.class );
serverBuilder.notify( CDI.current().getBeanManager()::fireEvent );
// Add global error handlers. As these are at the end, earlier ones take precedence
Actions.registerErrorHandlers( serverBuilder );
server = serverBuilder.build();
LOG.log( Level.INFO, () -> "Starting http server " + serverInfo + " on port " + port );
try {
server.start();
}
catch( IOException ex ) {
throw new UncheckedIOException( ex );
}
LOG.log( Level.INFO, () -> "Started http server " + serverInfo + " on port " + port );
}
@PreDestroy
void stop()
{
LOG.log( Level.INFO, () -> "Shutting down http server " + serverInfo + " on port " + port );
server.stop();
LOG.log( Level.INFO, () -> "Shut down http server " + serverInfo + " on port " + port );
}
}
| 34.469565 | 146 | 0.663724 |
79db342405cfcf13efc2304ae868b4b8b5c51730 | 431 | package com.zc.zcbucks.repository;
import com.zc.zcbucks.model.CoffeeOrder;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/**
* @description:
* @author: Zhangc
* @date: 2019-02-27
*/
public interface CoffeeOrderRepository extends JpaRepository<CoffeeOrder,Long> {
List<CoffeeOrder> findByCustomerOrderById(String customer);
List<CoffeeOrder> findByItemsName(String name);
}
| 21.55 | 80 | 0.772622 |
1ab157cf673e6e5885ade662e232e44b4a1ee7dc | 17,346 | package puzzledice;
import gui.AreaEditPanel;
import gui.PuzzleEditPanel;
import gui.WindowMain;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.swing.BoxLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import com.mxgraph.model.mxCell;
import com.mxgraph.view.mxGraph;
public class DoorUnlockBlock extends PuzzleBlock {
private AreaBlock _sourceArea, _destArea;
private PuzzleBlock _keyBlock;
private static int nextIndex = 0;
public static void reset() {
nextIndex = 0;
}
private String _sourceAreaName, _destAreaName, _keyName;
public void setSourceAreaName(String value) {
_sourceAreaName = value;
}
public void setDestAreaName(String value) {
_destAreaName = value;
}
public void setKeyName(String value) {
_keyName = value;
}
private JComboBox _sourceAreaSelect, _destAreaSelect, _keySelect;
// So we can actually reference ourself inside actionlisteners
private DoorUnlockBlock _selfReference;
public DoorUnlockBlock()
{
_selfReference = this;
_name = "Door-Unlock-Puzzle-" + ++nextIndex;
_type = "Door Unlock Puzzle";
JPanel editPanel = new JPanel();
editPanel.setLayout(new BoxLayout(editPanel, BoxLayout.Y_AXIS));
// Key Select Panel
JPanel keyPanel = new JPanel();
keyPanel.setLayout(new BoxLayout(keyPanel, BoxLayout.X_AXIS));
JLabel keyLabel = new JLabel("Key Spawn:");
keyPanel.add(keyLabel);
_keySelect = new JComboBox();
_keySelect.setMaximumSize(new Dimension(Integer.MAX_VALUE, _keySelect.getPreferredSize().height));
keyPanel.add(_keySelect);
editPanel.add(keyPanel);
// Source Area Select Panel
JPanel sourceAreaPanel = new JPanel();
sourceAreaPanel.setLayout(new BoxLayout(sourceAreaPanel, BoxLayout.X_AXIS));
JLabel sourceAreaLabel = new JLabel("Door Spawn Area:");
sourceAreaPanel.add(sourceAreaLabel);
_sourceAreaSelect = new JComboBox();
_sourceAreaSelect.setMaximumSize(new Dimension(Integer.MAX_VALUE, _sourceAreaSelect.getPreferredSize().height));
sourceAreaPanel.add(_sourceAreaSelect);
editPanel.add(sourceAreaPanel);
// Destination Area Select Panel
JPanel destAreaPanel = new JPanel();
destAreaPanel.setLayout(new BoxLayout(destAreaPanel, BoxLayout.X_AXIS));
JLabel destAreaLabel = new JLabel("Destination Area:");
destAreaPanel.add(destAreaLabel);
_destAreaSelect = new JComboBox();
_destAreaSelect.setMaximumSize(new Dimension(Integer.MAX_VALUE, _destAreaSelect.getPreferredSize().height));
destAreaPanel.add(_destAreaSelect);
editPanel.add(destAreaPanel);
_editUI = editPanel;
_keySelect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(_keyBlock == _keySelect.getSelectedItem() || _keyBlock == null && _keySelect.getSelectedItem().equals("None"))
return;
mxGraph puzzleGraph = WindowMain.getPuzzleGraph();
// Before anything, check for a cycle
if (_keySelect.getSelectedItem() != null && !_keySelect.getSelectedItem().equals("None")) {
PuzzleBlock block = (PuzzleBlock)_keySelect.getSelectedItem();
if (block.canReachBlockBackwards(DoorUnlockBlock.this)) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(null, "Error: Cannot add cycle to puzzle graph.");
}
});
if (_keyBlock != null)
_keySelect.setSelectedItem(_keyBlock);
else
_keySelect.setSelectedIndex(0);
return;
}
}
// first, see if we need to remove a previous edge
if(_keyBlock != null)
{
puzzleGraph.getModel().beginUpdate();
try { puzzleGraph.removeCells(puzzleGraph.getEdgesBetween(_keyBlock.getGraphCell(), _graphCell, false)); }
finally { puzzleGraph.getModel().endUpdate(); }
}
if (_keySelect.getSelectedItem() == null)
_keySelect.setSelectedIndex(0);
if(_keySelect.getSelectedItem().equals("None"))
_keyBlock = null;
else
{
_keyBlock = (PuzzleBlock)_keySelect.getSelectedItem();
// update the graph with a new edge
puzzleGraph.getModel().beginUpdate();
try { puzzleGraph.insertEdge(puzzleGraph.getDefaultParent(), null, null, _keyBlock.getGraphCell(), _graphCell);}
finally { puzzleGraph.getModel().endUpdate();}
}
PuzzleEditPanel.resetTextualDescription();
WindowMain.updatePuzzleGraph();
}
});
_sourceAreaSelect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(_sourceArea == _sourceAreaSelect.getSelectedItem() || _sourceArea == null && _sourceAreaSelect.getSelectedItem().equals("None"))
return;
mxGraph puzzleGraph = WindowMain.getPuzzleGraph();
// Before anything, check for a cycle
if (_sourceAreaSelect.getSelectedItem() != null && !_sourceAreaSelect.getSelectedItem().equals("None")) {
AreaBlock block = (AreaBlock)_sourceAreaSelect.getSelectedItem();
if (block.canReachBlockBackwards(DoorUnlockBlock.this)) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(null, "Error: Cannot add cycle to puzzle graph.");
}
});
if (_sourceArea != null)
_sourceAreaSelect.setSelectedItem(_sourceArea);
else
_sourceAreaSelect.setSelectedIndex(0);
return;
}
}
// First, see if we need to remove a previous edge
if(_sourceArea != null)
{
_sourceArea.removeSourceLock(_selfReference);
puzzleGraph.getModel().beginUpdate();
try
{
puzzleGraph.removeCells(puzzleGraph.getEdgesBetween(_sourceArea.getPuzzleGraphCell(), _graphCell, false));
_sourceArea.maybeDeletePuzzleCell();
}
finally { puzzleGraph.getModel().endUpdate();}
}
if (_sourceAreaSelect.getSelectedItem() == null)
_sourceAreaSelect.setSelectedIndex(0);
if(_sourceAreaSelect.getSelectedItem().equals("None"))
_sourceArea = null;
else
{
_sourceArea = (AreaBlock)_sourceAreaSelect.getSelectedItem();
_sourceArea.addSourceLock(_selfReference);
// update the graph with a new edge
puzzleGraph.getModel().beginUpdate();
try
{
if(_sourceArea.getPuzzleGraphCell() == null) {
_sourceArea.setPuzzleGraphCell(puzzleGraph.insertVertex(puzzleGraph.getDefaultParent(), null, _sourceArea, 0, 0, 0, 0, null));
mxCell edge = (mxCell)puzzleGraph.insertEdge(puzzleGraph.getDefaultParent(), null, null, WindowMain.getHierarchyRoot(), _sourceArea.getPuzzleGraphCell());
edge.setVisible(false);
puzzleGraph.updateCellSize(_sourceArea.getPuzzleGraphCell());
}
puzzleGraph.insertEdge(puzzleGraph.getDefaultParent(), null, null, _sourceArea.getPuzzleGraphCell(), _graphCell);
}
finally {puzzleGraph.getModel().endUpdate();}
}
// Update the other list
_destAreaSelect.setModel(new DefaultComboBoxModel(makeDestAreaList()));
if(_destArea == null)
_destAreaSelect.setSelectedIndex(0);
else
_destAreaSelect.setSelectedItem(_destArea);
PuzzleEditPanel.resetTextualDescription();
WindowMain.updatePuzzleGraph();
}
});
_destAreaSelect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(_destArea == _destAreaSelect.getSelectedItem() || _destArea == null && _destAreaSelect.getSelectedItem().equals("None"))
return;
mxGraph puzzleGraph = WindowMain.getPuzzleGraph();
// Before anything, check for a cycle
if (_destAreaSelect.getSelectedItem() != null && !_destAreaSelect.getSelectedItem().equals("None")) {
AreaBlock block = (AreaBlock)_destAreaSelect.getSelectedItem();
if (DoorUnlockBlock.this.canReachBlockBackwards(block)) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(null, "Error: Cannot add cycle to puzzle graph.");
}
});
if (_destArea != null)
_destAreaSelect.setSelectedItem(_destArea);
else
_destAreaSelect.setSelectedIndex(0);
return;
}
}
// First, see if we need to remove a previous edge
if(_destArea != null)
{
_destArea.removeDoorLock(_selfReference);
puzzleGraph.getModel().beginUpdate();
try
{
puzzleGraph.removeCells(puzzleGraph.getEdgesBetween(_destArea.getPuzzleGraphCell(), _graphCell, false));
_destArea.maybeDeletePuzzleCell();
}
finally { puzzleGraph.getModel().endUpdate();}
}
if (_destAreaSelect.getSelectedItem() == null)
_destAreaSelect.setSelectedIndex(0);
if(_destAreaSelect.getSelectedItem().equals("None"))
_destArea = null;
else
{
_destArea = (AreaBlock)_destAreaSelect.getSelectedItem();
_destArea.addDoorLock(_selfReference);
// update the graph with a new edge
puzzleGraph.getModel().beginUpdate();
try
{
if(_destArea.getPuzzleGraphCell() == null) {
_destArea.setPuzzleGraphCell(puzzleGraph.insertVertex(puzzleGraph.getDefaultParent(), null, _destArea, 0, 0, 0, 0, null));
mxCell edge = (mxCell)puzzleGraph.insertEdge(puzzleGraph.getDefaultParent(), null, null, WindowMain.getHierarchyRoot(), _destArea.getPuzzleGraphCell());
edge.setVisible(false);
puzzleGraph.updateCellSize(_destArea.getPuzzleGraphCell());
}
puzzleGraph.insertEdge(puzzleGraph.getDefaultParent(), null, null, _graphCell, _destArea.getPuzzleGraphCell());
}
finally {puzzleGraph.getModel().endUpdate();}
}
// Update the other list
_sourceAreaSelect.setModel(new DefaultComboBoxModel(makeSourceAreaList()));
if(_sourceArea == null)
_sourceAreaSelect.setSelectedIndex(0);
else
_sourceAreaSelect.setSelectedItem(_sourceArea);
PuzzleEditPanel.resetTextualDescription();
WindowMain.updatePuzzleGraph();
}
});
}
@Override
public void update() {
_keySelect.setModel(new DefaultComboBoxModel(makeKeyList()));
if (_keyBlock == null)
_keySelect.setSelectedIndex(0);
else
_keySelect.setSelectedItem(_keyBlock);
_sourceAreaSelect.setModel(new DefaultComboBoxModel(makeSourceAreaList()));
if(_sourceArea == null)
_sourceAreaSelect.setSelectedIndex(0);
else
_sourceAreaSelect.setSelectedItem(_sourceArea);
_destAreaSelect.setModel(new DefaultComboBoxModel(makeDestAreaList()));
if(_destArea == null)
_destAreaSelect.setSelectedIndex(0);
else
_destAreaSelect.setSelectedItem(_destArea);
}
private Object[] makeKeyList()
{
List<Object> retVal = new ArrayList<Object>();
PuzzleBlock[] blockList = PuzzleEditPanel.getBlockList();
retVal.add("None");
for(PuzzleBlock p : blockList) {
if(!p.equals(this))
retVal.add(p);
}
return retVal.toArray();
}
private Object[] makeSourceAreaList()
{
List<Object> retVal = new ArrayList<Object>();
AreaBlock[] areaList = AreaEditPanel.getAreaList();
retVal.add("None");
for(AreaBlock a : areaList) {
if(!a.equals(_destAreaSelect.getSelectedItem()))
retVal.add(a);
}
return retVal.toArray();
}
private Object[] makeDestAreaList()
{
List<Object> retVal = new ArrayList<Object>();
AreaBlock[] areaList = AreaEditPanel.getAreaList();
retVal.add("None");
for(AreaBlock a : areaList) {
if(!a.equals(_sourceAreaSelect.getSelectedItem()))
retVal.add(a);
}
return retVal.toArray();
}
@Override
public void maybeRemoveRef(PuzzleBlock block)
{
if (block.equals(_keyBlock)) {
_keyBlock = null;
_keySelect.setSelectedIndex(0);
}
}
@Override
public void onDelete()
{
// Remove our reference to our source and dest areas
mxGraph puzzleGraph = WindowMain.getPuzzleGraph();
if(_sourceArea != null)
{
_sourceArea.removeSourceLock(this);
puzzleGraph.getModel().beginUpdate();
try
{
puzzleGraph.removeCells(puzzleGraph.getEdgesBetween(_sourceArea.getPuzzleGraphCell(), _graphCell, false));
_sourceArea.maybeDeletePuzzleCell();
}
finally { puzzleGraph.getModel().endUpdate();}
}
if(_destArea != null)
{
_destArea.removeDoorLock(this);
puzzleGraph.getModel().beginUpdate();
try
{
puzzleGraph.removeCells(puzzleGraph.getEdgesBetween(_destArea.getPuzzleGraphCell(), _graphCell, false));
_destArea.maybeDeletePuzzleCell();
}
finally { puzzleGraph.getModel().endUpdate();}
}
}
// For when the changing area topology creates a cycle with this door unlock.
// Need to break the source edges to fix the cycle
public void disconnectSource()
{
mxGraph puzzleGraph = WindowMain.getPuzzleGraph();
if (_sourceArea != null) {
_sourceArea.removeSourceLock(this);
puzzleGraph.getModel().beginUpdate();
try
{
puzzleGraph.removeCells(puzzleGraph.getEdgesBetween(_sourceArea.getPuzzleGraphCell(), _graphCell, false));
}
finally { puzzleGraph.getModel().endUpdate(); }
_sourceArea = null;
_sourceAreaSelect.setSelectedIndex(0);
}
if (_keyBlock != null) {
puzzleGraph.getModel().beginUpdate();
try
{
puzzleGraph.removeCells(puzzleGraph.getEdgesBetween(_keyBlock.getGraphCell(), _graphCell, false));
}
finally { puzzleGraph.getModel().endUpdate(); }
_keyBlock = null;
_keySelect.setSelectedIndex(0);
}
}
public AreaBlock getSourceBlock()
{
return _sourceArea;
}
public AreaBlock getDestBlock()
{
return _destArea;
}
@Override
public void maybeRemoveRef(AreaBlock area)
{
if(area.equals(_sourceArea)) {
_sourceArea = null;
_sourceAreaSelect.setSelectedIndex(0);
}
if(area.equals(_destArea)) {
_destArea = null;
_destAreaSelect.setSelectedIndex(0);
}
}
@Override
public String getTextualDescription()
{
String retVal = "";
if (_sourceArea != null)
retVal += _sourceArea.getTextualDescription();
if(_keyBlock != null)
retVal += _keyBlock.getTextualDescription();
String sourceArea = (_sourceArea == null) ? "SOMEWHERE" : _sourceArea.getName();
String destArea = (_destArea == null) ? "SOMEWHERE" : _destArea.getName();
String key = (_keyBlock == null) ? "SOMETHING" : _keyBlock.getOutputTempName();
retVal += "The player uses " + key + " to unlock the door from " + sourceArea + " to " + destArea + ". ";
return retVal;
}
@Override
public void attachBlocksToName(Map<String, AreaBlock> areas, Map<String, PuzzleBlock> puzzles)
{
mxGraph puzzleGraph = WindowMain.getPuzzleGraph();
if (_sourceAreaName != null) {
_sourceArea = areas.get(_sourceAreaName);
_sourceArea.addSourceLock(_selfReference);
puzzleGraph.getModel().beginUpdate();
try
{
if(_sourceArea.getPuzzleGraphCell() == null) {
_sourceArea.setPuzzleGraphCell(puzzleGraph.insertVertex(puzzleGraph.getDefaultParent(), null, _sourceArea, 0, 0, 0, 0, null));
mxCell edge = (mxCell)puzzleGraph.insertEdge(puzzleGraph.getDefaultParent(), null, null, WindowMain.getHierarchyRoot(), _sourceArea.getPuzzleGraphCell());
edge.setVisible(false);
puzzleGraph.updateCellSize(_sourceArea.getPuzzleGraphCell());
}
puzzleGraph.insertEdge(puzzleGraph.getDefaultParent(), null, null, _sourceArea.getPuzzleGraphCell(), _graphCell);
}
finally {puzzleGraph.getModel().endUpdate();}
}
if (_destAreaName != null) {
_destArea = areas.get(_destAreaName);
_destArea.addDoorLock(_selfReference);
// update the graph with a new edge
puzzleGraph.getModel().beginUpdate();
try
{
if(_destArea.getPuzzleGraphCell() == null) {
_destArea.setPuzzleGraphCell(puzzleGraph.insertVertex(puzzleGraph.getDefaultParent(), null, _destArea, 0, 0, 0, 0, null));
mxCell edge = (mxCell)puzzleGraph.insertEdge(puzzleGraph.getDefaultParent(), null, null, WindowMain.getHierarchyRoot(), _destArea.getPuzzleGraphCell());
edge.setVisible(false);
puzzleGraph.updateCellSize(_destArea.getPuzzleGraphCell());
}
puzzleGraph.insertEdge(puzzleGraph.getDefaultParent(), null, null, _graphCell, _destArea.getPuzzleGraphCell());
}
finally {puzzleGraph.getModel().endUpdate();}
}
if (_keyName != null) {
_keyBlock = puzzles.get(_keyName);
puzzleGraph.getModel().beginUpdate();
try { puzzleGraph.insertEdge(puzzleGraph.getDefaultParent(), null, null, _keyBlock.getGraphCell(), _graphCell);}
finally { puzzleGraph.getModel().endUpdate();}
}
this.update();
}
@Override
public PuzzleBlock[] getPuzzleInputs()
{
if (_keyBlock != null)
return new PuzzleBlock[] { _keyBlock };
return new PuzzleBlock[0];
}
@Override
public AreaBlock[] getAreaInputs()
{
if (_sourceArea != null)
return new AreaBlock[] { _sourceArea };
return new AreaBlock[0];
}
@Override
public String toXML()
{
String xml = "<DoorUnlockPuzzle name=\"" + _name + "\" ";
if (_sourceArea != null)
xml += "source=\"" + _sourceArea.getName() + "\" ";
if (_destArea != null)
xml += "dest=\"" + _destArea.getName() + "\" ";
if (_keyBlock != null)
xml += "key=\"" + _keyBlock.getName() + "\" ";
xml += "/>";
return xml;
}
}
| 32.062847 | 161 | 0.704773 |
b09a49f80fb7883597dc5b1d36bb9b0d14482b98 | 7,028 | /*
* *****************************************************************
*
* Copyright 2018 DEKRA Testing and Certification, S.A.U. All Rights Reserved.
*
* *****************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* *****************************************************************
*/
package com.mango.home.viewmodel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.mango.home.domain.model.devicelist.DeviceType;
import com.mango.home.domain.model.resource.secure.acl.OcAce;
import com.mango.home.domain.usecase.UpdateDeviceTypeUseCase;
import com.mango.home.domain.usecase.accesscontrol.DeleteAclUseCase;
import com.mango.home.domain.usecase.accesscontrol.RetrieveAclUseCase;
import com.mango.home.utils.viewmodel.ViewModelError;
import com.mango.home.utils.viewmodel.ViewModelErrorType;
import com.mango.home.utils.rx.SchedulersFacade;
import com.mango.home.domain.model.devicelist.Device;
import javax.inject.Inject;
import io.reactivex.disposables.CompositeDisposable;
public class AccessControlViewModel extends ViewModel {
private final RetrieveAclUseCase mRetrieveAclUseCase;
private final DeleteAclUseCase mDeleteAclUseCase;
private final UpdateDeviceTypeUseCase mUpdateDeviceTypeUseCase;
private final SchedulersFacade mSchedulersFacade;
private final CompositeDisposable mDisposables = new CompositeDisposable();
private final MutableLiveData<Boolean> mProcessing = new MutableLiveData<>();
private final MutableLiveData<ViewModelError> mError = new MutableLiveData<>();
private final MutableLiveData<String> mRownerUuid = new MutableLiveData<>();
private final MutableLiveData<OcAce> mAce = new MutableLiveData<>();
private final MutableLiveData<Long> mDeletedAceId = new MutableLiveData<>();
@Inject
AccessControlViewModel(
RetrieveAclUseCase retrieveAclUseCase,
DeleteAclUseCase deleteAclUseCase,
SchedulersFacade schedulersFacade,
UpdateDeviceTypeUseCase updateDeviceTypeUseCase) {
this.mRetrieveAclUseCase = retrieveAclUseCase;
this.mDeleteAclUseCase = deleteAclUseCase;
this.mUpdateDeviceTypeUseCase = updateDeviceTypeUseCase;
this.mSchedulersFacade = schedulersFacade;
}
@Override
protected void onCleared() {
mDisposables.clear();
}
public LiveData<Boolean> isProcessing() {
return mProcessing;
}
public LiveData<ViewModelError> getError() {
return mError;
}
public LiveData<String> getResourceOwner() {
return mRownerUuid;
}
public LiveData<OcAce> getAce() {
return mAce;
}
public LiveData<Long> getDeletedAceId() {
return mDeletedAceId;
}
public void retrieveAcl(Device device) {
if (device.getDeviceType() != DeviceType.CLOUD) {
mDisposables.add(mRetrieveAclUseCase.execute(device)
.subscribeOn(mSchedulersFacade.io())
.observeOn(mSchedulersFacade.ui())
.doOnSubscribe(__ -> mProcessing.setValue(true))
.doFinally(() -> mProcessing.setValue(false))
.subscribe(
acl -> {
for (OcAce ace : acl.getAceList()) {
mAce.setValue(ace);
}
// if i can see ACL, i have some permits, so i have to update the DeviceType to OWNED_BY_OTHER_WITH_PERMITS
if (!device.hasACLpermit()
&& (device.getDeviceType() == DeviceType.OWNED_BY_OTHER
|| device.getDeviceType() == DeviceType.OWNED_BY_OTHER_WITH_PERMITS)) {
mDisposables.add(mUpdateDeviceTypeUseCase.execute(device.getDeviceId(),
DeviceType.OWNED_BY_OTHER_WITH_PERMITS,
device.getPermits() | Device.ACL_PERMITS)
.subscribeOn(mSchedulersFacade.io())
.observeOn(mSchedulersFacade.ui())
.subscribe(
() -> {
},
throwable2 -> mError.setValue(new ViewModelError(Error.DB_ACCESS, null))
));
}
},
throwable -> {
mError.setValue(new ViewModelError(Error.RETRIEVE, null));
if (device.hasACLpermit()) {
mDisposables.add(mUpdateDeviceTypeUseCase.execute(device.getDeviceId(),
DeviceType.OWNED_BY_OTHER,
device.getPermits() & ~Device.ACL_PERMITS)
.subscribeOn(mSchedulersFacade.io())
.observeOn(mSchedulersFacade.ui())
.subscribe(
() -> {
},
throwable2 -> mError.setValue(new ViewModelError(Error.DB_ACCESS, null))
));
}
}
));
}
}
public void deleteAce(Device device, long aceId) {
mDisposables.add(mDeleteAclUseCase.execute(device, aceId)
.subscribeOn(mSchedulersFacade.io())
.observeOn(mSchedulersFacade.ui())
.doOnSubscribe(__ -> mProcessing.setValue(true))
.doFinally(() -> mProcessing.setValue(false))
.subscribe(
() -> mDeletedAceId.setValue(aceId),
throwable -> mError.setValue(new ViewModelError(Error.DELETE, null))
));
}
public enum Error implements ViewModelErrorType {
RETRIEVE,
DB_ACCESS,
DELETE
}
}
| 42.593939 | 139 | 0.545532 |
b8c3780afd3202992ffa238bf3c186f375889ace | 13,505 | package org.aion.txpool;
import static org.aion.txpool.TxPoolA0.MIN_ENERGY_CONSUME;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import org.aion.base.AionTransaction;
import org.aion.base.PooledTransaction;
import org.aion.base.TransactionTypes;
import org.aion.crypto.ECKey;
import org.aion.crypto.ECKeyFac;
import org.aion.types.AionAddress;
import org.aion.util.types.AddressUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.spongycastle.pqc.math.linearalgebra.ByteUtils;
public class TxnPoolBenchmarkTest {
private List<ECKey> key;
private List<ECKey> key2;
private Random r = new Random();
@Before
public void Setup() {
ECKeyFac.setType(ECKeyFac.ECKeyType.ED25519);
int keyCnt = 10;
if (key == null) {
key = new ArrayList<>();
System.out.println("gen key list----------------");
for (int i = 0; i < keyCnt; i++) {
key.add(ECKeyFac.inst().create());
}
System.out.println("gen key list finished-------");
}
if (key2 == null) {
keyCnt = 10000;
key2 = new ArrayList<>();
System.out.println("gen key list 2--------------");
for (int i = 0; i < keyCnt; i++) {
key2.add(ECKeyFac.inst().create());
}
System.out.println("gen key list 2 finished-----");
}
}
/* 100K new transactions in pool around 1200ms (cold-call)*/
@Test
public void benchmarkSnapshot() {
Properties config = new Properties();
config.put("tx-timeout", "100");
TxPoolA0 tp = new TxPoolA0(config);
List<PooledTransaction> txnl = new ArrayList<>();
int cnt = 10000;
for (ECKey aKey1 : key) {
for (int i = 0; i < cnt; i++) {
AionTransaction txn =
AionTransaction.create(
aKey1,
BigInteger.valueOf(i).toByteArray(),
AddressUtils.wrapAddress(
"0000000000000000000000000000000000000000000000000000000000000001"),
ByteUtils.fromHexString("1"),
ByteUtils.fromHexString("1"),
MIN_ENERGY_CONSUME,
1L,
TransactionTypes.DEFAULT, null);
PooledTransaction pooledTx = new PooledTransaction(txn, MIN_ENERGY_CONSUME);
txnl.add(pooledTx);
}
}
tp.add(txnl);
Assert.assertEquals(tp.size(), cnt * key.size());
// sort the inserted txs
long start = System.currentTimeMillis();
tp.snapshot();
System.out.println("time spent: " + (System.currentTimeMillis() - start) + " ms.");
for (ECKey aKey : key) {
List<BigInteger> nl = tp.getNonceList(new AionAddress(aKey.getAddress()));
for (int i = 0; i < cnt; i++) {
Assert.assertEquals(nl.get(i), BigInteger.valueOf(i));
}
}
}
@Test
/* 100K new transactions in pool around 650ms (cold-call)
1K new transactions insert to the pool later around 150ms to snap (including sort)
*/
public void benchmarkSnapshot2() {
Properties config = new Properties();
config.put("tx-timeout", "100");
TxPoolA0 tp = new TxPoolA0(config);
List<PooledTransaction> txnl = new ArrayList<>();
int cnt = 10000;
for (ECKey aKey2 : key) {
for (int i = 0; i < cnt; i++) {
AionTransaction txn =
AionTransaction.create(
aKey2,
BigInteger.valueOf(i).toByteArray(),
AddressUtils.wrapAddress(
"0000000000000000000000000000000000000000000000000000000000000001"),
ByteUtils.fromHexString("1"),
ByteUtils.fromHexString("1"),
MIN_ENERGY_CONSUME,
1L,
TransactionTypes.DEFAULT, null);
PooledTransaction pooledTx = new PooledTransaction(txn, MIN_ENERGY_CONSUME);
txnl.add(pooledTx);
}
}
tp.add(txnl);
Assert.assertEquals(tp.size(), cnt * key.size());
// sort the inserted txs
long start = System.currentTimeMillis();
tp.snapshot();
System.out.println("time spent: " + (System.currentTimeMillis() - start) + " ms.");
int cnt2 = 100;
txnl.clear();
for (ECKey aKey1 : key) {
for (int i = 0; i < cnt2; i++) {
AionTransaction txn =
AionTransaction.create(
aKey1,
BigInteger.valueOf(cnt + i).toByteArray(),
AddressUtils.wrapAddress(
"0000000000000000000000000000000000000000000000000000000000000001"),
ByteUtils.fromHexString("1"),
ByteUtils.fromHexString("1"),
MIN_ENERGY_CONSUME,
1L,
TransactionTypes.DEFAULT, null);
PooledTransaction pooledTx = new PooledTransaction(txn, MIN_ENERGY_CONSUME);
txnl.add(pooledTx);
}
}
tp.add(txnl);
Assert.assertEquals(tp.size(), (cnt + cnt2) * key.size());
start = System.currentTimeMillis();
tp.snapshot();
System.out.println("2nd time spent: " + (System.currentTimeMillis() - start) + " ms.");
for (ECKey aKey : key) {
List<BigInteger> nl = tp.getNonceList(new AionAddress(aKey.getAddress()));
for (int i = 0; i < cnt + cnt2; i++) {
Assert.assertEquals(nl.get(i), BigInteger.valueOf(i));
}
}
}
@Test
@Ignore
/* 1M new transactions with 10000 accounts (100 txs per account)in pool snapshot around 10s (cold-call)
gen new txns 55s (spent a lot of time to sign tx)
put txns into pool 2.5s
snapshot txn 5s
*/
public void benchmarkSnapshot3() {
Properties config = new Properties();
config.put("tx-timeout", "100");
TxPoolA0 tp = new TxPoolA0(config);
List<PooledTransaction> txnl = new ArrayList<>();
int cnt = 100;
System.out.println("Gen new transactions --");
long start = System.currentTimeMillis();
for (ECKey aKey21 : key2) {
for (int i = 0; i < cnt; i++) {
AionTransaction txn =
AionTransaction.create(
aKey21,
BigInteger.valueOf(i).toByteArray(),
AddressUtils.wrapAddress(
"0000000000000000000000000000000000000000000000000000000000000001"),
ByteUtils.fromHexString("1"),
ByteUtils.fromHexString("1"),
MIN_ENERGY_CONSUME,
1L,
TransactionTypes.DEFAULT, null);
PooledTransaction pooledTx = new PooledTransaction(txn, MIN_ENERGY_CONSUME);
txnl.add(pooledTx);
}
}
System.out.println("time spent: " + (System.currentTimeMillis() - start) + " ms.");
System.out.println("Adding transactions into pool--");
start = System.currentTimeMillis();
tp.add(txnl);
System.out.println("time spent: " + (System.currentTimeMillis() - start) + " ms.");
Assert.assertEquals(tp.size(), cnt * key2.size());
// sort the inserted txs
System.out.println("Snapshoting --");
start = System.currentTimeMillis();
tp.snapshot();
System.out.println("time spent: " + (System.currentTimeMillis() - start) + " ms.");
for (ECKey aKey2 : key2) {
List<BigInteger> nl = tp.getNonceList(new AionAddress(aKey2.getAddress()));
for (int i = 0; i < cnt; i++) {
Assert.assertEquals(nl.get(i), BigInteger.valueOf(i));
}
}
}
@Test
/* 100K new transactions in pool around 350ms (cold-call)
*/
public void benchmarkSnapshot4() {
Properties config = new Properties();
config.put("tx-timeout", "100");
TxPoolA0 tp = new TxPoolA0(config);
List<PooledTransaction> txnl = new ArrayList<>();
List<PooledTransaction> txnlrm = new ArrayList<>();
int cnt = 100000;
int rmCnt = 10;
System.out.println("gen new transactions...");
long start = System.currentTimeMillis();
for (int i = 0; i < cnt; i++) {
AionTransaction txn =
AionTransaction.create(
key.get(0),
BigInteger.valueOf(i).toByteArray(),
AddressUtils.wrapAddress(
"0000000000000000000000000000000000000000000000000000000000000001"),
ByteUtils.fromHexString("1"),
ByteUtils.fromHexString("1"),
MIN_ENERGY_CONSUME,
1L,
TransactionTypes.DEFAULT, null);
PooledTransaction pooledTx = new PooledTransaction(txn, MIN_ENERGY_CONSUME);
txnl.add(pooledTx);
if (i < rmCnt) {
txnlrm.add(pooledTx);
}
}
System.out.println("time spent: " + (System.currentTimeMillis() - start) + " ms.");
System.out.println("Inserting txns...");
start = System.currentTimeMillis();
tp.add(txnl);
System.out.println("time spent: " + (System.currentTimeMillis() - start) + " ms.");
Assert.assertEquals(tp.size(), cnt);
// sort the inserted txs
System.out.println("Snapshoting...");
start = System.currentTimeMillis();
tp.snapshot();
System.out.println("time spent: " + (System.currentTimeMillis() - start) + " ms.");
System.out.println("Removing the first 10 txns...");
start = System.currentTimeMillis();
List rm = tp.remove(txnlrm);
System.out.println("time spent: " + (System.currentTimeMillis() - start) + " ms.");
Assert.assertEquals(rm.size(), rmCnt);
Assert.assertEquals(tp.size(), cnt - rmCnt);
System.out.println("Re-Snapshot after some txns was been removed...");
start = System.currentTimeMillis();
tp.snapshot();
System.out.println("time spent: " + (System.currentTimeMillis() - start) + " ms.");
List<BigInteger> nl = tp.getNonceList(new AionAddress(key.get(0).getAddress()));
for (int i = 0; i < nl.size(); i++) {
Assert.assertEquals(nl.get(i), BigInteger.valueOf(i).add(BigInteger.valueOf(rmCnt)));
}
}
@Test
/* 100K new transactions in pool around 350ms (cold-call)
the second time snapshot is around 35ms
*/
public void benchmarkSnapshot5() {
Properties config = new Properties();
config.put("tx-timeout", "100");
TxPoolA0 tp = new TxPoolA0(config);
List<PooledTransaction> txnl = new ArrayList<>();
int cnt = 10000;
for (ECKey aKey1 : key) {
for (int i = 0; i < cnt; i++) {
AionTransaction txn =
AionTransaction.create(
aKey1,
BigInteger.valueOf(i).toByteArray(),
AddressUtils.wrapAddress(
"0000000000000000000000000000000000000000000000000000000000000001"),
ByteUtils.fromHexString("1"),
ByteUtils.fromHexString("1"),
MIN_ENERGY_CONSUME,
1L,
TransactionTypes.DEFAULT, null);
PooledTransaction pooledTx = new PooledTransaction(txn, MIN_ENERGY_CONSUME);
txnl.add(pooledTx);
}
}
tp.add(txnl);
Assert.assertEquals(tp.size(), cnt * key.size());
// sort the inserted txs
System.out.println("1st time snapshot...");
long start = System.currentTimeMillis();
tp.snapshot();
System.out.println("1st time spent: " + (System.currentTimeMillis() - start) + " ms.");
System.out.println("2nd time snapshot...");
start = System.currentTimeMillis();
tp.snapshot();
System.out.println("2nd time spent: " + (System.currentTimeMillis() - start) + " ms.");
for (ECKey aKey : key) {
List<BigInteger> nl = tp.getNonceList(new AionAddress(aKey.getAddress()));
for (int i = 0; i < cnt; i++) {
Assert.assertEquals(nl.get(i), BigInteger.valueOf(i));
}
}
}
}
| 38.919308 | 108 | 0.522103 |
e9806101f6a637ad4db48f1558d5f21c11c87b75 | 662 | package com.project.wanderlust.DataClasses;
import android.graphics.Bitmap;
public class Contact {
private Bitmap photo;
private String name;
private String phone;
public Contact(Bitmap photo, String name, String phone) {
this.photo = photo;
this.name = name;
this.phone = phone;
}
public Bitmap getPhoto() { return photo; }
public String getName() { return name; }
public String getPhone() { return phone; }
public void setPhoto(Bitmap photo) { this.photo = photo; }
public void setName(String name) { this.name = name; }
public void setPhone(String phone) { this.phone = phone; }
}
| 22.827586 | 62 | 0.660121 |
86c7208f9b06b9cf5c3ba6252b88bb362dd2a0df | 2,402 | /*
Copyright (c) 2022 Preponderous Software
MIT License
*/
package preponderous.ponder.minecraft.bukkit.services;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import preponderous.ponder.minecraft.bukkit.abs.AbstractPluginCommand;
import preponderous.ponder.minecraft.bukkit.tools.PermissionChecker;
import preponderous.ponder.minecraft.bukkit.PonderMC;
import preponderous.ponder.misc.ArgumentParser;
import java.util.ArrayList;
import java.util.Set;
/**
* @author Daniel McCoy Stephenson
*/
public class CommandService {
private ArrayList<AbstractPluginCommand> commands = new ArrayList<>();
private final Set<String> coreCommands;
private String notFoundMessage;
private final ArgumentParser parser = new ArgumentParser();
private final PermissionChecker permissionChecker = new PermissionChecker();
public CommandService(@NotNull Set<String> coreCommands) {
this.coreCommands = coreCommands;
}
public CommandService(@NotNull JavaPlugin plugin) {
this(plugin.getDescription().getCommands().keySet());
}
public CommandService(@NotNull PonderMC ponder) {
this(ponder.getPlugin());
}
public void initialize(ArrayList<AbstractPluginCommand> commands, String notFoundMessage) {
this.commands = commands;
this.notFoundMessage = notFoundMessage;
}
public boolean interpretAndExecuteCommand(CommandSender sender, String label, String[] args) {
if (!coreCommands.contains(label)) {
return false;
}
if (args.length == 0) {
return false;
}
String subCommand = args[0];
String[] arguments = parser.dropFirstArgument(args);
for (AbstractPluginCommand command : commands) {
if (command.getNames().contains(subCommand)) {
if (!permissionChecker.checkPermission(sender, command.getPermissions())) {
return false;
}
if (arguments.length == 0) {
return command.execute(sender);
}
else {
return command.execute(sender, arguments);
}
}
}
sender.sendMessage(ChatColor.RED + notFoundMessage);
return false;
}
} | 32.026667 | 98 | 0.666528 |
09cf58b6f04b3fe42f6c8cf3c5ce92d9800e0091 | 169 | /**
* Package for ru.job4j.multithreading.monitor task.
*
* @author Vladimir Ivanov
* @version 0.1
* @since 28.11.2017
*/
package ru.job4j.multithreading.monitor; | 18.777778 | 52 | 0.704142 |
7170b188cff5595ca2516154e3bf510214e7a7cc | 513 | import java.io.StreamTokenizer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
int n, a, f = 0;
st.nextToken();
n = (int) st.nval;
n = 2 * n - 1;
while (n-- > 0) {
st.nextToken();
a = (int) st.nval;
f ^= a;
}
System.out.print(f);
}
}
| 22.304348 | 99 | 0.631579 |
fa84f4d7aa9b746bccdf0d5a819fe630aa77db02 | 2,609 | package pl.droidsonroids.examplerealmmvp.ui.books;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.realm.RealmResults;
import javax.inject.Inject;
import pl.droidsonroids.examplerealmmvp.R;
import pl.droidsonroids.examplerealmmvp.model.Book;
import pl.droidsonroids.examplerealmmvp.ui.BaseActivity;
import pl.droidsonroids.examplerealmmvp.ui.adapter.BookListAdapter;
import pl.droidsonroids.examplerealmmvp.ui.add.AddBookActivity;
import pl.droidsonroids.examplerealmmvp.ui.detail.DetailActivity;
public class BooksActivity extends BaseActivity implements BooksView, BookListAdapter.OnBookClickListener {
@Bind(R.id.recycler_view) RecyclerView mRecyclerView;
@Bind(R.id.toolbar) Toolbar mToolbar;
@Inject BooksPresenter mBooksPresenter;
private BookListAdapter mAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
initToolbar();
initList();
}
@Override
protected Object getModule() {
return new BooksModule();
}
private void initToolbar() {
setSupportActionBar(mToolbar);
}
private void initList() {
mAdapter = new BookListAdapter();
mAdapter.setOnBookClickListener(this);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mAdapter);
}
@Override
protected void onStart() {
super.onStart();
mBooksPresenter.setView(this);
}
@Override
protected void onStop() {
super.onStop();
mBooksPresenter.clearView();
}
@Override
protected void closeRealm() {
mBooksPresenter.closeRealm();
}
@Override
public void showBooks(final RealmResults<Book> books) {
mAdapter.setBooks(books);
}
@Override
public void onBookClick(final int id) {
mBooksPresenter.onBookClick(id);
}
@OnClick(R.id.fab)
public void onAddNewBookClick() {
mBooksPresenter.onAddNewBookClick();
}
@Override
public void showBookDetailView(final int id) {
startActivity(DetailActivity.getStartIntent(this, id));
}
@Override
public void showAddNewBookView() {
startActivity(new Intent(this, AddBookActivity.class));
}
}
| 26.896907 | 107 | 0.715217 |
6cfc237cf8a40fb31ab1c4d697873b7ccfe068f8 | 2,068 | package org.apache.spark.sql.execution.command;
/**
* A command used to write the result of a query to a directory.
* <p>
* The syntax of using this command in SQL is:
* <pre><code>
* INSERT OVERWRITE DIRECTORY (path=STRING)?
* USING format OPTIONS ([option1_name "option1_value", option2_name "option2_value", ...])
* SELECT ...
* </code></pre>
* <p>
* param: storage storage format used to describe how the query result is stored.
* param: provider the data source type to be used
* param: query the logical plan representing data to write to
* param: overwrite whthere overwrites existing directory
*/
public class InsertIntoDataSourceDirCommand extends org.apache.spark.sql.catalyst.plans.logical.LogicalPlan implements org.apache.spark.sql.execution.command.RunnableCommand, scala.Product, scala.Serializable {
static public abstract R apply (T1 v1, T2 v2, T3 v3, T4 v4) ;
static public java.lang.String toString () { throw new RuntimeException(); }
public scala.collection.immutable.Map<java.lang.String, org.apache.spark.sql.execution.metric.SQLMetric> metrics () { throw new RuntimeException(); }
public org.apache.spark.sql.catalyst.catalog.CatalogStorageFormat storage () { throw new RuntimeException(); }
public java.lang.String provider () { throw new RuntimeException(); }
public org.apache.spark.sql.catalyst.plans.logical.LogicalPlan query () { throw new RuntimeException(); }
public boolean overwrite () { throw new RuntimeException(); }
// not preceding
public InsertIntoDataSourceDirCommand (org.apache.spark.sql.catalyst.catalog.CatalogStorageFormat storage, java.lang.String provider, org.apache.spark.sql.catalyst.plans.logical.LogicalPlan query, boolean overwrite) { throw new RuntimeException(); }
public scala.collection.Seq<org.apache.spark.sql.catalyst.plans.logical.LogicalPlan> innerChildren () { throw new RuntimeException(); }
public scala.collection.Seq<org.apache.spark.sql.Row> run (org.apache.spark.sql.SparkSession sparkSession) { throw new RuntimeException(); }
}
| 68.933333 | 254 | 0.754352 |
4b1172016b94ed53f62da988e648ee2042710917 | 202 |
public class TestForInnerClass2 {
public Destination destination(final String dest) {
return new Destination() {
private String label =dest;
public String readLabel() {
return label;
}
};
}
}
| 14.428571 | 51 | 0.722772 |
d50625328f077362dc0d998f94dbd639f69775a1 | 339 | package g191210385;
import java.sql.SQLException;
public class KritikSogutma implements IObserver{
@Override
public int kritikDurum(int kritikSicaklik,String roomId, IEyleyici eyleyici) throws InterruptedException, SQLException {
Thread.sleep(500);
return eyleyici.sogutucuAc(kritikSicaklik, roomId);
}
}
| 22.6 | 122 | 0.752212 |
1858f6b48b110442201860cdbe2a57ec8180d52e | 1,033 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.indexing;
import com.intellij.util.io.DataExternalizer;
import com.intellij.util.io.VoidDataExternalizer;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
/**
* A specialization of FileBasedIndexExtension allowing to create a mapping {@code [DataObject -> List of files containing this object]}.
*/
@ApiStatus.OverrideOnly
public abstract class ScalarIndexExtension<K> extends FileBasedIndexExtension<K, Void> {
/**
* To remove in IDEA 2018.1.
*
* @deprecated use {@link VoidDataExternalizer#INSTANCE}
*/
@ApiStatus.ScheduledForRemoval(inVersion = "2021.1")
@Deprecated
public static final DataExternalizer<Void> VOID_DATA_EXTERNALIZER = VoidDataExternalizer.INSTANCE;
@NotNull
@Override
public final DataExternalizer<Void> getValueExternalizer() {
return VoidDataExternalizer.INSTANCE;
}
} | 34.433333 | 140 | 0.776379 |
80bd5da2e1ea7d7848d2d0218924bfdd01367ee5 | 8,505 | package com.mathgame.activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.TextView;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LegendEntry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.mathgame.R;
import com.mathgame.appdata.Constant;
import com.mathgame.appdata.Dependencies;
import com.mathgame.model.GameResult;
import com.mathgame.model.Question;
import com.mathgame.structure.BaseActivity;
import com.mathgame.util.Transition;
import com.mathgame.util.Utils;
import java.util.ArrayList;
import java.util.List;
import static com.github.mikephil.charting.utils.ColorTemplate.rgb;
public class DualGameResultActivity extends BaseActivity implements View.OnClickListener {
private int[] MATERIAL_COLORS = {rgb("#e666d02a"), rgb("#e6e2574c"), rgb("#4D000000")};
private PieChart playerOneChart, playerTwoChart;
private GameResult playerOneResult, playerTwoResult;
private TextView tvResultFeedback, tvPlayer1, tvPlayer2;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
setData();
}
@Override
public String getToolbarTitle() {
return getString(R.string.analytics);
}
@Override
public int getContentView() {
return R.layout.activity_dual_game_result;
}
private void init() {
tvResultFeedback = findViewById(R.id.tvResultFeedback);
playerOneChart = findViewById(R.id.playerOneChart);
playerTwoChart = findViewById(R.id.playerTwoChart);
tvPlayer1 = findViewById(R.id.tvPlayer1);
tvPlayer2 = findViewById(R.id.tvPlayer2);
TextView tvSeeAllQuestions = findViewById(R.id.tvSeeAllQuestions);
Utils.setOnClickListener(this, tvSeeAllQuestions);
}
private void setData() {
playerOneResult = Dependencies.getSinglePlayerResult(this);
playerTwoResult = Dependencies.getSecondPlayerResult(this);
int playerOneCorrect = 0, playerTwoCorrect = 0;
if (playerOneResult != null) {
ArrayList<Question> questionList = playerOneResult.getQuestionList();
int incorrect = 0, unattempted = 0;
for (Question question : questionList) {
if (question.getAnswerType() == Constant.AnswerType.CORRECT) {
playerOneCorrect++;
} else if (question.getAnswerType() == Constant.AnswerType.INCORRECT) {
incorrect++;
} else {
unattempted++;
}
}
List<PieEntry> noOfEmp = new ArrayList<>();
if (playerOneCorrect > 0) {
noOfEmp.add(new PieEntry(playerOneCorrect, 0));
}
if (incorrect > 0) {
noOfEmp.add(new PieEntry(incorrect, 1));
}
if (unattempted > 0) {
noOfEmp.add(new PieEntry(unattempted, 2));
}
PieDataSet dataSet = new PieDataSet(noOfEmp, getString(R.string.question_result));
dataSet.setValueTextSize(20f);
dataSet.setValueTextColor(ContextCompat.getColor(this, R.color.white));
PieData data = new PieData(dataSet);
LegendEntry l1 = new LegendEntry(getString(R.string.correct), Legend.LegendForm.SQUARE, 10f, 2f, null, MATERIAL_COLORS[0]);
LegendEntry l2 = new LegendEntry(getString(R.string.incorrect), Legend.LegendForm.SQUARE, 10f, 2f, null, MATERIAL_COLORS[1]);
LegendEntry l3 = new LegendEntry(getString(R.string.unattempted), Legend.LegendForm.SQUARE, 10f, 2f, null, MATERIAL_COLORS[2]);
playerOneChart.getLegend().setCustom(new LegendEntry[]{l1, l2, l3});
playerOneChart.getLegend().setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
playerOneChart.getLegend().setTextColor(ContextCompat.getColor(this, R.color.white));
playerOneChart.getDescription().setEnabled(false);
playerOneChart.getLegend().setTextSize(13f);
playerOneChart.getLegend().setFormToTextSpace(5f);
playerOneChart.setData(data);
dataSet.setColors(MATERIAL_COLORS);
playerOneChart.animateXY(1000, 1000);
}
if (playerTwoResult != null) {
ArrayList<Question> questionList = playerTwoResult.getQuestionList();
int incorrect = 0, unattempted = 0;
for (Question question : questionList) {
if (question.getAnswerType() == Constant.AnswerType.CORRECT) {
playerTwoCorrect++;
} else if (question.getAnswerType() == Constant.AnswerType.INCORRECT) {
incorrect++;
} else {
unattempted++;
}
}
List<PieEntry> noOfEmp = new ArrayList<>();
if (playerTwoCorrect > 0) {
noOfEmp.add(new PieEntry(playerTwoCorrect, 0));
}
if (incorrect > 0) {
noOfEmp.add(new PieEntry(incorrect, 1));
}
if (unattempted > 0) {
noOfEmp.add(new PieEntry(unattempted, 2));
}
PieDataSet dataSet = new PieDataSet(noOfEmp, getString(R.string.question_result));
dataSet.setValueTextSize(20f);
dataSet.setValueTextColor(ContextCompat.getColor(this, R.color.white));
PieData data = new PieData(dataSet);
LegendEntry l1 = new LegendEntry(getString(R.string.correct), Legend.LegendForm.SQUARE, 10f, 2f, null, MATERIAL_COLORS[0]);
LegendEntry l2 = new LegendEntry(getString(R.string.incorrect), Legend.LegendForm.SQUARE, 10f, 2f, null, MATERIAL_COLORS[1]);
LegendEntry l3 = new LegendEntry(getString(R.string.unattempted), Legend.LegendForm.SQUARE, 10f, 2f, null, MATERIAL_COLORS[2]);
playerTwoChart.getLegend().setCustom(new LegendEntry[]{l1, l2, l3});
playerTwoChart.getLegend().setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
playerTwoChart.getLegend().setTextColor(ContextCompat.getColor(this, R.color.white));
playerTwoChart.getDescription().setEnabled(false);
playerTwoChart.getLegend().setTextSize(13f);
playerTwoChart.getLegend().setFormToTextSpace(5f);
playerTwoChart.setData(data);
dataSet.setColors(MATERIAL_COLORS);
playerTwoChart.animateXY(1000, 1000);
}
if (playerOneCorrect > playerTwoCorrect) {
tvResultFeedback.setText(R.string.player_1_wins);
tvPlayer1.setCompoundDrawablesWithIntrinsicBounds(null, ContextCompat.getDrawable(this, R.drawable.ic_winner), null, null);
tvPlayer2.setCompoundDrawablesWithIntrinsicBounds(null, ContextCompat.getDrawable(this, R.drawable.ic_loser), null, null);
} else if (playerOneCorrect < playerTwoCorrect) {
tvResultFeedback.setText(R.string.player_2_wins);
tvPlayer2.setCompoundDrawablesWithIntrinsicBounds(null, ContextCompat.getDrawable(this, R.drawable.ic_winner), null, null);
tvPlayer1.setCompoundDrawablesWithIntrinsicBounds(null, ContextCompat.getDrawable(this, R.drawable.ic_loser), null, null);
} else {
tvResultFeedback.setText(R.string.its_a_draw);
tvPlayer2.setCompoundDrawablesWithIntrinsicBounds(null, ContextCompat.getDrawable(this, R.drawable.ic_winner), null, null);
tvPlayer1.setCompoundDrawablesWithIntrinsicBounds(null, ContextCompat.getDrawable(this, R.drawable.ic_winner), null, null);
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tvSeeAllQuestions:
Bundle bundle = new Bundle();
ArrayList<Question> questionList = playerOneResult.getQuestionList();
questionList.addAll(playerTwoResult.getQuestionList());
bundle.putParcelableArrayList(Question.class.getName(), questionList);
Transition.transit(this, AnswerListActivity.class, bundle);
break;
}
}
}
| 48.050847 | 139 | 0.661493 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.