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
|
|---|---|---|---|---|---|
d078de490ba219895ed7d0740352483334cba2f5
| 1,495
|
package com.robotoworks.example.ghissues.net;
import com.robotoworks.mechanoid.net.Parser;
import java.io.IOException;
import com.robotoworks.mechanoid.net.Response;
import com.robotoworks.mechanoid.net.ServiceException;
import java.io.InputStream;
import com.robotoworks.mechanoid.net.ServiceClient;
import com.robotoworks.mechanoid.net.JsonEntityWriterProvider;
import com.robotoworks.mechanoid.net.JsonEntityReaderProvider;
public abstract class AbstractGithubClient extends ServiceClient {
private static final String LOG_TAG = "GithubClient";
protected static final String DEFAULT_BASE_URL = "https://api.github.com";
@Override
protected String getLogTag() {
return LOG_TAG;
}
@Override
protected JsonEntityWriterProvider createWriterProvider() {
return new DefaultGithubClientWriterProvider();
}
@Override
protected JsonEntityReaderProvider createReaderProvider() {
return new DefaultGithubClientReaderProvider();
}
public AbstractGithubClient(String baseUrl, boolean debug){
super(baseUrl, debug);
}
public Response<GetIssuesForRepositoryResult> getIssuesForRepository(GetIssuesForRepositoryRequest request)
throws ServiceException {
Parser<GetIssuesForRepositoryResult> parser = new Parser<GetIssuesForRepositoryResult>() {
public GetIssuesForRepositoryResult parse(InputStream inStream) throws IOException {
return new GetIssuesForRepositoryResult(getReaderProvider(), inStream);
}
};
return get(request, parser);
}
}
| 29.313725
| 108
| 0.806689
|
9867c7b692811b9e4c7da7a01fd893dde4bd5e0d
| 3,786
|
/*
* Copyright 2016 nathan.
*
* 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 tools;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import start.AppProperties;
import start.Start;
import API.Layer;
import com.googlecode.javacv.FFmpegFrameRecorder;
import com.googlecode.javacv.FrameRecorder.Exception;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
public class RendererTool{
public static void renderShot () {
int w = Start.getMainWindow().getCameraWidth();
int h = Start.getMainWindow().getCameraHeight();
BufferedImage render = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
for (Layer layer : Start.getMainWindow().getLayers())
if (layer.doRenderOutside())
layer.render(render, 0, 0, w, h, 1);
try {
ImageIO.write(render, "png", new File(AppProperties.getRenderOutputPath() + "frame-" + TimeLine.getTime() + ".png"));
} catch (IOException e) {
System.err.println("Wow ! what have you done ? the image can't be written :/");
}
System.out.println("image shot ("+TimeLine.getTime()+")" + " at path :" + AppProperties.getRenderOutputPath());
}
public static void renderVideo () {
new RendererTool().new Renderer().start();
}
class Renderer extends Thread {
public void run () {
int w = Start.getMainWindow().getCameraWidth();
int h = Start.getMainWindow().getCameraHeight();
CommandFrame printer = new CommandFrame();
printer.activate();
printer.print("rendering will be starting in a instant");
System.out.println("trying to render in :" + AppProperties.getRenderOutputPath() + "film.mp4");
FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(AppProperties.getRenderOutputPath() + "film.mp4", Start.getMainWindow().getCameraWidth(), Start.getMainWindow().getCameraHeight());
Start.getMainWindow().secureRedrawerStop();
try {
recorder.setFrameRate(24);
recorder.setPixelFormat(0);
recorder.setVideoCodec(28);
System.out.println("recording will start soon, info :" + Start.getMainWindow().getCameraWidth() + ":" + Start.getMainWindow().getCameraHeight());
recorder.start();
IplImage img = new IplImage();
TimeLine.setTime(0);
BufferedImage render;
printer.print("rendering start, Start.getMainWindow() is hibernating");
printer.print("****************************");
for (int i = 0; i<PropertiesWindow.getEndVideo();i++) {
render = new BufferedImage(w,h,BufferedImage.TYPE_3BYTE_BGR);
for (Layer layer : Start.getMainWindow().getLayers())
if (layer.doRenderOutside())
layer.render(render, 0, 0, w, h, 1);
img = IplImage.createFrom(render);
recorder.record(img);
System.out.println("recording images :"+i);
TimeLine.addTime(1);
TimeLine.calculateItemsState();
printer.print("frame " + TimeLine.getTime() + "/" + PropertiesWindow.getEndVideo());
}
printer.print("****************************");
recorder.stop();
printer.print("rendering stoped");
printer.print("done :)");
} catch (Exception e) {
System.err.println("exception catched" + e.getMessage());
}
System.out.println("video done");
Start.getMainWindow().secureRedrawRestart();
}
}
}
| 36.057143
| 189
| 0.690967
|
af8f1d24824f6e8da88c8986ab14a0197a104050
| 427
|
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package noppes.npcs.client.gui.custom.interfaces;
import net.minecraft.client.Minecraft;
import noppes.npcs.scripted.interfaces.ICustomGuiComponent;
public interface IGuiComponent {
int getID();
void onRender(Minecraft var1, int var2, int var3, int var4, float var5);
ICustomGuiComponent toComponent();
}
| 23.722222
| 76
| 0.761124
|
24c231ffb360869e34072bb867f2c930e5b7c81e
| 281
|
package org.apache.spark.deploy.worker;
// no position
/**
* Utility object for launching driver programs such that they share fate with the Worker process.
*/
public class DriverWrapper {
static public void main (java.lang.String[] args) { throw new RuntimeException(); }
}
| 31.222222
| 98
| 0.743772
|
427cad289161a5fca3b3c4a6419b56fa9e0f44ea
| 4,792
|
package io.particle.android.sdk.utils.ui;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.Dialog;
import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
public class Ui {
@SuppressWarnings("unchecked")
public static <T extends View> T findView(FragmentActivity activity, int id) {
return (T) activity.findViewById(id);
}
@SuppressWarnings("unchecked")
public static <T extends View> T findView(View enclosingView, int id) {
return (T) enclosingView.findViewById(id);
}
@SuppressWarnings("unchecked")
public static <T extends View> T findView(Fragment frag, int id) {
return (T) frag.getActivity().findViewById(id);
}
@SuppressWarnings("unchecked")
public static <T extends View> T findView(Dialog dialog, int id) {
return (T) dialog.findViewById(id);
}
@SuppressWarnings("unchecked")
public static <T extends Fragment> T findFrag(FragmentActivity activity, int id) {
return (T) activity.getSupportFragmentManager().findFragmentById(id);
}
@SuppressWarnings("unchecked")
public static <T extends Fragment> T findFrag(FragmentActivity activity, String tag) {
return (T) activity.getSupportFragmentManager().findFragmentByTag(tag);
}
public static TextView setText(FragmentActivity activity, int textViewId, CharSequence text) {
TextView textView = findView(activity, textViewId);
textView.setText(text);
return textView;
}
public static TextView setText(View view, int textViewId, CharSequence text) {
TextView textView = findView(view, textViewId);
textView.setText(text);
return textView;
}
public static TextView setText(Fragment frag, int textViewId, CharSequence text) {
TextView textView = findView(frag, textViewId);
textView.setText(text);
return textView;
}
public static String getText(FragmentActivity activity, int textViewId, boolean trim) {
TextView textView = findView(activity, textViewId);
String text = textView.getText().toString();
return trim ? text.trim() : text;
}
public static String getText(Fragment frag, int textViewId, boolean trim) {
TextView textView = findView(frag, textViewId);
String text = textView.getText().toString();
return trim ? text.trim() : text;
}
public static TextView setTextFromHtml(FragmentActivity activity, int textViewId, int htmlStringId) {
return setTextFromHtml(activity, textViewId, activity.getString(htmlStringId));
}
public static TextView setTextFromHtml(FragmentActivity activity, int textViewId, String htmlString) {
TextView tv = Ui.findView(activity, textViewId);
tv.setText(Html.fromHtml(htmlString), TextView.BufferType.SPANNABLE);
return tv;
}
public static void fadeViewVisibility(FragmentActivity activity, int viewId, final boolean show) {
// Fade-in the progress spinner.
int shortAnimTime = activity.getResources().getInteger(
android.R.integer.config_shortAnimTime);
final View progressView = Ui.findView(activity, viewId);
progressView.setVisibility(View.VISIBLE);
progressView.animate()
.setDuration(shortAnimTime)
.alpha(show ? 1 : 0)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
progressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
}
// Technique taken from:
// http://blog.danlew.net/2014/08/18/fast-android-asset-theming-with-colorfilter/
public static Drawable getTintedDrawable(Context ctx, @DrawableRes int drawableResId,
@ColorRes int colorResId) {
Drawable drawable = ContextCompat.getDrawable(ctx, drawableResId);
int color = ContextCompat.getColor(ctx, colorResId);
drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
return drawable;
}
public static void setDrawable(FragmentActivity activity, int imageViewID, @DrawableRes int drawableID) {
((ImageView) findView(activity, imageViewID)).setImageResource(drawableID);
}
}
| 38.031746
| 109
| 0.689691
|
c7fdaf21a006efdc8321ad0c6fd02bc9bc29f28a
| 3,886
|
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.streamnative.pulsar.handlers.kop;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import lombok.Cleanup;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.PartitionInfo;
import org.apache.pulsar.client.admin.PulsarAdminException;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* Test unit for non-partitioned topic.
*/
public class KafkaNonPartitionedTopicTest extends KopProtocolHandlerTestBase {
private static final String TENANT = "KafkaNonPartitionedTopicTest";
private static final String NAMESPACE = "ns1";
@BeforeClass
@Override
protected void setup() throws Exception {
super.resetConfig();
conf.setKafkaTenant(TENANT);
conf.setKafkaNamespace(NAMESPACE);
conf.setKafkaMetadataTenant("internal");
conf.setKafkaMetadataNamespace("__kafka");
conf.setEnableTransactionCoordinator(true);
conf.setClusterName(super.configClusterName);
super.internalSetup();
}
@AfterClass
@Override
protected void cleanup() throws Exception {
super.internalCleanup();
}
@Test(timeOut = 30000)
public void testNonPartitionedTopic() throws PulsarAdminException {
String topic = "persistent://" + TENANT + "/" + NAMESPACE + "/" + "testNonPartitionedTopic";
admin.topics().createNonPartitionedTopic(topic);
try {
@Cleanup
KProducer kProducer = new KProducer(topic, false, getKafkaBrokerPort());
int totalMsgs = 50;
String messageStrPrefix = topic + "_message_";
for (int i = 0; i < totalMsgs; i++) {
String messageStr = messageStrPrefix + i;
kProducer.getProducer().send(new ProducerRecord<>(topic, i, messageStr));
}
@Cleanup
KConsumer kConsumer = new KConsumer(topic, getKafkaBrokerPort(), "DemoKafkaOnPulsarConsumer");
kConsumer.getConsumer().subscribe(Collections.singleton(topic));
int i = 0;
while (i < totalMsgs) {
ConsumerRecords<Integer, String> records = kConsumer.getConsumer().poll(Duration.ofSeconds(1));
for (ConsumerRecord<Integer, String> record : records) {
Integer key = record.key();
assertEquals(messageStrPrefix + key.toString(), record.value());
i++;
}
}
assertEquals(i, totalMsgs);
// No more records
ConsumerRecords<Integer, String> records = kConsumer.getConsumer().poll(Duration.ofMillis(200));
assertTrue(records.isEmpty());
// Ensure that we can list the topic
Map<String, List<PartitionInfo>> result = kConsumer
.getConsumer().listTopics(Duration.ofSeconds(1));
assertEquals(result.size(), 1);
} finally {
admin.topics().delete(topic);
}
}
}
| 35.651376
| 111
| 0.663407
|
c2c3a8f0a35fe5e668a19a2f3f0aed6d7bd8f060
| 932
|
/*
* @(#)DrawerPanel.java 2.1 2003/10/07
*
* Copyright (C) 1999, 2003 D.A. Watt and D.F. Brown
* Dept. of Computing Science, University of Glasgow, Glasgow G12 8QQ Scotland
* and School of Computer and Math Sciences, The Robert Gordon University,
* St. Andrew Street, Aberdeen AB25 1HG, Scotland.
* All rights reserved.
*
* This software is provided free for educational use only. It may
* not be used for commercial purposes without the prior written permission
* of the authors.
*/
package Triangle.TreeDrawer;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JPanel;
class DrawerPanel extends JPanel {
private Drawer drawer;
public DrawerPanel(Drawer drawer) {
setPreferredSize(new Dimension(4096, 4096));
this.drawer = drawer;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
drawer.paintAST(g);
}
}
| 27.411765
| 79
| 0.694206
|
5588c3e623a1dc39628351d8a5fb5001812839d0
| 367
|
class Test {
interface I { Object invoke(); }
interface IStr { String foo(); }
private static void call(IStr str) {
System.out.println(str);
}
private static void <warning descr="Private method 'call(Test.I)' is never used">call</warning>(I i) {
System.out.println(i);
}
public static void main(String[] args) {
call(()-> null);
}
}
| 22.9375
| 104
| 0.626703
|
0070caa8d3c35ec81e1a0139c812573762a76a48
| 3,966
|
package henryrichard.epicwasteoftime.item.weapon;
import com.google.common.collect.Multimap;
import henryrichard.epicwasteoftime.EwotMain;
import henryrichard.epicwasteoftime.item.EwotItemTier;
import net.minecraft.block.BlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.EquipmentSlotType;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Rarity;
import net.minecraft.item.SwordItem;
import net.minecraft.item.TieredItem;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraft.world.World;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import javax.annotation.Nullable;
import java.util.List;
public class ZwammahItem extends TieredItem {
private final float attackDamage = 13;
private final float attackSpeed = -3.5f;
public ZwammahItem(Properties builder) {
super(EwotItemTier.ZWAMMAH, builder);
}
@Override
public Rarity getRarity(ItemStack stack) {
return Rarity.EPIC;
}
@OnlyIn(Dist.CLIENT)
@Override
public void addInformation(ItemStack stack, @Nullable World worldIn, List<ITextComponent> tooltip, ITooltipFlag flagIn) {
for(int i = 1; i <= 4; i++) {
tooltip.add(new TranslationTextComponent(this.getTranslationKey() + ".desc." + i));
}
String worldName;
if(Minecraft.getInstance().isSingleplayer()) {
worldName = Minecraft.getInstance().getIntegratedServer().getWorldName();
} else {
worldName = "Minecraft";
}
if(Minecraft.getInstance().isSingleplayer()) {
tooltip.add(new TranslationTextComponent(this.getTranslationKey() + ".desc.5", Minecraft.getInstance().getIntegratedServer().getWorldName()));
}
}
@Override
public boolean canPlayerBreakBlockWhileHolding(BlockState state, World worldIn, BlockPos pos, PlayerEntity player) {
return !player.isCreative();
}
/**
* Gets a map of item attribute modifiers, used by ItemSword to increase hit damage.
*/
@Override
public Multimap<String, AttributeModifier> getAttributeModifiers(EquipmentSlotType equipmentSlot, ItemStack stack) {
Multimap<String, AttributeModifier> multimap = super.getAttributeModifiers(equipmentSlot, stack);
if (equipmentSlot == EquipmentSlotType.MAINHAND) {
multimap.put(SharedMonsterAttributes.ATTACK_DAMAGE.getName(), new AttributeModifier(ATTACK_DAMAGE_MODIFIER, "Weapon modifier", (double)this.attackDamage, AttributeModifier.Operation.ADDITION));
multimap.put(SharedMonsterAttributes.ATTACK_SPEED.getName(), new AttributeModifier(ATTACK_SPEED_MODIFIER, "Weapon modifier", (double)this.attackSpeed, AttributeModifier.Operation.ADDITION));
}
return multimap;
}
@Override
public boolean hitEntity(ItemStack stack, LivingEntity target, LivingEntity attacker) {
stack.damageItem(1, attacker, (holder) -> {
holder.sendBreakAnimation(EquipmentSlotType.MAINHAND);
});
return true;
}
/**
* Called when a Block is destroyed using this Item. Return true to trigger the "Use Item" statistic.
*/
@Override
public boolean onBlockDestroyed(ItemStack stack, World worldIn, BlockState state, BlockPos pos, LivingEntity entityLiving) {
if (state.getBlockHardness(worldIn, pos) != 0.0F) {
stack.damageItem(2, entityLiving, (holder) -> {
holder.sendBreakAnimation(EquipmentSlotType.MAINHAND);
});
}
return true;
}
}
| 39.267327
| 205
| 0.723903
|
0da6ce202842200bf22d752b25426aab690c8c62
| 3,646
|
package com.yourname.re.pre_defined;
import com.yourname.re.PreliminaryData;
import org.junit.Test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Created by Charles on 10/3/2016.
*/
public class PredefinedTest
{
@Test
public void testPredefinedDigits()
{
try
{
Pattern digitPattern = Pattern.compile("\\d"); // note 2 back slash characters; due to Java escape character
Matcher digitMatcher = digitPattern.matcher(PreliminaryData.oldSong);
boolean findFlag = digitMatcher.find();
assertTrue (findFlag);
if (findFlag)
{
String groupString = digitMatcher.group();
int startPosition = digitMatcher.start();
int endPosition = digitMatcher.end();
String tempString = String.format
(
"found the text" + " \"%s\" starting at " + "index %d and ending at index %d.%n",
groupString,
startPosition,
endPosition
);
System.out.println(tempString);
}
}
catch (Exception e)
{
fail(e.toString() );
}
}
@Test
public void testWord()
{
try
{
Pattern whiteSpacePattern = Pattern.compile("\\w");
Matcher whiteSpaceMatcher = whiteSpacePattern.matcher(PreliminaryData.typingTest);
boolean findFlag = whiteSpaceMatcher.find();
assertTrue (findFlag);
if (findFlag)
{
String groupString = whiteSpaceMatcher.group();
int startPosition = whiteSpaceMatcher.start();
int endPosition = whiteSpaceMatcher.end();
String tempString = String.format
(
"found the text" + " \"%s\" starting at " + "index %d and ending at index %d.%n",
groupString,
startPosition,
endPosition
);
System.out.println(tempString);
}
}
catch (Exception e)
{
fail(e.toString() );
}
}
@Test
public void testNonWord()
{
try
{
Pattern whiteSpacePattern = Pattern.compile("\\W");
Matcher whiteSpaceMatcher = whiteSpacePattern.matcher(PreliminaryData.typingTest);
boolean findFlag = whiteSpaceMatcher.find();
assertTrue (findFlag);
if (findFlag)
{
String groupString = whiteSpaceMatcher.group();
int startPosition = whiteSpaceMatcher.start();
int endPosition = whiteSpaceMatcher.end();
String tempString = String.format
(
"found the text" + " \"%s\" starting at " + "index %d and ending at index %d.%n",
groupString,
startPosition,
endPosition
);
System.out.println(tempString);
}
}
catch (Exception e)
{
fail(e.toString() );
}
}
}
| 32.265487
| 122
| 0.467361
|
c9edd30a8a4976259d0a375985bd68e3d189eb16
| 9,304
|
package net.sanlite.client.plugins.combattickcounter;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Provides;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.Actor;
import net.runelite.api.Client;
import net.runelite.api.GameState;
import net.runelite.api.Player;
import net.runelite.api.events.AnimationChanged;
import net.runelite.client.events.ConfigChanged;
import net.runelite.api.events.GameStateChanged;
import net.runelite.api.events.GameTick;
import net.runelite.api.kit.KitType;
import net.runelite.client.config.ConfigManager;
import net.runelite.client.eventbus.EventBus;
import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor;
import net.runelite.client.ui.overlay.OverlayManager;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.awt.*;
import java.util.List;
import java.util.*;
import static java.util.Collections.reverseOrder;
import static net.sanlite.client.plugins.combattickcounter.id.AnimationID.BLOWPIPE_ATTACK;
@PluginDescriptor(
name = "Combat Tick Counter",
description = "Count the amount of perfect combat ticks performed by each player",
tags = {"combat", "counter", "tick", "pvm", "overlay", "boss", "sanlite"},
enabledByDefault = false
)
@Singleton
@Slf4j
public class CombatTickCounterPlugin extends Plugin
{
@Inject
private Client client;
@Inject
private CombatTickCounterOverlay tickOverlay;
@Inject
private OverlayManager overlayManager;
@Inject
private CombatTickCounterConfig config;
@Inject
private EventBus eventBus;
private boolean instanced = false;
@Setter(AccessLevel.PACKAGE)
@Getter(AccessLevel.PACKAGE)
private Map<String, Long> counter = new HashMap<>();
private final Map<String, Long> blowpipe = new HashMap<>();
@Getter(AccessLevel.PACKAGE)
private boolean showTickCounter;
private boolean resetOnNewInstance;
@Getter(AccessLevel.PACKAGE)
private Color selfColor;
@Getter(AccessLevel.PACKAGE)
private Color totalColor;
@Getter(AccessLevel.PACKAGE)
private Color otherColor;
@Getter(AccessLevel.PACKAGE)
private Color backgroundColor;
@Getter(AccessLevel.PACKAGE)
private Color titleColor;
@Provides
CombatTickCounterConfig provideConfig(ConfigManager configManager)
{
return configManager.getConfig(CombatTickCounterConfig.class);
}
private static final Map<Integer, Integer> VARIABLES = ImmutableMap.<Integer, Integer>builder()
.put(422, 4) // Unarmed Punch, Block
.put(423, 4) // Unarmed Kick
.put(8145, 4) // Rapier Stab, Lunge, Block
.put(390, 4) // Rapier Slash
.put(7552, 5) // Armadyl Crossbow Accurate, Rapid, Longrange, Special
.put(1167, 4) // Trident Accurate, Accurate, Longrange
.put(401, 6) // Dragon Warhammer Pound, Pummel, Block
.put(1378, 6) // Dragon Warhammer Special
.put(393, 4) // Dragon Claws Chop, Slash, Block
.put(1067, 4) // Dragon Claws Lunge
.put(7514, 4) // Dragon Claws Special
.put(8288, 4) // Dragon Hunter Lance Lunge, Block
.put(8289, 4) // Dragon Hunter Lance Swipe
.put(8290, 4) // Dragon Hunter Lance Pound
.put(7516, 6) // Elder maul Pound, Pummel, Block
.put(8056, 5) // Scythe of Vitur Reap, Chop, Jab, Block
.put(7045, 6) // Bandos Godsword Chop, Slash
.put(7054, 6) // Bandos Godsword Smash
.put(7055, 6) // Bandos Godsword Block
.put(7642, 6) // Bandos Godsword Special
.put(7643, 6) // Bandos Godsword Special (Ornate)
.put(426, 5) // Twisted Bow Accurate, Rapid, Longrange
.put(414, 5) // Kodai Bash, Pound, Focus
// .put(428, 4) // Staff of Light Jab
.put(440, 4) // Staff of Light Swipe
//.put(419, 4) // Staff of Light Fend
.put(7967, 4) // Staff of Light Special
.put(428, 7) // Crystal Halberd Jab, Fend
.put(419, 7) // Crystal Halberd Swipe
.put(1203, 7) // Crystal Halberd Special
.put(5061, 2) // Toxic Blowpipe Accurate, Rapid, Longrange, Special
.put(1979, 5) // Ancient Magicks Barrage
.put(1978, 5) // Ancient Magicks Blitz
.put(7618, 3) // Chinchompa Short, Medium, Long Fuse
.put(1658, 4) // Whip Flick, Lash, Deflect
.put(7555, 6) // Ballista Accurate, Rapid, Longrange
.build();
private static final Set<Integer> MELEE_ANIMATIONS = ImmutableSet.<Integer>builder()
.add(422) // Unarmed Punch, Block
.add(423) // Unarmed Kick
.add(8145) // Rapier Stab, Lunge, Block
.add(390) // Rapier Slash
.add(401) // Dragon Warhammer Pound, Pummel, Block
.add(1378) // Dragon Warhammer Special
.add(393) // Dragon Claws Chop, Slash, Block
.add(1067) // Dragon Claws Lunge
.add(7514) // Dragon Claws Special
.add(8288) // Dragon Hunter Lance Lunge, Block
.add(8289) // Dragon Hunter Lance Swipe
.add(8290) // Dragon Hunter Lance Pound
.add(7516) // Elder maul Pound, Pummel, Block
.add(8056) // Scythe of Vitur Reap, Chop, Jab, Block
.add(7045) // Bandos Godsword Chop, Slash
.add(7054) // Bandos Godsword Smash
.add(7055) // Bandos Godsword Block
.add(7642) // Bandos Godsword Special
.add(7643) // Bandos Godsword Special (Ornate)
.add(414) // Kodai Bash, Pound, Focus
.add(428) // Staff of Light Jab
.add(440) // Staff of Light Swipe
.add(419) // Staff of Light Fend
.add(428) // Crystal Halberd Jab, Fend
.add(419) // Crystal Halberd Swipe
.add(1203) // Crystal Halberd Special
.add(1658) // Whip Flick, Lash, Deflect
.build();
private static final Set<Integer> RANGE_ANIMATIONS = ImmutableSet.of(
7552, // Armadyl Crossbow Accurate, Rapid, Longrange, Special
426, // Twisted Bow Accurate, Rapid, Longrange
7618, // Chinchompa Short, Medium, Long Fuse
7555 // Ballista Accurate, Rapid, Longrange
);
private static final Set<Integer> MAGE_ANIMATIONS = ImmutableSet.of(
1167, // Trident Accurate, Accurate, Longrange
1978, // Ancient Magicks Blitz
1979 // Ancient Magicks Barrage
);
@Override
protected void startUp() throws Exception
{
updateConfig();
overlayManager.add(tickOverlay);
reset();
}
@Override
protected void shutDown() throws Exception
{
eventBus.unregister(this);
overlayManager.remove(tickOverlay);
reset();
}
private void reset()
{
this.counter.clear();
this.blowpipe.clear();
}
@Subscribe
private void onAnimationChanged(AnimationChanged event)
{
Actor actor = event.getActor();
if (actor instanceof Player)
{
Player player = (Player) actor;
String name = actor.getName();
if (name != null)
{
int animation = player.getAnimation();
if (animation != -1)
{
if (VARIABLES.containsKey(animation))
{
long ticks = VARIABLES.get(animation);
if (((Player) actor).getPlayerComposition().getEquipmentId(KitType.WEAPON) == 23360)
{
ticks = 3;
}
if (counter.containsKey(name))
{
ticks += counter.get(name);
}
counter.put(name, ticks);
counter = sortByValue(counter);
if (animation == BLOWPIPE_ATTACK)
{
this.blowpipe.put(name, -4L);
}
}
}
else
{
this.blowpipe.remove(name);
}
}
}
}
@Subscribe
private void onGameTick(GameTick event)
{
if (this.resetOnNewInstance)
{
boolean prevInstance = instanced;
instanced = client.isInInstancedRegion();
if (!prevInstance && instanced)
{
this.counter.clear();
this.blowpipe.clear();
}
}
Map<String, Player> visible = new HashMap<>();
for (Player player : this.client.getPlayers())
{
if (player.getName() != null)
{
visible.put(player.getName(), player);
}
}
for (String user : new ArrayList<>(blowpipe.keySet()))
{
if (visible.containsKey(user))
{
long count = blowpipe.get(user);
count++;
blowpipe.replace(user, count);
if (count % 2 == 0 && count >= 0 && counter.containsKey(user))
{
long ticks = counter.get(user);
counter.replace(user, ticks + 2);
counter = sortByValue(counter);
}
}
else
{
blowpipe.remove(user);
}
}
}
private <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map)
{
List<Map.Entry<K, V>> list = new ArrayList<>(map.entrySet());
list.sort(reverseOrder(Map.Entry.comparingByValue()));
Map<K, V> result = new LinkedHashMap<>();
for (Map.Entry<K, V> entry : list)
{
result.put(entry.getKey(), entry.getValue());
}
return result;
}
@Subscribe
public void onGameStateChanged(GameStateChanged event)
{
GameState gameState = event.getGameState();
if (gameState == GameState.LOGGING_IN || gameState == GameState.CONNECTION_LOST || gameState == GameState.HOPPING)
{
reset();
}
}
@Subscribe
private void onConfigChanged(ConfigChanged event)
{
if (event.getGroup().equals("Combat Tick Counter"))
{
updateConfig();
}
}
private void updateConfig()
{
this.showTickCounter = config.showTickCounter();
this.resetOnNewInstance = config.resetOnNewInstance();
this.selfColor = config.selfColor();
this.totalColor = config.totalColor();
this.otherColor = config.otherColor();
this.backgroundColor = config.backgroundColor();
this.titleColor = config.titleColor();
}
}
| 26.282486
| 116
| 0.690348
|
52ae0429cf260b70f452a17a6255a5a21cd0defa
| 636
|
package exercise;
public class Ch1601 {
static void printObject(BerylliumSphere[] berylliumSpheres) {
System.out.println(berylliumSpheres.length);
}
public static void main(String[] args) {
// printObject(new BerylliumSphere[]{new BerylliumSphere(), new BerylliumSphere()});
BerylliumSphere[] b1 = {new BerylliumSphere()};
BerylliumSphere[] b2 = new BerylliumSphere[2];
System.arraycopy(b1, 0, b2, 0, 1);
}
}
class BerylliumSphere {
private static long counter;
private final long id = counter++;
public String toString() {
return "Sphere " + id;
}
}
| 24.461538
| 91
| 0.649371
|
141ce811513d7617938d383c723817de33cae318
| 1,477
|
package com.sensorfields.digiduck.android;
import android.content.Context;
import com.sensorfields.android.mvp.Presenter;
import com.sensorfields.digiduck.android.infrastructure.dagger.ApplicationComponent;
import com.sensorfields.digiduck.android.infrastructure.dagger.ApplicationModule;
import com.sensorfields.digiduck.android.infrastructure.dagger.DaggerApplicationComponent;
public class Application extends android.app.Application {
@Override
public void onCreate() {
super.onCreate();
setupTimber();
setupDagger();
}
// Timber
protected void setupTimber() {
}
// Dagger
protected ApplicationComponent applicationComponent;
protected void setupDagger() {
applicationComponent = DaggerApplicationComponent.builder()
.applicationModule(new ApplicationModule(this))
.build();
}
public static ApplicationComponent getApplicationComponent(Context context) {
return ((Application) context.getApplicationContext()).applicationComponent;
}
/**
* Helper for getting {@link Presenter.Factory presenter factories} from DI component.
*/
@SuppressWarnings("unchecked")
public static <T extends Presenter.Factory> T getPresenterFactory(Context context,
Class<T> type) {
return (T) getApplicationComponent(context).presenterFactories().get(type);
}
}
| 31.425532
| 90
| 0.693297
|
b3a79c685eb569c414bb8e7243dabd43db84750c
| 2,412
|
/*
* Copyright (C) 1999-2011 University of Connecticut Health Center
*
* Licensed under the MIT License (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.opensource.org/licenses/mit-license.php
*/
package org.sbpax.schemas.util;
/* NameSpace --- by Oliver Ruebenacker, UCHC --- November 2007 to May 2009
* A number of popular name spaces and their usual shortcuts
*/
import org.sbpax.schemas.BioPAX3;
import org.sbpax.schemas.SBPAX3;
import org.vcell.pathway.sbo.SBOTerm;
public class DefaultNameSpaces {
public static NSMap defaultMap = new NSMap();
public static final NameSpace RDF = defaultMap.register("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
public static final NameSpace RDFS = defaultMap.register("rdfs", "http://www.w3.org/2000/01/rdf-schema#");
public static final NameSpace OWL = defaultMap.register("owl", "http://www.w3.org/2002/07/owl#");
public static final NameSpace XMLS = defaultMap.register("xmls", "http://www.w3.org/2001/XMLSchema#");
public static final NameSpace XSD = defaultMap.register("xsd", "http://www.w3.org/2001/XMLSchema#");
public static final NameSpace DUBLIN_CORE = defaultMap.register("dc", "http://purl.org/dc/elements/1.1/");
public static final NameSpace DC_TERMS = defaultMap.register("dcterms", "http://purl.org/dc/terms/");
public static final NameSpace FOAF = defaultMap.register("foaf", "http://xmlns.com/foaf/0.1/");
public static final NameSpace VCARD = defaultMap.register("vcard", "http://www.w3.org/2001/vcard-rdf/3.0#");
public static final NameSpace BQBIOL = defaultMap.register("bqbiol", "http://biomodels.net/biology-qualifiers/");
public static final NameSpace BQMODEL = defaultMap.register("bqmodel", "http://biomodels.net/model-qualifiers/");
public static final NameSpace BP3 = defaultMap.register("bp3", BioPAX3.ns.uri);
public static final NameSpace SBX3 = defaultMap.register("sbx3", SBPAX3.ns.uri);
public static final NameSpace UOME_CORE = defaultMap.register("uome-core", "http://www.sbpax.org/uome/core.owl#");
public static final NameSpace UOME_LIST = defaultMap.register("uome-list", "http://www.sbpax.org/uome/list.owl#");
public static final NameSpace SBO = defaultMap.register("sbo", SBOTerm.SBO_BASE_URI);
public static final NameSpace EX = defaultMap.register("ex", "http://example.org/");
}
| 54.818182
| 115
| 0.740879
|
e9a2bb469c8e1dd40fd6abc0ad6a07ee589427d2
| 2,027
|
package com.ecjtu.flesh.model;
import com.ecjtu.flesh.model.models.NotificationModel;
import com.ecjtu.flesh.model.models.VideoModel;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Ethan_Xiang on 2017/9/22.
*/
public class ModelManager {
public static NotificationModel getNotificationModel(int id, String title, String content, String ticker, int limit, String time, String timeLimit, String actionDetailUrl, String h5Page) {
NotificationModel model = new NotificationModel();
model.setId(id);
model.setTitle(title);
model.setContent(content);
model.setTicker(ticker);
model.setLimit(limit);
model.setTime(time);
model.setTimeLimit(timeLimit);
model.setActionDetailUrl(actionDetailUrl);
model.setH5Page(h5Page);
return model;
}
public static List<VideoModel> getVideoModelByString(String json) {
try {
JSONObject root = new JSONObject(json);
JSONArray arr = root.getJSONArray("data");
List<VideoModel> ret = new ArrayList<>();
for (int i = 0; i < arr.length(); i++) {
JSONObject obj = arr.getJSONObject(i);
VideoModel model = new VideoModel();
model.setK(obj.optString("k"));
model.setId(obj.optString("id"));
model.setTitle(obj.optString("title"));
model.setPic_url(obj.optString("pic_url"));
model.setCishu(obj.optString("cishu"));
model.setMember(obj.optString("member"));
model.setSource(obj.optString("source"));
model.setAddtime(obj.optString("addtime"));
model.setHits(obj.optString("hits"));
ret.add(model);
}
return ret;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
| 34.355932
| 192
| 0.609275
|
3766bd9f93c2bf7d7735fc5c0e6eb9d1f27bed20
| 2,838
|
package ca.uoit.crobot;
import ca.uoit.crobot.hardware.*;
import ca.uoit.crobot.model.GameObject;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
public class Simulator {
public static void main(String[] args) throws InterruptedException, IOException {
final JFrame frame = new JFrame("Crobot Simulator");
final List<GameObject> objects = new LinkedList<>();
final int[] xPointsBox = new int[] { 10, 100, 990, 500, 400, 990, 10};
final int[] yPointsBox = new int[] { 10, 100, 10, 600, 750, 990, 990};
final int[] xPoints = new int[] { 0, 25, 50, 75, 75, 50, 38, 25, 0};
final int[] yPoints = new int[] { 25, 0, 0, 25, 50, 75, 100, 75, 50};
final GameObject wall = new GameObject(new Polygon(xPointsBox, yPointsBox, 7), Color.BLACK);
objects.add(wall);
final GameObject robot = new GameObject(new Polygon(xPoints, yPoints, 9), Color.BLACK);
final SimulatedMotor left = new SimulatedMotor(robot);
final SimulatedMotor right = new SimulatedMotor(robot);
left.setOtherMotor(right);
right.setOtherMotor(left);
robot.getPosition().setX(200);
robot.getPosition().setY(250);
objects.add(robot);
final SimulatedLidar lidar = new SimulatedLidar(objects, robot, 1000, 600);
final Display display = new Display(objects, Color.GRAY, lidar, 1000, 1000);
frame.add(display);
frame.pack();
frame.setSize(600, 600);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
Thread.sleep(1000);
System.out.println("Initialized...");
// robot(left, right, lidar);
// left.setSpeed(30);
// right.setSpeed(30);
// LidarScan scan = lidar.scan();
// final Map map = CRSlam.createMap(1000, 0.5);
//
// CRSlam.ts_map_update(scan, map, new Position(robot.getPosition().getX(), robot.getPosition().getY(), robot.getYaw()), 50);
//
// robot.getPosition().setX(200);
// robot.getPosition().setX(400);
// scan = lidar.scan();
//
// ImageIO.write(map.toImage(), "png", new File("img1.png"));
//
// CRSlam.ts_map_update(scan, map, new Position(robot.getPosition().getX(), robot.getPosition().getY(), robot.getYaw()), 50);
//
// ImageIO.write(map.toImage(), "png", new File("img2.png"));
// while (true) {
// Thread.sleep(50);
// objects.forEach(GameObject::update);
// left.update();
// right.update();
// display.repaint();
// }
}
private enum ACTION {
STOP,
FORWARD,
TURN_LEFT,
TURN_RIGHT
}
}
| 31.186813
| 132
| 0.606765
|
72d021910d39627dd287f4e2a3f2450b8d9b316b
| 5,020
|
package io.dockstore.webservice.helpers;
import com.google.common.collect.Sets;
import io.dockstore.webservice.CustomWebApplicationException;
import io.dockstore.webservice.core.Alias;
import io.dockstore.webservice.core.User;
import io.dockstore.webservice.core.Workflow;
import io.dockstore.webservice.core.WorkflowVersion;
import io.dockstore.webservice.jdbi.WorkflowDAO;
import io.dockstore.webservice.jdbi.WorkflowVersionDAO;
import io.dockstore.webservice.resources.AliasableResourceInterface;
import io.dockstore.webservice.resources.AuthenticatedResourceInterface;
import java.util.Arrays;
import java.util.Optional;
import java.util.Set;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class AliasHelper {
private static final Logger LOG = LoggerFactory.getLogger(AliasHelper.class);
private AliasHelper() {
}
/**
* Finds a workflow and returns the workflow id based on a workflow version id.
*
* @param workflowDAO Workflow data access object
* @param workflowVersionId the id of the workflow version
* @return workflow or throws an exception if the workflow cannot be found
*/
public static Workflow getWorkflow(WorkflowDAO workflowDAO, long workflowVersionId) {
Optional<Workflow> workflow = workflowDAO.getWorkflowByWorkflowVersionId(workflowVersionId);
if (!workflow.isPresent()) {
LOG.error("Could not get workflow based on workflow version id " + workflowVersionId);
throw new CustomWebApplicationException("Could not get workflow based on workflow version id " + workflowVersionId, HttpStatus.SC_NOT_FOUND);
}
return workflow.get();
}
/**
* Gets the Workflow Version object via a Workflow Version ID
* and checks that the Workflow exists and that the
* user is authorized to update it
* @param authenticatedResourceInterface interface to check users and entries
* @param workflowDAO Workflow data access object
* @param workflowVersionDAO Workflow Version data access object
* @param user user authenticated to update the workflow
* @param workflowVersionId the id of the workflow version
* @return the workflow version
*/
public static WorkflowVersion getAndCheckWorkflowVersionResource(AuthenticatedResourceInterface authenticatedResourceInterface, WorkflowDAO workflowDAO,
WorkflowVersionDAO workflowVersionDAO, User user, Long workflowVersionId) {
final WorkflowVersion workflowVersion = workflowVersionDAO.findById(workflowVersionId);
if (workflowVersion == null) {
LOG.error("Could not find workflow version using the workflow version id: " + workflowVersionId);
throw new CustomWebApplicationException("Workflow version not found when searching with id: " + workflowVersionId, HttpStatus.SC_BAD_REQUEST);
}
Workflow workflow = getWorkflow(workflowDAO, workflowVersionId);
authenticatedResourceInterface.checkUserCanUpdate(user, workflow);
return workflowVersion;
}
/**
* Add aliases to a Workflow Version
* and check that they are valid before adding them:
* Only works for owner of the entry
* If blockFormat false, then no limit on format
* @param authenticatedResourceInterface interface to check users and entries
* @param workflowDAO Workflow data access object
* @param workflowVersionDAO Workflow Version data access object
* @param user user authenticated to issue a DOI for the workflow
* @param id the id of the Entry
* @param aliases a comma separated string of aliases
* @param blockFormat if true don't allow specific formats
* @return the Workflow Version
*/
public static WorkflowVersion addWorkflowVersionAliasesAndCheck(AuthenticatedResourceInterface authenticatedResourceInterface, WorkflowDAO workflowDAO,
WorkflowVersionDAO workflowVersionDAO, User user, Long id, String aliases, boolean blockFormat) {
WorkflowVersion workflowVersion = getAndCheckWorkflowVersionResource(authenticatedResourceInterface, workflowDAO, workflowVersionDAO, user, id);
Set<String> oldAliases = workflowVersion.getAliases().keySet();
Set<String> newAliases = Sets.newHashSet(Arrays.stream(aliases.split(",")).map(String::trim).toArray(String[]::new));
AliasableResourceInterface.checkAliases(newAliases, user, blockFormat);
Set<String> duplicateAliasesToAdd = Sets.intersection(newAliases, oldAliases);
if (!duplicateAliasesToAdd.isEmpty()) {
String dupAliasesString = String.join(", ", duplicateAliasesToAdd);
throw new CustomWebApplicationException("Aliases " + dupAliasesString + " already exist; please use unique aliases",
HttpStatus.SC_BAD_REQUEST);
}
newAliases.forEach(alias -> workflowVersion.getAliases().put(alias, new Alias()));
return workflowVersion;
}
}
| 50.2
| 156
| 0.74502
|
634551c8c0a3922d4d8dacd0f4423bee828ff729
| 672
|
package edu.uw.edm.profile;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.ApplicationPidFileWriter;
import org.springframework.hateoas.config.EnableHypermediaSupport;
/**
* @author Maxime Deravet Date: 10/13/17
*/
@SpringBootApplication
@EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL)
public class Application {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Application.class);
app.addListeners(new ApplicationPidFileWriter());
app.run(args);
}
}
| 25.846154
| 75
| 0.78125
|
714eb53cb20489d45b119182d429d7df7d133cc8
| 28,432
|
package org.sec.core;
import org.sec.model.ClassReference;
import org.sec.model.MethodReference;
import org.objectweb.asm.*;
import org.objectweb.asm.commons.AnalyzerAdapter;
import java.util.*;
@SuppressWarnings("all")
public class CoreMethodAdapter<T> extends MethodVisitor {
private final InheritanceMap inheritanceMap;
private final AnalyzerAdapter analyzerAdapter;
private final int access;
private final String name;
private final String desc;
private final String signature;
private final String[] exceptions;
private final Map<MethodReference.Handle, Set<Integer>> passthroughDataflow;
private final Map<Label, GotoState<T>> gotoStates = new HashMap<>();
private final Set<Label> exceptionHandlerLabels = new HashSet<>();
protected OperandStack<T> operandStack;
protected LocalVariables<T> localVariables;
public CoreMethodAdapter(InheritanceMap inheritanceMap,
Map<MethodReference.Handle, Set<Integer>> passthroughDataflow,
final int api, final MethodVisitor mv, final String owner, int access,
String name, String desc, String signature, String[] exceptions) {
super(api, new AnalyzerAdapter(owner, access, name, desc, mv));
this.inheritanceMap = inheritanceMap;
this.passthroughDataflow = passthroughDataflow;
this.analyzerAdapter = (AnalyzerAdapter) this.mv;
this.access = access;
this.name = name;
this.desc = desc;
this.signature = signature;
this.exceptions = exceptions;
operandStack = new OperandStack<>();
localVariables = new LocalVariables<>();
}
private void sanityCheck() {
if (analyzerAdapter.stack != null && operandStack.size() != analyzerAdapter.stack.size()) {
throw new IllegalStateException("bad stack size");
}
}
private void mergeGotoState(Label label) {
if (gotoStates.containsKey(label)) {
GotoState<T> state = gotoStates.get(label);
// old -> label
LocalVariables<T> oldLocalVariables = state.getLocalVariables();
OperandStack<T> oldOperandStack = state.getOperandStack();
// new -> null
LocalVariables<T> newLocalVariables = new LocalVariables<>();
OperandStack<T> newOperandStack = new OperandStack<>();
// init new
for (Set<T> original : oldLocalVariables.getList()) {
newLocalVariables.add(new HashSet<>(original));
}
for (Set<T> original : oldOperandStack.getList()) {
newOperandStack.add(new HashSet<>(original));
}
// add current state
for (int i = 0; i < newLocalVariables.size(); i++) {
while (i >= oldLocalVariables.size()) {
oldLocalVariables.add(new HashSet<>());
}
newLocalVariables.get(i).addAll(oldLocalVariables.get(i));
}
for (int i = 0; i < newOperandStack.size(); i++) {
while (i >= oldOperandStack.size()) {
oldOperandStack.add(new HashSet<>());
}
oldOperandStack.get(i).addAll(oldOperandStack.get(i));
}
// set new state
GotoState<T> newGotoState = new GotoState<>();
newGotoState.setOperandStack(newOperandStack);
newGotoState.setLocalVariables(newLocalVariables);
gotoStates.put(label, newGotoState);
} else {
LocalVariables<T> oldLocalVariables = localVariables;
OperandStack<T> oldOperandStack = operandStack;
// new -> null
LocalVariables<T> newLocalVariables = new LocalVariables<>();
OperandStack<T> newOperandStack = new OperandStack<>();
// init new
for (Set<T> original : oldLocalVariables.getList()) {
newLocalVariables.add(new HashSet<>(original));
}
for (Set<T> original : oldOperandStack.getList()) {
newOperandStack.add(new HashSet<>(original));
}
// set new state
GotoState<T> newGotoState = new GotoState<>();
newGotoState.setOperandStack(newOperandStack);
newGotoState.setLocalVariables(newLocalVariables);
gotoStates.put(label, newGotoState);
}
}
@Override
public void visitCode() {
super.visitCode();
localVariables.clear();
operandStack.clear();
if ((this.access & Opcodes.ACC_STATIC) == 0) {
localVariables.add(new HashSet<>());
}
for (Type argType : Type.getArgumentTypes(desc)) {
for (int i = 0; i < argType.getSize(); i++) {
localVariables.add(new HashSet<>());
}
}
}
@Override
public void visitFrame(int type, int nLocal, Object[] local, int nStack, Object[] stack) {
int stackSize = 0;
for (int i = 0; i < nStack; i++) {
Object typ = stack[i];
int objectSize = 1;
if (typ.equals(Opcodes.LONG) || typ.equals(Opcodes.DOUBLE)) {
objectSize = 2;
}
for (int j = operandStack.size(); j < stackSize + objectSize; j++) {
operandStack.add(new HashSet<>());
}
stackSize += objectSize;
}
int localSize = 0;
for (int i = 0; i < nLocal; i++) {
Object typ = local[i];
int objectSize = 1;
if (typ.equals(Opcodes.LONG) || typ.equals(Opcodes.DOUBLE)) {
objectSize = 2;
}
for (int j = localVariables.size(); j < localSize + objectSize; j++) {
localVariables.add(new HashSet<>());
}
localSize += objectSize;
}
for (int i = operandStack.size() - stackSize; i > 0; i--) {
operandStack.remove(operandStack.size() - 1);
}
for (int i = localVariables.size() - localSize; i > 0; i--) {
localVariables.remove(localVariables.size() - 1);
}
super.visitFrame(type, nLocal, local, nStack, stack);
sanityCheck();
}
@Override
public void visitInsn(int opcode) {
Set<T> saved0, saved1, saved2, saved3;
sanityCheck();
switch (opcode) {
case Opcodes.NOP:
break;
case Opcodes.ACONST_NULL:
case Opcodes.ICONST_M1:
case Opcodes.ICONST_0:
case Opcodes.ICONST_1:
case Opcodes.ICONST_2:
case Opcodes.ICONST_3:
case Opcodes.ICONST_4:
case Opcodes.ICONST_5:
case Opcodes.FCONST_0:
case Opcodes.FCONST_1:
case Opcodes.FCONST_2:
operandStack.push();
break;
case Opcodes.LCONST_0:
case Opcodes.LCONST_1:
case Opcodes.DCONST_0:
case Opcodes.DCONST_1:
operandStack.push();
operandStack.push();
break;
case Opcodes.IALOAD:
case Opcodes.FALOAD:
case Opcodes.AALOAD:
case Opcodes.BALOAD:
case Opcodes.CALOAD:
case Opcodes.SALOAD:
operandStack.pop();
operandStack.pop();
operandStack.push();
break;
case Opcodes.LALOAD:
case Opcodes.DALOAD:
operandStack.pop();
operandStack.pop();
operandStack.push();
operandStack.push();
break;
case Opcodes.IASTORE:
case Opcodes.FASTORE:
case Opcodes.AASTORE:
case Opcodes.BASTORE:
case Opcodes.CASTORE:
case Opcodes.SASTORE:
operandStack.pop();
operandStack.pop();
operandStack.pop();
break;
case Opcodes.LASTORE:
case Opcodes.DASTORE:
operandStack.pop();
operandStack.pop();
operandStack.pop();
operandStack.pop();
break;
case Opcodes.POP:
operandStack.pop();
break;
case Opcodes.POP2:
operandStack.pop();
operandStack.pop();
break;
case Opcodes.DUP:
operandStack.push(operandStack.get(0));
break;
case Opcodes.DUP_X1:
saved0 = operandStack.pop();
saved1 = operandStack.pop();
operandStack.push(saved0);
operandStack.push(saved1);
operandStack.push(saved0);
break;
case Opcodes.DUP_X2:
saved0 = operandStack.pop();
saved1 = operandStack.pop();
saved2 = operandStack.pop();
operandStack.push(saved0);
operandStack.push(saved2);
operandStack.push(saved1);
operandStack.push(saved0);
break;
case Opcodes.DUP2:
operandStack.push(operandStack.get(1));
operandStack.push(operandStack.get(1));
break;
case Opcodes.DUP2_X1:
saved0 = operandStack.pop();
saved1 = operandStack.pop();
saved2 = operandStack.pop();
operandStack.push(saved1);
operandStack.push(saved0);
operandStack.push(saved2);
operandStack.push(saved1);
operandStack.push(saved0);
break;
case Opcodes.DUP2_X2:
saved0 = operandStack.pop();
saved1 = operandStack.pop();
saved2 = operandStack.pop();
saved3 = operandStack.pop();
operandStack.push(saved1);
operandStack.push(saved0);
operandStack.push(saved3);
operandStack.push(saved2);
operandStack.push(saved1);
operandStack.push(saved0);
break;
case Opcodes.SWAP:
saved0 = operandStack.pop();
saved1 = operandStack.pop();
operandStack.push(saved0);
operandStack.push(saved1);
break;
case Opcodes.IADD:
case Opcodes.FADD:
case Opcodes.ISUB:
case Opcodes.FSUB:
case Opcodes.IMUL:
case Opcodes.FMUL:
case Opcodes.IDIV:
case Opcodes.FDIV:
case Opcodes.IREM:
case Opcodes.FREM:
operandStack.pop();
operandStack.pop();
operandStack.push();
break;
case Opcodes.LADD:
case Opcodes.DADD:
case Opcodes.LSUB:
case Opcodes.DSUB:
case Opcodes.LMUL:
case Opcodes.DMUL:
case Opcodes.LDIV:
case Opcodes.DDIV:
case Opcodes.LREM:
case Opcodes.DREM:
operandStack.pop();
operandStack.pop();
operandStack.pop();
operandStack.pop();
operandStack.push();
operandStack.push();
break;
case Opcodes.INEG:
case Opcodes.FNEG:
operandStack.pop();
operandStack.push();
break;
case Opcodes.LNEG:
case Opcodes.DNEG:
operandStack.pop();
operandStack.pop();
operandStack.push();
operandStack.push();
break;
case Opcodes.ISHL:
case Opcodes.ISHR:
case Opcodes.IUSHR:
operandStack.pop();
operandStack.pop();
operandStack.push();
break;
case Opcodes.LSHL:
case Opcodes.LSHR:
case Opcodes.LUSHR:
operandStack.pop();
operandStack.pop();
operandStack.pop();
operandStack.push();
operandStack.push();
break;
case Opcodes.IAND:
case Opcodes.IOR:
case Opcodes.IXOR:
operandStack.pop();
operandStack.pop();
operandStack.push();
break;
case Opcodes.LAND:
case Opcodes.LOR:
case Opcodes.LXOR:
operandStack.pop();
operandStack.pop();
operandStack.pop();
operandStack.pop();
operandStack.push();
operandStack.push();
break;
case Opcodes.I2B:
case Opcodes.I2C:
case Opcodes.I2S:
case Opcodes.I2F:
operandStack.pop();
operandStack.push();
break;
case Opcodes.I2L:
case Opcodes.I2D:
operandStack.pop();
operandStack.push();
operandStack.push();
break;
case Opcodes.L2I:
case Opcodes.L2F:
operandStack.pop();
operandStack.pop();
operandStack.push();
break;
case Opcodes.D2L:
case Opcodes.L2D:
operandStack.pop();
operandStack.pop();
operandStack.push();
operandStack.push();
break;
case Opcodes.F2I:
operandStack.pop();
operandStack.push();
break;
case Opcodes.F2L:
case Opcodes.F2D:
operandStack.pop();
operandStack.push();
operandStack.push();
break;
case Opcodes.D2I:
case Opcodes.D2F:
operandStack.pop();
operandStack.pop();
operandStack.push();
break;
case Opcodes.LCMP:
operandStack.pop();
operandStack.pop();
operandStack.pop();
operandStack.pop();
operandStack.push();
break;
case Opcodes.FCMPL:
case Opcodes.FCMPG:
operandStack.pop();
operandStack.pop();
operandStack.push();
break;
case Opcodes.DCMPL:
case Opcodes.DCMPG:
operandStack.pop();
operandStack.pop();
operandStack.pop();
operandStack.pop();
operandStack.push();
break;
case Opcodes.IRETURN:
case Opcodes.FRETURN:
case Opcodes.ARETURN:
operandStack.pop();
break;
case Opcodes.LRETURN:
case Opcodes.DRETURN:
operandStack.pop();
operandStack.pop();
break;
case Opcodes.RETURN:
break;
case Opcodes.ARRAYLENGTH:
operandStack.pop();
operandStack.push();
break;
case Opcodes.ATHROW:
operandStack.pop();
break;
case Opcodes.MONITORENTER:
case Opcodes.MONITOREXIT:
operandStack.pop();
break;
default:
throw new IllegalStateException("unsupported opcode: " + opcode);
}
super.visitInsn(opcode);
sanityCheck();
}
@Override
public void visitIntInsn(int opcode, int operand) {
switch (opcode) {
case Opcodes.BIPUSH:
case Opcodes.SIPUSH:
operandStack.push();
break;
case Opcodes.NEWARRAY:
operandStack.pop();
operandStack.push();
break;
default:
throw new IllegalStateException("unsupported opcode: " + opcode);
}
super.visitIntInsn(opcode, operand);
sanityCheck();
}
@Override
public void visitVarInsn(int opcode, int var) {
for (int i = localVariables.size(); i <= var; i++) {
localVariables.add(new HashSet<>());
}
Set<T> saved0;
switch (opcode) {
case Opcodes.ILOAD:
case Opcodes.FLOAD:
operandStack.push();
break;
case Opcodes.LLOAD:
case Opcodes.DLOAD:
operandStack.push();
operandStack.push();
break;
case Opcodes.ALOAD:
operandStack.push(localVariables.get(var));
break;
case Opcodes.ISTORE:
case Opcodes.FSTORE:
operandStack.pop();
localVariables.set(var, new HashSet<>());
break;
case Opcodes.DSTORE:
case Opcodes.LSTORE:
operandStack.pop();
operandStack.pop();
localVariables.set(var, new HashSet<>());
break;
case Opcodes.ASTORE:
saved0 = operandStack.pop();
localVariables.set(var, saved0);
break;
case Opcodes.RET:
break;
default:
throw new IllegalStateException("unsupported opcode: " + opcode);
}
super.visitVarInsn(opcode, var);
sanityCheck();
}
@Override
public void visitTypeInsn(int opcode, String type) {
switch (opcode) {
case Opcodes.NEW:
operandStack.push();
break;
case Opcodes.ANEWARRAY:
operandStack.pop();
operandStack.push();
break;
case Opcodes.CHECKCAST:
break;
case Opcodes.INSTANCEOF:
operandStack.pop();
operandStack.push();
break;
default:
throw new IllegalStateException("unsupported opcode: " + opcode);
}
super.visitTypeInsn(opcode, type);
sanityCheck();
}
@Override
public void visitFieldInsn(int opcode, String owner, String name, String desc) {
int typeSize = Type.getType(desc).getSize();
switch (opcode) {
case Opcodes.GETSTATIC:
for (int i = 0; i < typeSize; i++) {
operandStack.push();
}
break;
case Opcodes.PUTSTATIC:
for (int i = 0; i < typeSize; i++) {
operandStack.pop();
}
break;
case Opcodes.GETFIELD:
operandStack.pop();
for (int i = 0; i < typeSize; i++) {
operandStack.push();
}
break;
case Opcodes.PUTFIELD:
for (int i = 0; i < typeSize; i++) {
operandStack.pop();
}
operandStack.pop();
break;
default:
throw new IllegalStateException("unsupported opcode: " + opcode);
}
super.visitFieldInsn(opcode, owner, name, desc);
sanityCheck();
}
@Override
public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) {
final MethodReference.Handle methodHandle = new MethodReference.Handle(
new ClassReference.Handle(owner), name, desc);
Type[] argTypes = Type.getArgumentTypes(desc);
if (opcode != Opcodes.INVOKESTATIC) {
Type[] extendedArgTypes = new Type[argTypes.length + 1];
System.arraycopy(argTypes, 0, extendedArgTypes, 1, argTypes.length);
extendedArgTypes[0] = Type.getObjectType(owner);
argTypes = extendedArgTypes;
}
final Type returnType = Type.getReturnType(desc);
final int retSize = returnType.getSize();
switch (opcode) {
case Opcodes.INVOKESTATIC:
case Opcodes.INVOKEVIRTUAL:
case Opcodes.INVOKESPECIAL:
case Opcodes.INVOKEINTERFACE:
final List<Set<T>> argTaint = new ArrayList<>(argTypes.length);
for (int i = 0; i < argTypes.length; i++) {
argTaint.add(null);
}
for (int i = 0; i < argTypes.length; i++) {
Type argType = argTypes[i];
if (argType.getSize() > 0) {
for (int j = 0; j < argType.getSize() - 1; j++) {
operandStack.pop();
}
argTaint.set(argTypes.length - 1 - i, operandStack.pop());
}
}
Set<T> resultTaint;
if (name.equals("<init>")) {
resultTaint = argTaint.get(0);
} else {
resultTaint = new HashSet<>();
}
if (passthroughDataflow != null) {
Set<Integer> passthroughArgs = passthroughDataflow.get(methodHandle);
if (passthroughArgs != null) {
for (int arg : passthroughArgs) {
resultTaint.addAll(argTaint.get(arg));
}
}
}
if (opcode != Opcodes.INVOKESTATIC && argTypes[0].getSort() == Type.OBJECT) {
Set<ClassReference.Handle> parents = inheritanceMap.getSuperClasses(
new ClassReference.Handle(argTypes[0].getClassName().replace('.', '/')));
if (parents != null &&
(parents.contains(new ClassReference.Handle("java/util/Collection")) ||
parents.contains(new ClassReference.Handle("java/util/Map")))) {
for (int i = 1; i < argTaint.size(); i++) {
argTaint.get(0).addAll(argTaint.get(i));
}
if (returnType.getSort() == Type.OBJECT || returnType.getSort() == Type.ARRAY) {
resultTaint.addAll(argTaint.get(0));
}
}
}
if (retSize > 0) {
operandStack.push(resultTaint);
for (int i = 1; i < retSize; i++) {
operandStack.push();
}
}
break;
default:
throw new IllegalStateException("unsupported opcode: " + opcode);
}
super.visitMethodInsn(opcode, owner, name, desc, itf);
sanityCheck();
}
@Override
public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object... bsmArgs) {
int argsSize = 0;
for (Type type : Type.getArgumentTypes(desc)) {
argsSize += type.getSize();
}
int retSize = Type.getReturnType(desc).getSize();
for (int i = 0; i < argsSize; i++) {
operandStack.pop();
}
for (int i = 0; i < retSize; i++) {
operandStack.push();
}
super.visitInvokeDynamicInsn(name, desc, bsm, bsmArgs);
sanityCheck();
}
@Override
public void visitJumpInsn(int opcode, Label label) {
switch (opcode) {
case Opcodes.IFEQ:
case Opcodes.IFNE:
case Opcodes.IFLT:
case Opcodes.IFGE:
case Opcodes.IFGT:
case Opcodes.IFLE:
case Opcodes.IFNULL:
case Opcodes.IFNONNULL:
operandStack.pop();
break;
case Opcodes.IF_ICMPEQ:
case Opcodes.IF_ICMPNE:
case Opcodes.IF_ICMPLT:
case Opcodes.IF_ICMPGE:
case Opcodes.IF_ICMPGT:
case Opcodes.IF_ICMPLE:
case Opcodes.IF_ACMPEQ:
case Opcodes.IF_ACMPNE:
operandStack.pop();
operandStack.pop();
break;
case Opcodes.GOTO:
break;
case Opcodes.JSR:
operandStack.push();
super.visitJumpInsn(opcode, label);
return;
default:
throw new IllegalStateException("unsupported opcode: " + opcode);
}
mergeGotoState(label);
super.visitJumpInsn(opcode, label);
sanityCheck();
}
@Override
public void visitLabel(Label label) {
if (gotoStates.containsKey(label)) {
GotoState<T> state = gotoStates.get(label);
// old -> label
LocalVariables<T> oldLocalVariables = state.getLocalVariables();
OperandStack<T> oldOperandStack = state.getOperandStack();
// new -> null
LocalVariables<T> newLocalVariables = new LocalVariables<>();
OperandStack<T> newOperandStack = new OperandStack<>();
// init new
for (Set<T> original : oldLocalVariables.getList()) {
newLocalVariables.add(new HashSet<>(original));
}
for (Set<T> original : oldOperandStack.getList()) {
newOperandStack.add(new HashSet<>(original));
}
this.operandStack = newOperandStack;
this.localVariables = newLocalVariables;
}
if (exceptionHandlerLabels.contains(label)) {
operandStack.push(new HashSet<>());
}
super.visitLabel(label);
sanityCheck();
}
@Override
public void visitLdcInsn(Object cst) {
if (cst instanceof Long || cst instanceof Double) {
operandStack.push();
operandStack.push();
} else {
operandStack.push();
}
super.visitLdcInsn(cst);
sanityCheck();
}
@Override
public void visitIincInsn(int var, int increment) {
super.visitIincInsn(var, increment);
sanityCheck();
}
@Override
public void visitTableSwitchInsn(int min, int max, Label dflt, Label... labels) {
operandStack.pop();
mergeGotoState(dflt);
for (Label label : labels) {
mergeGotoState(label);
}
super.visitTableSwitchInsn(min, max, dflt, labels);
sanityCheck();
}
@Override
public void visitLookupSwitchInsn(Label dflt, int[] keys, Label[] labels) {
operandStack.pop();
mergeGotoState(dflt);
for (Label label : labels) {
mergeGotoState(label);
}
super.visitLookupSwitchInsn(dflt, keys, labels);
sanityCheck();
}
@Override
public void visitMultiANewArrayInsn(String desc, int dims) {
for (int i = 0; i < dims; i++) {
operandStack.pop();
}
operandStack.push();
super.visitMultiANewArrayInsn(desc, dims);
sanityCheck();
}
@Override
public AnnotationVisitor visitInsnAnnotation(int typeRef, TypePath typePath, String desc, boolean visible) {
return super.visitInsnAnnotation(typeRef, typePath, desc, visible);
}
@Override
public void visitTryCatchBlock(Label start, Label end, Label handler, String type) {
exceptionHandlerLabels.add(handler);
super.visitTryCatchBlock(start, end, handler, type);
}
@Override
public AnnotationVisitor visitTryCatchAnnotation(int typeRef, TypePath typePath, String desc, boolean visible) {
return super.visitTryCatchAnnotation(typeRef, typePath, desc, visible);
}
@Override
public void visitMaxs(int maxStack, int maxLocals) {
super.visitMaxs(maxStack, maxLocals);
}
@Override
public void visitEnd() {
super.visitEnd();
}
}
| 35.85372
| 116
| 0.503623
|
8ac76b74cd06d1768e6b6e5bfeb68afaed27bda8
| 127
|
package poo.provas.p2.armazenamento;
public interface Armazem {
void guardar(Armazenavel a);
boolean temEspacoLivre();
}
| 12.7
| 36
| 0.76378
|
30b63a57aace9d1b51b2690d07600ee55d03108e
| 4,693
|
/*
*************************************************************************
*************************************************************************
** **
** V2KPARSE **
** Copyright (C) 2008-2009 Karl W. Pfalzer **
** **
** This program is free software; you can redistribute it and/or **
** modify it under the terms of the GNU General Public License **
** as published by the Free Software Foundation; either version 2 **
** of the License, or (at your option) any later version. **
** **
** This program is distributed in the hope that it will be useful, **
** but WITHOUT ANY WARRANTY; without even the implied warranty of **
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the **
** GNU General Public License for more details. **
** **
** You should have received a copy of the GNU General Public License **
** along with this program; if not, write to the **
** Free Software Foundation, Inc. **
** 51 Franklin Street, Fifth Floor **
** Boston, MA 02110-1301, USA. **
** **
*************************************************************************
*************************************************************************
*/
package v2k.util;
import java.util.*;
import java.io.*;
/**
*
* @author karl
*/
public class Utils {
/** Creates a new instance of Utils */
public static String stripDoubleQuotes (final String s) {
int len = s.length();
String ns = s.substring(1, len-1);
return ns;
}
public static void invariant(boolean c) {
if (false == c) {
Thread.dumpStack();
System.exit(1);
}
}
private final static String stDOT = ".";
public static String getToolRoot() {
String root = System.getProperty("tool.root");
if (null == root) {
root = stDOT;
}
return root;
}
public static void fatal(Exception ex) {
PrintStream err = System.err;
err.print(ex.getMessage());
ex.printStackTrace(err);
System.exit(1);
}
/**Lookup property value.
*
* @param prop property name
* @return true if property exists and set to "true" or else false.
*/
public static boolean getPropertyAsBool(String prop) {
String pv = System.getProperty(prop);
boolean v = (null == pv) ? false : Boolean.parseBoolean(pv);
return v;
}
public static void abnormalExit(Exception ex) {
System.err.println(ex.getMessage());
ex.printStackTrace(System.err);
System.exit(1);
}
public static List<String> arrayToList(String s[]) {
List<String> rval = new LinkedList<String>();
for (String i : s) {
rval.add(i);
}
return rval;
}
public static int streamCopy(BufferedInputStream from, BufferedOutputStream to) throws IOException {
final int bufSz = 2048;
byte buf[] = new byte[bufSz];
int tlCnt = 0, cnt = 0;
while (0 <= (cnt = from.read(buf, 0, bufSz))) {
tlCnt += cnt;
to.write(buf, 0, cnt);
}
to.flush();
return tlCnt;
}
public static String nl() {
return m_nl;
}
public static File findFile(List<File> dirs, String fname, boolean getCanon)
{
File rval = null;
for (File d : dirs)
{
File f = new File(d, fname);
if (f.exists())
{
try {
rval = (getCanon) ? f.getCanonicalFile() : f;
break; //for
} catch (Exception ex) {
//do nothing
}
}
}
return rval;
}
public static File findFile(List<File> dirs, String fname)
{
return findFile(dirs, fname, true);
}
/** Return a null x as an empty collection. */
public static <T> T asEmpty(T x, T empty) {
return (null != x) ? x : empty;
}
private final static String m_nl = System.getProperty("line.separator");
}
| 33.521429
| 104
| 0.448753
|
3f1f755f9906c0b7d0c7826d34d78c7ee747221f
| 4,440
|
/*
* Copyright 2021 The caver-java Authors
*
* Licensed under the Apache License, Version 2.0 (the “License”);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.klaytn.caver.transaction.type.wrapper;
import com.klaytn.caver.rpc.Klay;
import com.klaytn.caver.transaction.type.SmartContractDeploy;
import com.klaytn.caver.wallet.keyring.SignatureData;
import java.util.List;
/**
* Represents a SmartContractDeployWrapper
* 1. This class wraps all of static methods of SmartContractDeploy
* 2. This class should be accessed via `caver.transaction.smartContractDeploy`
*/
public class SmartContractDeployWrapper {
/**
* Klay RPC instance
*/
private Klay klaytnCall;
/**
* Creates a SmartContractDeployWrapper instance.
* @param klaytnCall Klay RPC instance
*/
public SmartContractDeployWrapper(Klay klaytnCall) {
this.klaytnCall = klaytnCall;
}
/**
* Creates a SmartContractDeploy instance derived from a RLP-encoded SmartContractDeploy string.
* @param rlpEncoded RLP-encoded SmartContractDeploy string
* @return SmartContractDeploy
*/
public SmartContractDeploy create(String rlpEncoded) {
SmartContractDeploy smartContractDeploy = SmartContractDeploy.decode(rlpEncoded);
smartContractDeploy.setKlaytnCall(this.klaytnCall);
return smartContractDeploy;
}
/**
* Creates a SmartContractDeploy instance derived from a RLP-encoded SmartContractDeploy byte array.
* @param rlpEncoded RLP-encoded SmartContractDeploy byte array.
* @return SmartContractDeploy
*/
public SmartContractDeploy create(byte[] rlpEncoded) {
SmartContractDeploy smartContractDeploy = SmartContractDeploy.decode(rlpEncoded);
smartContractDeploy.setKlaytnCall(this.klaytnCall);
return smartContractDeploy;
}
/**
* Creates a SmartContractDeploy instance using SmartContractDeploy.Builder
* @param builder SmartContractDeploy.Builder
* @return SmartContractDeploy
*/
public SmartContractDeploy create(SmartContractDeploy.Builder builder) {
builder.setKlaytnCall(this.klaytnCall);
return SmartContractDeploy.create(builder);
}
/**
* Creates a SmartContractDeploy instance.
* @param from The address of the sender.
* @param nonce A value used to uniquely identify a sender’s transaction.
* @param gas The maximum amount of gas the transaction is allowed to use.
* @param gasPrice A unit price of gas in peb the sender will pay for a transaction fee.
* @param chainId Network ID
* @param signatures A Signature list
* @param to The account address that will receive the transferred value.
* @param value The amount of KLAY in peb to be transferred.
* @param input The message data attached to the transaction.
* @param humanReadable Is human-readable address.
* @param codeFormat The code format of smart contract code
* @return SmartContractDeploy
*/
public SmartContractDeploy create(String from, String nonce, String gas, String gasPrice, String chainId, List<SignatureData> signatures, String to, String value, String input, boolean humanReadable, String codeFormat) {
return SmartContractDeploy.create(klaytnCall, from, nonce, gas, gasPrice, chainId, signatures, to, value, input, humanReadable, codeFormat);
}
/**
* Decodes a RLP-encoded SmartContractDeploy string.
* @param rlpEncoded RLP-encoded SmartContractDeploy string
* @return SmartContractDeploy
*/
public SmartContractDeploy decode(String rlpEncoded) {
return SmartContractDeploy.decode(rlpEncoded);
}
/**
* Decodes a RLP-encoded SmartContractDeploy byte array.
* @param rlpEncoded RLP-encoded SmartContractDeploy byte array.
* @return SmartContractDeploy
*/
public SmartContractDeploy decode(byte[] rlpEncoded) {
return SmartContractDeploy.decode(rlpEncoded);
}
}
| 39.642857
| 224
| 0.72973
|
fc66a211e3e9e079462d753d444d646635049c0e
| 172
|
package com.ctrip.soa.caravan.configuration;
/**
* Created by Qiang Zhao on 10/05/2016.
*/
public interface Configuration {
String getPropertyValue(String key);
}
| 15.636364
| 44
| 0.726744
|
6a19628384c6cfb45617d45c92bfa3b7897098d9
| 869
|
package org.omg.hw.equipment;
/**
* Generated from IDL definition of struct "Shelf_T"
* @author JacORB IDL compiler
*/
public final class Shelf_T
implements org.omg.CORBA.portable.IDLEntity
{
public Shelf_T(){}
public java.lang.String name = "";
public java.lang.String equipmentRoomName = "";
public java.lang.String cabinetName = "";
public java.lang.String numbering = "";
public java.lang.String locationOfCabinet = "";
public java.lang.String memo = "";
public Shelf_T(java.lang.String name, java.lang.String equipmentRoomName, java.lang.String cabinetName, java.lang.String numbering, java.lang.String locationOfCabinet, java.lang.String memo)
{
this.name = name;
this.equipmentRoomName = equipmentRoomName;
this.cabinetName = cabinetName;
this.numbering = numbering;
this.locationOfCabinet = locationOfCabinet;
this.memo = memo;
}
}
| 31.035714
| 191
| 0.749137
|
4dad4f6cabfce969a321169105c81e892721ba36
| 1,750
|
package a.yoreni.potioneffectmod;
import net.fabricmc.api.ModInitializer;
import net.minecraft.text.TranslatableText;
public class Potioneffectmod implements ModInitializer
{
@Override
public void onInitialize()
{
}
/**
* Converts game ticks in to human readable time format
* This will be used to display static effect durations
*
* @param ticks
* @return
*/
public static String formatTime(int ticks)
{
// handles negative inputs
if(ticks < 0)
{
return "-" + formatTime(ticks * -1);
}
int s = (ticks / 20) % 60;
int m = (ticks / (20 * 60)) % 60;
int h = (ticks / (20 * 60 * 60));
if(h == 0) //mins-secs format
{
String text = new TranslatableText("potioneffectmod.time.minsecFormat").getString();
// we have to replace it cos we dont want the TranslatableText object to handle the % cos it
// does a bad job at it you cant put extra options such as 0 padding in it but you can with
// String.format . If we do this this gives the translater more power and can localise the
// time formatter better.
text = text.replaceAll("!","%");
return String.format(text, m, s);
}
else if(h < 100) //hrs-mins format
{
String text = new TranslatableText("potioneffectmod.time.hrminFormat").getString();
text = text.replaceAll("!","%");
return String.format(text, h, m);
}
else //we will return infinity if the effect is longer than 100 hours
{
return new TranslatableText("potioneffectmod.time.forever").getString();
}
}
}
| 32.407407
| 104
| 0.582857
|
645f10e7735039e677882e7d2e182cf21812789d
| 427
|
package com.thoughtworks.forecastAlexaSkillBackend.interceptors;
import com.amazon.ask.dispatcher.request.handler.HandlerInput;
import com.amazon.ask.dispatcher.request.interceptor.RequestInterceptor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class LogRequestInterceptor implements RequestInterceptor {
@Override
public void process(HandlerInput input) {
log.info(input.getRequestEnvelope().toString());
}
}
| 28.466667
| 72
| 0.819672
|
7ba321606ee5778f25847c8e237ce6ffe6443092
| 1,244
|
package com.tekwill.hints.inheritance.exceptions.book.controller;
import com.tekwill.hints.inheritance.exceptions.book.domain.Book;
import com.tekwill.hints.inheritance.exceptions.book.domain.exceptions.BookNotFoundCheckedException;
import com.tekwill.hints.inheritance.exceptions.book.domain.exceptions.ISBNNotSupportedRuntimeException;
import com.tekwill.hints.inheritance.exceptions.book.service.BookService;
public class BookController {
private final BookService bookService;
public BookController(BookService bookService) {
this.bookService = bookService;
}
public void renderViewBookByISBNPage(String isbn) {
//tryToFindLanguage
if (isbn.length() > 10)
throw new ISBNNotSupportedRuntimeException("ISBN not supported");
try {
Book bookByIsbn = bookService.getBookByIsbn(isbn);
System.out.println("<h1>Book by ISBN page</h1><p>" + bookByIsbn + "</p>");
} catch (BookNotFoundCheckedException e) {
// System.out.println(e.getMessage()); log it at DEBUG level to a file
System.out.println("<h1>Book by ISBN page</h1><p>N/A</p>");
} finally {
System.out.println("<nav>tekwill</nav>");
}
}
}
| 40.129032
| 104
| 0.698553
|
1370df2feeb526aede82fa3d552e575b86c8c357
| 892
|
package com.knits.coreplatform.service.dto;
import static org.assertj.core.api.Assertions.assertThat;
import com.knits.coreplatform.web.rest.TestUtil;
import org.junit.jupiter.api.Test;
class ApplicationDTOTest {
@Test
void dtoEqualsVerifier() throws Exception {
TestUtil.equalsVerifier(ApplicationDTO.class);
ApplicationDTO applicationDTO1 = new ApplicationDTO();
applicationDTO1.setId(1L);
ApplicationDTO applicationDTO2 = new ApplicationDTO();
assertThat(applicationDTO1).isNotEqualTo(applicationDTO2);
applicationDTO2.setId(applicationDTO1.getId());
assertThat(applicationDTO1).isEqualTo(applicationDTO2);
applicationDTO2.setId(2L);
assertThat(applicationDTO1).isNotEqualTo(applicationDTO2);
applicationDTO1.setId(null);
assertThat(applicationDTO1).isNotEqualTo(applicationDTO2);
}
}
| 35.68
| 66
| 0.744395
|
2ef3903e067d2a0cc8b2938bda24e43f690a6880
| 1,965
|
package org.swingeasy;
import java.awt.Dimension;
import java.awt.Point;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
import net.miginfocom.swing.MigLayout;
/**
* @author Jurgen
*/
public class ComboboxAutoResizeDemo {
public static void main(String[] args) {
Point location = null;
EComboBoxConfig cfg = new EComboBoxConfig();
cfg.setAutoResizePopup(true);
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
EComboBox<String> combo = new EComboBox<>(cfg);
Dimension dim = new Dimension(100, 20);
combo.setMaximumSize(dim);
combo.setPreferredSize(dim);
combo.setSize(dim);
combo.stsi().addRecord(new EComboBoxRecord<>("azertyuiopqsdfghjklmwxcvbn0123456789"));
frame.getContentPane().add(combo);
frame.setSize(new Dimension(100, 70));
frame.setLocationRelativeTo(null);
frame.setTitle("ComboboxAutoResizeDemo (borderlayout)");
frame.setVisible(true);
location = frame.getLocation();
}
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
EComboBox<String> combo = new EComboBox<>(cfg);
Dimension dim = new Dimension(100, 20);
combo.setMaximumSize(dim);
combo.setPreferredSize(dim);
combo.setSize(dim);
combo.stsi().addRecord(new EComboBoxRecord<>("azertyuiopqsdfghjklmwxcvbn0123456789"));
frame.getContentPane().setLayout(new MigLayout());
frame.getContentPane().add(combo);
frame.setSize(new Dimension(100, 70));
location.y += 150;
frame.setLocation(location);
frame.setTitle("ComboboxAutoResizeDemo (miglayout)");
frame.setVisible(true);
}
}
}
| 36.388889
| 98
| 0.619338
|
04b703199814ad127bf919019ee73122d08022d3
| 3,778
|
package dao;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import beans.Role;
import beans.Task;
import beans.User;
import beans.UserLeaves;
import factory.HSFactory;
public class UsersHibDAO implements UsersDAO {
Session s;
public UsersHibDAO() {
try {
s=HSFactory.getSession();
}
catch(Exception e) {
e.printStackTrace();
}
}
public int addRole(String rname) {
int rid=0;
try {
Transaction t =s.beginTransaction();
Role r=new Role(0,rname);
s.save(r);
s.flush();
t.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rid;
}
public List roleListing() {
List list=new ArrayList();
try {
Query q=s.createQuery("FROM Role");
list=q.list();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
public int addUser(User user) {
// pk generation
int usrid=0;
try {
Transaction t =s.beginTransaction();
s.save(user);
s.flush();
t.commit();
usrid=user.getUsrid();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return usrid;
}
public List userListing() {
List<User> list=new ArrayList();
try {
Query q = s.createQuery("FROM User");
list = q.list();
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
public boolean applyLeave(int usrid, String leaveType, int noOfDays) {
boolean flag=false;
try {
Transaction t=s.beginTransaction();
Query q=s.createQuery("FROM UserLeaves WHERE usrid="+usrid);
UserLeaves ul=(UserLeaves)q.uniqueResult();
if(leaveType.equalsIgnoreCase("cl")) {
ul.setClleft(ul.getClleft()-noOfDays);
} else {
ul.setElleft(ul.getElleft()-noOfDays);
}
s.update(ul);
s.flush();
t.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flag;
}
public List myLeaveList(int usrid) {
List list=new ArrayList();
try {
Query q=s.createQuery("SELECT ul.clleft, ul.elleft FROM UserLeaves ul WHERE usrid="+usrid);
Object o[]=(Object[])q.uniqueResult();
System.out.println(o.getClass().getName());
list.add(o[0]);
list.add(o[1]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
public List leaveListing() {
List<UserLeaves> list=new ArrayList();
try {
Query q=s.createQuery("FROM UserLeaves");
list=q.list();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
public int addTask(int usrid, String tdetail) {
int tid=0;
try {
Transaction t=s.beginTransaction();
Task t1=new Task(0, tdetail, usrid);
s.save(t1);
s.flush();
t.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return tid;
}
public List myTaskListing(int usrid) {
List<Task> list=new ArrayList();
try {
Query q=s.createQuery("FROM Task WHERE usrid="+usrid);
list=q.list();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
public List allTaskListing() {
List<Task> list=new ArrayList();
try {
Query q=s.createQuery("FROM Task");
list=q.list();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
}
| 21.965116
| 95
| 0.617522
|
d5a0f5b84c3c3e78b8983b3e57545b95428f1c43
| 560
|
package p02_Blob.models.behavors;
import p02_Blob.models.Blob;
public class Inflated extends AbstractBehavior {
private static final int INFLATED_HEALTH_DECREMENT = 10;
private static final int INFLATED_HEALTH_POINTS = 50;
public Inflated() {
super();
}
@Override
protected void applyTriggerEffect(Blob source) {
source.setHealth(source.getHealth() + INFLATED_HEALTH_POINTS);
}
@Override
public void takeTriggerEffect(Blob source) {
if (super.isTriggered()) {
source.setHealth(source.getHealth() - INFLATED_HEALTH_DECREMENT);
}
}
}
| 20.740741
| 68
| 0.760714
|
7a47d9efe5b5e7004a1a08cf073edcd0cba7a28c
| 175
|
package com.prathab.data.base.exception;
/**
* Any DB operation can only throw this Exception
*
* @author jmprathab
*
*/
public class DbException extends Exception {
}
| 15.909091
| 49
| 0.72
|
4f024462e4ad302751baaae193c84d59d9fe3061
| 1,311
|
package com.chuhelan.netex.dao;
import com.chuhelan.netex.domain.WorkOrder;
import org.apache.ibatis.annotations.*;
import java.util.Date;
/**
* @Version: 1.0
* @Date: 2021/6/5 下午 04:14
* @ClassName: WorkOrderDao
* @Author: Stapxs
* @Description TO DO
**/
@Mapper
public interface WorkOrderDao {
// Select
@Select("select * from netex_workorder where workOrder_userID=#{id}")
public WorkOrder[] getAllWOrderByUID(Integer id);
@Select("select * from netex_workorder where workOrder_endWay=0")
public WorkOrder[] getAllNoCloseOrder();
// Update
@Update("update netex_workorder set workOrder_dieDate=#{endDate}, workOrder_endContent=#{backStr}, workOrder_serviceID=#{serviceID}, workOrder_endWay=#{way} where workOrder_id=#{workOrderID}")
public void detalWorkOrder(@Param("workOrderID") Integer workOrderID, @Param("endDate") Date endDate, @Param("backStr") String backStr, @Param("serviceID") Integer serviceID, @Param("way") Integer way);
// Insert
@Insert("insert into netex_workorder ( workOrder_userID, workOrder_orderId, workOrder_date, workOrder_content ) values ( #{uid}, #{oid}, #{date}, #{content} )")
public void addWorkOrder(@Param("uid") Integer uid, @Param("oid") String oid, @Param("date") Date date, @Param("content") String content);
}
| 36.416667
| 206
| 0.720824
|
6c2d8942e902a722e25d0c128b9e8646a90c9daf
| 1,500
|
/***************************************************************************
* Copyright 2021 Kieker Project (http://kieker-monitoring.net)
*
* 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 kieker.analysis.trace.execution;
import kieker.model.system.model.ExecutionTrace;
/**
* @author Andre van Hoorn
*
* @since 1.2
*/
abstract class AbstractExecutionTraceHashContainer { // NOPMD (abstract class without abstract methods)
private final ExecutionTrace executionTrace;
/**
* Abstract constructor to initialize the container.
*
* @param t
* The execution trace to be stored in this container.
*/
public AbstractExecutionTraceHashContainer(final ExecutionTrace t) {
this.executionTrace = t;
}
/**
* Delivers the stored execution trace.
*
* @return The content of this container.
*/
public ExecutionTrace getExecutionTrace() {
return this.executionTrace;
}
}
| 31.25
| 103
| 0.66
|
ebc6aeb8e495343bad69dc5f8ebd05f7e86de38d
| 413
|
package com.xw.spring.jsonrpc;
import com.xw.spring.tag.JsonrpcTag;
import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
/**
* Created by huangdongbin on 2018/4/10.
*/
public class JsonrpcNameSpaceHandler extends NamespaceHandlerSupport {
@Override
public void init() {
registerBeanDefinitionParser("jsonrpc", new JsonrpcBeanDefinitionParser(JsonrpcTag.class,false));
}
}
| 27.533333
| 105
| 0.769976
|
5ecf367d6958bb6a3e84091b785a06e485a67545
| 6,085
|
/*
* Copyright <2020> 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://www.apache.org/licenses/LICENSE-2.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 software.amazon.timestream.jdbc;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.ImmutableList;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
/**
* Class handling Azure AD SSO.
*/
class TimestreamAzureADCredentialsProvider extends TimestreamSAMLCredentialsProvider {
private final String appID;
private final String clientSecret;
private final String tenantID;
/**
* Constructor for {@link TimestreamAzureADCredentialsProvider}.
*
* @param httpClient The HTTP Client to be used during SAML Authentication.
* @param azureADFieldsMap A {@link Map} including the following required parameters:
* <ol>
* <li>userName: The user name for the specified IdP account.
* <li>password: The password for the specified IdP account.
* <li>roleARN: The Amazon Resource Name (ARN) of the role that the caller is assuming.
* <li>idpARN: The Amazon Resource Name (ARN) of the SAML provider in IAM that describes the IdP.
* <li>appID: The unique id of the registered application on Azure AD.
* <li>clientSecret: The client secret associated with the registered application on Azure AD used to authorize fetching tokens.
* <li>tenantID: The Azure AD Tenant ID.
* </li></ol>
*/
TimestreamAzureADCredentialsProvider(CloseableHttpClient httpClient, final Map<String, String> azureADFieldsMap) {
super(httpClient, azureADFieldsMap);
this.appID = azureADFieldsMap.get(TimestreamConnectionProperty.AAD_APP_ID.getConnectionProperty());
this.clientSecret = azureADFieldsMap.get(TimestreamConnectionProperty.AAD_CLIENT_SECRET.getConnectionProperty());
this.tenantID = azureADFieldsMap.get(TimestreamConnectionProperty.AAD_TENANT_ID.getConnectionProperty());
}
/**
* Constructs the SAML Assertion with the access token.
*
* @return The SAML assertion needed to get temporary credentials from AWS.
* @throws SQLException if unable to parse the response body or the request fails.
*/
@Override
protected String getSAMLAssertion() throws SQLException {
final String accessToken = getAccessToken();
final String assertion = "<samlp:Response xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\">"
+ "<samlp:Status>"
+ "<samlp:StatusCode Value=\"urn:oasis:names:tc:SAML:2.0:status:Success\"/>"
+ "</samlp:Status>"
+ new String(Base64.decodeBase64(accessToken), StandardCharsets.UTF_8)
+ "</samlp:Response>";
return new String(Base64.encodeBase64(assertion.getBytes(StandardCharsets.UTF_8)),
StandardCharsets.UTF_8);
}
/**
* Fetches an access token from Azure AD Oauth2 endpoint using the provided properties.
*
* @return The fetched access token from Azure AD.
* @throws SQLException if unable to parse the response body or the request fails.
*/
private String getAccessToken() throws SQLException {
final String accessTokenEndpoint = "https://login.microsoftonline.com/" + this.tenantID + "/oauth2/token";
final List<BasicNameValuePair> requestParameters =
ImmutableList.of(new BasicNameValuePair("grant_type", "password"),
new BasicNameValuePair("requested_token_type", "urn:ietf:params:oauth:token-type:saml2"),
new BasicNameValuePair("username", userName),
new BasicNameValuePair("password", password),
new BasicNameValuePair("client_secret", clientSecret),
new BasicNameValuePair("client_id", appID),
new BasicNameValuePair("resource", appID));
final HttpUriRequest accessTokenRequest = RequestBuilder
.post()
.setUri(accessTokenEndpoint)
.addHeader("Accept", "application/json")
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.setEntity(new UrlEncodedFormEntity(requestParameters, StandardCharsets.UTF_8))
.build();
try (CloseableHttpResponse response = this.httpClient.execute(accessTokenRequest)) {
final StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
throw Error.createSQLException(LOGGER, Error.AAD_ACCESS_TOKEN_REQUEST_FAILED);
}
final HttpEntity responseEntity = response.getEntity();
final String responseString = EntityUtils.toString(responseEntity, "UTF-8");
final JsonNode jsonNode = OBJECT_MAPPER.readTree(responseString).get("access_token");
if (jsonNode == null) {
throw Error.createSQLException(LOGGER, Error.INVALID_AAD_ACCESS_TOKEN_RESPONSE);
}
return jsonNode.asText();
} catch (IOException e) {
throw Error.createSQLException(LOGGER, e, Error.AAD_ACCESS_TOKEN_ERROR);
}
}
}
| 47.170543
| 154
| 0.71931
|
cdab707df415ea8e70c9a3e07559f6ec6af11e8d
| 8,292
|
/*
* Copyright 2015-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package be.ordina.msdashboard.applicationinstance;
import java.net.URI;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import reactor.core.publisher.Mono;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.LinkDiscoverer;
import org.springframework.hateoas.LinkDiscoverers;
import org.springframework.hateoas.MediaTypes;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClient;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.verify;
import static org.mockito.BDDMockito.verifyNoMoreInteractions;
import static org.mockito.BDDMockito.when;
import static org.mockito.Mockito.times;
/**
* @author Tim Ysewyn
*/
@RunWith(MockitoJUnitRunner.class)
public class HalActuatorEndpointsDiscovererTests {
@Mock
private WebClient webClient;
@Mock
private WebClient.RequestHeadersUriSpec requestHeadersUriSpec;
@Mock
private WebClient.RequestHeadersSpec requestHeadersSpec;
@Mock
private ClientResponse clientResponse;
@Mock
private LinkDiscoverers linkDiscoverers;
@Mock
private LinkDiscoverer linkDiscoverer;
@InjectMocks
private HalActuatorEndpointsDiscoverer discoverer;
private ApplicationInstance applicationInstance;
@Before
public void setup() {
this.applicationInstance = ApplicationInstanceMother.instance("a-1", "a");
when(this.webClient.get()).thenReturn(this.requestHeadersUriSpec);
when(this.requestHeadersUriSpec.uri(any(URI.class))).thenReturn(this.requestHeadersSpec);
when(this.requestHeadersSpec.exchange()).thenReturn(Mono.just(this.clientResponse));
when(this.linkDiscoverers.getLinkDiscovererFor(any(MediaType.class)))
.thenReturn(this.linkDiscoverer);
}
@Test
public void shouldReturnEmptyListWhenUrlWasNotResolved() {
when(this.clientResponse.toEntity(String.class))
.thenReturn(Mono.just(ResponseEntity.notFound().build()));
this.discoverer.findActuatorEndpoints(this.applicationInstance)
.subscribe(actuatorEndpoints -> {
verify(this.webClient).get();
verifyNoMoreInteractions(this.webClient);
assertThat(actuatorEndpoints).isEmpty();
});
}
@Test
public void shouldReturnEmptyListWhenNoBodyHasBeenSent() {
when(this.clientResponse.toEntity(String.class))
.thenReturn(Mono.just(ResponseEntity.ok().build()));
this.discoverer.findActuatorEndpoints(this.applicationInstance)
.subscribe(actuatorEndpoints -> {
verify(this.webClient).get();
verifyNoMoreInteractions(this.webClient);
assertThat(actuatorEndpoints).isEmpty();
});
}
@Test
public void shouldReturnEmptyListWhenBodyIsEmpty() {
when(this.clientResponse.toEntity(String.class))
.thenReturn(Mono.just(ResponseEntity.ok("")));
this.discoverer.findActuatorEndpoints(this.applicationInstance)
.subscribe(actuatorEndpoints -> {
verify(this.webClient).get();
verifyNoMoreInteractions(this.webClient);
assertThat(actuatorEndpoints).isEmpty();
});
}
@Test
public void shouldReturnEmptyListWhenNoLinkInResponse() {
when(this.clientResponse.toEntity(String.class))
.thenReturn(Mono.just(ResponseEntity.ok("{ }")));
this.discoverer.findActuatorEndpoints(this.applicationInstance)
.subscribe(actuatorEndpoints -> {
verify(this.webClient).get();
verifyNoMoreInteractions(this.webClient);
assertThat(actuatorEndpoints).isEmpty();
});
}
@Test
public void shouldReturnEmptyListWhenNoRelsInResponse() {
when(this.clientResponse.toEntity(String.class))
.thenReturn(Mono.just(ResponseEntity.ok("{ _links: [] }")));
this.discoverer.findActuatorEndpoints(this.applicationInstance)
.subscribe(actuatorEndpoints -> {
verify(this.webClient).get();
verifyNoMoreInteractions(this.webClient);
assertThat(actuatorEndpoints).isEmpty();
});
}
@Test
public void shouldReturnListWithDiscoveredEndpointsFromResponse() {
String body = "{\"_links\":{\"self\":{\"href\":\"http://localhost:8080/actuator\",\"templated\":false},\"health-component-instance\":{\"href\":\"http://localhost:8080/actuator/health/{component}/{instance}\",\"templated\":true},\"health-component\":{\"href\":\"http://localhost:8080/actuator/health/{component}\",\"templated\":true},\"health\":{\"href\":\"http://localhost:8080/actuator/health\",\"templated\":false},\"info\":{\"href\":\"http://localhost:8080/actuator/info\",\"templated\":false}}}";
when(this.clientResponse.toEntity(String.class))
.thenReturn(Mono.just(ResponseEntity.ok(body)));
when(this.linkDiscoverers.getLinkDiscovererFor(MediaTypes.HAL_JSON_UTF8))
.thenReturn(this.linkDiscoverer);
when(this.linkDiscoverer.findLinkWithRel("self", body))
.thenReturn(new Link("http://localhost:8080/actuator", "self"));
when(this.linkDiscoverer.findLinkWithRel("health-component-instance", body))
.thenReturn(new Link("http://localhost:8080/actuator/health/{component}/instance/{instance}", "health-component-instance"));
when(this.linkDiscoverer.findLinkWithRel("health-component", body))
.thenReturn(new Link("http://localhost:8080/actuator/health/{component}", "health-component"));
when(this.linkDiscoverer.findLinkWithRel("health", body))
.thenReturn(new Link("http://localhost:8080/actuator/health", "health"));
when(this.linkDiscoverer.findLinkWithRel("info", body))
.thenReturn(new Link("http://localhost:8080/actuator/info", "info"));
this.discoverer.findActuatorEndpoints(this.applicationInstance)
.subscribe(actuatorEndpoints -> {
assertThat(actuatorEndpoints).hasSize(5);
verify(this.webClient).get();
verifyNoMoreInteractions(this.webClient);
verify(this.requestHeadersSpec).exchange();
verifyNoMoreInteractions(this.requestHeadersSpec);
verify(this.requestHeadersUriSpec).uri(URI.create("http://localhost:8080/actuator"));
verifyNoMoreInteractions(this.requestHeadersUriSpec);
verify(this.clientResponse).toEntity(String.class);
verifyNoMoreInteractions(this.clientResponse);
verify(this.linkDiscoverers, times(5)).getLinkDiscovererFor(MediaTypes.HAL_JSON_UTF8);
verifyNoMoreInteractions(this.linkDiscoverers);
verify(this.linkDiscoverer).findLinkWithRel("self", body);
verify(this.linkDiscoverer).findLinkWithRel("health-component-instance", body);
verify(this.linkDiscoverer).findLinkWithRel("health-component", body);
verify(this.linkDiscoverer).findLinkWithRel("health", body);
verify(this.linkDiscoverer).findLinkWithRel("info", body);
verifyNoMoreInteractions(this.linkDiscoverer);
});
}
@Test
public void shouldReturnAnEmptyMonoWhenSomethingGoesWrong() {
when(this.clientResponse.toEntity(String.class))
.thenReturn(Mono.error(new RuntimeException("OOPSIE")));
this.discoverer.findActuatorEndpoints(this.applicationInstance)
.subscribe(actuatorEndpoints -> {
assertThat(actuatorEndpoints).isEmpty();
verify(this.webClient).get();
verifyNoMoreInteractions(this.webClient);
verify(this.requestHeadersSpec).exchange();
verifyNoMoreInteractions(this.requestHeadersSpec);
verify(this.requestHeadersUriSpec).uri(URI.create("http://localhost:8080/actuator"));
verifyNoMoreInteractions(this.requestHeadersUriSpec);
verify(this.clientResponse).toEntity(String.class);
verifyNoMoreInteractions(this.clientResponse);
});
}
}
| 39.113208
| 502
| 0.764472
|
e9a225f3639fc22d6762a3da63a225f0c714c606
| 5,452
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.dev.betaTransporte;
import com.dev.betaTransporte.dao.GenericoDAO;
import com.dev.betaTransporte.negocio.UsuarioNegocio;
import com.dev.betaTransporte.negocio.exception.LoginException;
import java.awt.Desktop;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javax.persistence.EntityManager;
import util.BoxInfo;
import util.Message;
/**
* FXML Controller class
*
* @author Henrique
*/
public class LoginController implements Initializable {
@FXML
private TextField txtLogin;
@FXML
private PasswordField txtSenha;
@FXML
private Hyperlink hypEsqueceuSenha;
@FXML
private Button btnCancelar;
@FXML
private StackPane stcLogin;
@FXML
private Button btnEntrar;
Message msg = new Message();
BoxInfo box = new BoxInfo();
EntityManager em;
GenericoDAO dao;
void complete_erros(LoginException ex) {
final String COR = "-fx-border-color:red";
final String NORMAL = "-fx-border-color:darkgrey";
final String NONE = "-fx-border-color:none";
if (ex.getUsuario()) {
this.txtLogin.setStyle(COR);
} else {
this.txtLogin.setStyle(NORMAL);
}
if (ex.getSenha()) {
this.txtSenha.setStyle(COR);
} else {
this.txtSenha.setStyle(NORMAL);
}
if (ex.getMsg().length() > 0) {
box.BoxInfo(Alert.AlertType.WARNING, Message.message("err.title.login"), Message.message(ex.getMsg()));
}
}
void Login() {
UsuarioNegocio authenticated = new UsuarioNegocio();
try {
LoginException isValid = authenticated.Login(txtLogin.getText(), txtSenha.getText());
complete_erros(isValid);
if (isValid.getMsg().length() == 0) {
// Parent root = FXMLLoader.load(getClass().getResource("/gui/Main.fxml"), ResourceBundle.getBundle("docs/i18N_pt_BR"));
Parent root = FXMLLoader.load(getClass().getResource("/gui/Main.fxml"), ResourceBundle.getBundle("docs/i18N_pt_BR"));
Scene scene = new Scene(root);
Stage stage = new Stage();
stage.setMaximized(true);
scene.getStylesheets().add("/styles/Styles.css");
stage.setTitle(msg.message("TituloSistema"));
stage.getIcons().add(new Image("./img/IMG_01_LogoBetaTransportePNG.PNG"));
stage.setScene(scene);
MainApp.primaryStage.close();
stage.show();
}
} catch (Exception ex) {
System.err.println(ex.getMessage());
}
}
@FXML
void onActionLogin(ActionEvent event) {
Login();
}
@FXML
void onActionSair(ActionEvent event) {
System.exit(0);
}
@FXML
void inputLogin(KeyEvent event) {
if (txtLogin.getText().length() > 0 && txtSenha.getText().length() > 0) {
btnEntrar.setDisable(false);
} else {
btnEntrar.setDisable(true);
}
if (event.getCode() == KeyCode.ENTER) {
Login();
}
}
@FXML
void inputSenha(KeyEvent event) {
if (txtLogin.getText().length() > 0 && txtSenha.getText().length() > 0) {
btnEntrar.setDisable(false);
} else {
btnEntrar.setDisable(true);
}
if (event.getCode() == KeyCode.ENTER) {
Login();
}
}
@FXML
void onKeyPressedSair(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
System.exit(0);
}
}
@FXML
void onKeyPressedLogin(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
Login();
}
}
void esqueceuSenha() {
try {
Desktop.getDesktop().browse(new URI("https://github.com/henriquehrf/BetaTransporte"));
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
@FXML
void onKeyPressedEsqSenha(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
esqueceuSenha();
}
}
@FXML
void hypOnAction(ActionEvent event) {
esqueceuSenha();
}
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
btnEntrar.setDisable(true);
}
}
| 26.990099
| 136
| 0.592627
|
dd728a64a76d5e0994491a39ea9628e20f956f57
| 7,902
|
/*
* This file is part of ELKI:
* Environment for Developing KDD-Applications Supported by Index-Structures
*
* Copyright (C) 2019
* ELKI Development Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.lmu.ifi.dbs.elki.datasource.filter.transform;
import static de.lmu.ifi.dbs.elki.math.linearalgebra.VMath.plusTimesEquals;
import static de.lmu.ifi.dbs.elki.math.linearalgebra.VMath.times;
import de.lmu.ifi.dbs.elki.data.NumberVector;
import de.lmu.ifi.dbs.elki.data.type.SimpleTypeInformation;
import de.lmu.ifi.dbs.elki.data.type.TypeUtil;
import de.lmu.ifi.dbs.elki.data.type.VectorFieldTypeInformation;
import de.lmu.ifi.dbs.elki.datasource.filter.AbstractVectorConversionFilter;
import de.lmu.ifi.dbs.elki.logging.Logging;
import de.lmu.ifi.dbs.elki.math.linearalgebra.CovarianceMatrix;
import de.lmu.ifi.dbs.elki.math.linearalgebra.pca.EigenPair;
import de.lmu.ifi.dbs.elki.math.linearalgebra.pca.PCAResult;
import de.lmu.ifi.dbs.elki.math.linearalgebra.pca.PCARunner;
import de.lmu.ifi.dbs.elki.math.linearalgebra.pca.filter.EigenPairFilter;
import de.lmu.ifi.dbs.elki.utilities.Alias;
import de.lmu.ifi.dbs.elki.utilities.Priority;
import de.lmu.ifi.dbs.elki.utilities.exceptions.AbortException;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.AbstractParameterizer;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.EnumParameter;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.ObjectParameter;
import net.jafama.FastMath;
/**
* Apply Principal Component Analysis (PCA) to the data set.
* <p>
* This is also popular form of "Whitening transformation", and will project the
* data to have a unit covariance matrix.
* <p>
* If you want to also reduce dimensionality, set the {@code -pca.filter}
* parameter! Note that this implementation currently will always perform a full
* matrix inversion. For very high dimensional data, this can take an excessive
* amount of time O(d³) and memory O(d²). Please contribute a better
* implementation to ELKI that only computes the requiried dimensions, yet
* allows for the same filtering flexibility.
* <p>
* TODO: design an API (and implementation) that allows plugging in efficient
* solvers that do not need to decompose the entire matrix. This may, however,
* require external dependencies such as jBlas.
*
* @author Erich Schubert
* @since 0.5.0
*
* @composed - - - PCARunner
* @composed - - - CovarianceMatrix
* @composed - - - EigenPairFilter
*
* @param <O> Vector type
*/
@Alias({ "whiten", "whitening", "pca" })
@Priority(Priority.RECOMMENDED)
public class GlobalPrincipalComponentAnalysisTransform<O extends NumberVector> extends AbstractVectorConversionFilter<O, O> {
/**
* Class logger.
*/
private static final Logging LOG = Logging.getLogger(GlobalPrincipalComponentAnalysisTransform.class);
/**
* Transformation mode.
*/
public enum Mode {
/** Center, rotate, and scale */
FULL,
/** Center and rotate */
CENTER_ROTATE,
}
/**
* Filter to use for dimensionality reduction.
*/
EigenPairFilter filter = null;
/**
* Covariance matrix builder.
*/
CovarianceMatrix covmat = null;
/**
* Final projection after analysis run.
*/
double[][] proj = null;
/**
* Projection buffer.
*/
double[] buf = null;
/**
* Vector for data set centering.
*/
double[] mean = null;
/**
* Mode.
*/
Mode mode;
/**
* Constructor.
*
* @param filter Filter to use for dimensionality reduction.
*/
public GlobalPrincipalComponentAnalysisTransform(EigenPairFilter filter) {
this(filter, Mode.FULL);
}
/**
* Constructor.
*
* @param filter Filter to use for dimensionality reduction.
* @param mode Mode
*/
public GlobalPrincipalComponentAnalysisTransform(EigenPairFilter filter, Mode mode) {
super();
this.filter = filter;
this.mode = mode;
}
@Override
protected boolean prepareStart(SimpleTypeInformation<O> in) {
if(!(in instanceof VectorFieldTypeInformation)) {
throw new AbortException("PCA can only applied to fixed dimensionality vectors");
}
int dim = ((VectorFieldTypeInformation<?>) in).getDimensionality();
covmat = new CovarianceMatrix(dim);
proj = null;
mean = null;
return true;
}
@Override
protected void prepareProcessInstance(O obj) {
covmat.put(obj);
}
@Override
protected void prepareComplete() {
mean = covmat.getMeanVector();
PCAResult pcares = (new PCARunner(null)).processCovarMatrix(covmat.destroyToPopulationMatrix());
covmat = null;
final int dim = mean.length;
final int pdim = filter != null ? filter.filter(pcares.getEigenvalues()) : dim;
if(filter != null && LOG.isVerbose()) {
LOG.verbose("Reducing dimensionality from " + dim + " to " + pdim + " via PCA.");
}
// Build the projection matrux
proj = new double[pdim][dim];
for(int d = 0; d < pdim; d++) {
EigenPair ep = pcares.getEigenPairs()[d];
plusTimesEquals(proj[d], ep.getEigenvector(), mode == Mode.FULL ? 1. / FastMath.sqrt(ep.getEigenvalue()) : 1.);
}
buf = new double[dim];
}
@Override
protected O filterSingleObject(O obj) {
// Shift by mean and copy to scratch buffer
for(int i = 0; i < mean.length; i++) {
buf[i] = obj.doubleValue(i) - mean[i];
}
return factory.newNumberVector(times(proj, buf));
}
@Override
protected SimpleTypeInformation<? super O> getInputTypeRestriction() {
return TypeUtil.NUMBER_VECTOR_FIELD;
}
@Override
protected SimpleTypeInformation<? super O> convertedType(SimpleTypeInformation<O> in) {
initializeOutputType(in);
return new VectorFieldTypeInformation<>(factory, proj.length);
}
@Override
protected Logging getLogger() {
return LOG;
}
/**
* Parameterization class.
*
* @author Erich Schubert
*/
public static class Parameterizer<O extends NumberVector> extends AbstractParameterizer {
/**
* To specify the eigenvectors to keep.
*/
public static final OptionID FILTER_ID = new OptionID("globalpca.filter", "Filter to use for dimensionality reduction.");
/**
* Mode control.
*/
public static final OptionID MODE_ID = new OptionID("globalpca.mode", "Operation mode: full, or rotate only.");
/**
* Filter to use for dimensionality reduction.
*/
EigenPairFilter filter = null;
/**
* Mode.
*/
Mode mode;
@Override
protected void makeOptions(Parameterization config) {
super.makeOptions(config);
ObjectParameter<EigenPairFilter> filterP = new ObjectParameter<>(FILTER_ID, EigenPairFilter.class, true);
if(config.grab(filterP)) {
filter = filterP.instantiateClass(config);
}
EnumParameter<Mode> modeP = new EnumParameter<>(MODE_ID, Mode.class, Mode.FULL);
if(config.grab(modeP)) {
mode = modeP.getValue();
}
}
@Override
protected GlobalPrincipalComponentAnalysisTransform<O> makeInstance() {
return new GlobalPrincipalComponentAnalysisTransform<>(filter, mode);
}
}
}
| 31.608
| 125
| 0.707163
|
016e6d1db58b9d3683cdc2532270545e983cd4f6
| 3,786
|
package com.mattiasselin.linewriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BufferingLineWriter implements ILineWriter, ILineSource {
private final IIdGenerator idGenerator;
private final List<ICommand> bufferedCommands;
private final String id;
public BufferingLineWriter() {
this(new IIdGenerator() {
private int nextId = 0;
@Override
public String newId() {
return String.valueOf(nextId++);
}
}, new ArrayList<ICommand>());
}
protected BufferingLineWriter(IIdGenerator idGenerator, List<ICommand> bufferedCommands) {
this.idGenerator = idGenerator;
this.bufferedCommands = bufferedCommands;
this.id = idGenerator.newId();
}
@Override
public void writeTo(ILineWriter lineWriter) {
ExecutionContext context = new ExecutionContext();
context.registerImplementation(id, lineWriter);
for(ICommand bufferedCommand: bufferedCommands) {
bufferedCommand.execute(context);
}
}
@Override
public void indent() {
bufferedCommands.add(new SimpleCommand() {
@Override
public void writeTo(ILineWriter lineWriter) {
lineWriter.indent();
}
});
}
@Override
public void unindent() {
bufferedCommands.add(new SimpleCommand() {
@Override
public void writeTo(ILineWriter lineWriter) {
lineWriter.unindent();
}
});
}
@Override
public ILineWriter indented() {
BufferingLineWriter indentedWriter = newBufferingLineWriter(idGenerator, bufferedCommands);
final String indentedId = indentedWriter.id;
bufferedCommands.add(new ICommand() {
@Override
public void execute(IExecutionContext executionContext) {
ILineWriter lineWriter = executionContext.getImplementation(id);
executionContext.registerImplementation(indentedId, lineWriter.indented());
}
});
return indentedWriter;
}
protected BufferingLineWriter newBufferingLineWriter(IIdGenerator idGenerator, List<ICommand> bufferedCommands) {
return new BufferingLineWriter(idGenerator, bufferedCommands);
}
@Override
public ILineWriter print(final String text) {
bufferedCommands.add(new SimpleCommand() {
@Override
public void writeTo(ILineWriter lineWriter) {
lineWriter.print(text);
}
});
return this;
}
@Override
public void println() {
bufferedCommands.add(new SimpleCommand() {
@Override
public void writeTo(ILineWriter lineWriter) {
lineWriter.println();
}
});
}
@Override
public void println(final String text) {
bufferedCommands.add(new SimpleCommand() {
@Override
public void writeTo(ILineWriter lineWriter) {
lineWriter.println(text);
}
});
}
private interface IExecutionContext {
void registerImplementation(String id, ILineWriter lineWriter);
ILineWriter getImplementation(String id);
}
protected interface ICommand {
void execute(IExecutionContext context);
}
private abstract class SimpleCommand implements ICommand, ILineSource {
@Override
public void execute(IExecutionContext context) {
this.writeTo(context.getImplementation(id));
}
}
private static class ExecutionContext implements IExecutionContext {
private final Map<String, ILineWriter> implementations = new HashMap<>();
@Override
public void registerImplementation(String id, ILineWriter lineWriter) {
if(lineWriter == null) {
throw new IllegalArgumentException("indented() returned null");
}
implementations.put(id, lineWriter);
}
@Override
public ILineWriter getImplementation(String id) {
ILineWriter lineWriter = implementations.get(id);
if(lineWriter == null) {
throw new IllegalArgumentException("No implementation registered for id "+id);
}
return lineWriter;
}
}
protected interface IIdGenerator {
String newId();
}
}
| 25.581081
| 114
| 0.743001
|
54944e406be35c182a74125294f7d9103af24ef2
| 440
|
package uk.co.philanderson;
import java.util.function.Function;
public class FunctionalProgramming {
protected static Function<Student,Boolean> f = s -> {
System.out.println(s.getFullName());
System.out.println(s.studentNumber);
var fullname = s.getFullName();
if("John Smith".equals(s.getFullName()) && s.studentNumber=="js123"){
return true;
}
else return false;
};
}
| 27.5
| 77
| 0.631818
|
61dbcfd2c8d196cf51cb2da4196d909fcaa7c303
| 7,147
|
/*******************************************************************************
* Copyright (C) 2005-2012 Alfresco Software Limited.
*
* This file is part of the Alfresco Mobile SDK.
*
* 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.alfresco.mobile.android.api.model.impl;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Map;
import org.alfresco.mobile.android.api.constants.CloudConstant;
import org.alfresco.mobile.android.api.constants.OnPremiseConstant;
import org.alfresco.mobile.android.api.model.Comment;
import org.alfresco.mobile.android.api.model.Person;
import org.alfresco.mobile.android.api.utils.DateUtils;
import org.apache.chemistry.opencmis.commons.impl.JSONConverter;
/**
* Comment :
* <ul>
* <li>is a convenient way to provide users with information or notes specific
* to that content</li>
* </ul>
*
* @author Jean Marie Pascal
*/
public class CommentImpl implements Comment
{
private static final long serialVersionUID = 1L;
/** Unique identifier of the comment. */
private String identifier;
/** Title. */
private String title;
/** Name. */
private String name;
/** Creation Date. */
private String creationDate;
/** Modification Date. */
private String modificationDate;
/** Author of the comment. */
private Person author;
/** Indicate if it's possible to edit. */
private boolean edit;
/** Indicate if it's possible to delete. */
private boolean delete;
private boolean isUpdated;
/** Content of the comment (HTML formatted). */
private String content;
/**
* Parse Json Response from Alfresco REST API to create a comment Object.
*
* @param json : json response that contains data from the repository
* @return Comment that contains informations about the comment.
*/
@SuppressWarnings("unchecked")
public static CommentImpl parseJson(Map<String, Object> json)
{
CommentImpl comment = new CommentImpl();
comment.identifier = JSONConverter.getString(json, OnPremiseConstant.NODEREF_VALUE);
comment.name = JSONConverter.getString(json, OnPremiseConstant.NAME_VALUE);
comment.title = JSONConverter.getString(json, OnPremiseConstant.TITLE_VALUE);
comment.content = JSONConverter.getString(json, OnPremiseConstant.CONTENT_VALUE);
comment.creationDate = JSONConverter.getString(json, OnPremiseConstant.CREATEDON_VALUE);
comment.modificationDate = JSONConverter.getString(json, OnPremiseConstant.MODIFIEDON_VALUE);
comment.author = PersonImpl.parseJson((Map<String, Object>) json.get(OnPremiseConstant.AUTHOR_VALUE));
comment.isUpdated = JSONConverter.getBoolean(json, OnPremiseConstant.ISUPDATED_VALUE);
Map<String, Object> jo = (Map<String, Object>) json.get(OnPremiseConstant.PERMISSION_VALUE);
comment.edit = JSONConverter.getBoolean(jo, OnPremiseConstant.EDIT_VALUE);
comment.delete = JSONConverter.getBoolean(jo, OnPremiseConstant.DELETE_VALUE);
return comment;
}
/**
* Parse Json Response from Alfresco Public API to create a comment Object.
*
* @param json : json response that contains data from the repository
* @return Comment that contains informations about the comment.
*/
@SuppressWarnings("unchecked")
public static CommentImpl parsePublicAPIJson(Map<String, Object> json)
{
CommentImpl comment = new CommentImpl();
comment.identifier = JSONConverter.getString(json, CloudConstant.ID_VALUE);
if (json.containsKey(CloudConstant.TITLE_VALUE))
{
comment.title = JSONConverter.getString(json, CloudConstant.TITLE_VALUE);
}
comment.content = JSONConverter.getString(json, CloudConstant.CONTENT_VALUE);
comment.creationDate = JSONConverter.getString(json, CloudConstant.CREATEDAT_VALUE);
comment.modificationDate = JSONConverter.getString(json, CloudConstant.MODIFIEDAT_VALUE);
comment.author = PersonImpl.parsePublicAPIJson((Map<String, Object>) json.get(CloudConstant.CREATEDBY_VALUE));
comment.isUpdated = JSONConverter.getBoolean(json, CloudConstant.EDITED_VALUE);
if (json.containsKey(CloudConstant.CANEDIT_VALUE))
{
comment.edit = JSONConverter.getBoolean(json, CloudConstant.CANEDIT_VALUE);
}
if (json.containsKey(CloudConstant.CANDELETE_VALUE))
{
comment.delete = JSONConverter.getBoolean(json, CloudConstant.CANDELETE_VALUE);
}
return comment;
}
/** {@inheritDoc} */
public String getIdentifier()
{
return identifier;
}
/** {@inheritDoc} */
public String getName()
{
return name;
}
/** {@inheritDoc} */
public String getTitle()
{
return title;
}
/** {@inheritDoc} */
public GregorianCalendar getCreatedAt()
{
GregorianCalendar g = null;
if (creationDate != null)
{
Date d = DateUtils.parseDate(creationDate);
if (d != null)
{
g = new GregorianCalendar();
g.setTime(d);
}
}
return g;
}
/**
* @return Returns the timestamp in the session’s locale when this comment
* has been modified.
*/
public GregorianCalendar getModifiedAt()
{
GregorianCalendar g = null;
if (modificationDate != null)
{
Date d = DateUtils.parseDate(modificationDate);
if (d != null)
{
g = new GregorianCalendar();
g.setTime(d);
}
}
return g;
}
/** {@inheritDoc} */
public String getContent()
{
return content;
}
/** {@inheritDoc} */
public String getCreatedBy()
{
return (author != null) ? author.getIdentifier() : null;
}
/** {@inheritDoc} */
public boolean isEdited()
{
return isUpdated;
}
/** {@inheritDoc} */
public boolean canEdit()
{
return edit;
}
/** {@inheritDoc} */
public boolean canDelete()
{
return delete;
}
public Person getCreatedByPerson()
{
return author;
}
}
| 32.193694
| 119
| 0.62082
|
fc2b6aaea25c2ed2fc335c7a0991b3c38a827647
| 1,126
|
package in.xnnyygn.xgossip;
import in.xnnyygn.xgossip.rpc.messages.AbstractMessage;
import java.util.ArrayList;
import java.util.List;
public class MessageCollector {
private final List<Message> messages = new ArrayList<>();
public void add(MemberEndpoint sender, MemberEndpoint recipient, AbstractMessage payload) {
messages.add(new Message(sender, recipient, payload));
}
public List<Message> getMessages() {
return messages;
}
public static class Message {
private final MemberEndpoint sender;
private final MemberEndpoint recipient;
private final AbstractMessage payload;
Message(MemberEndpoint sender, MemberEndpoint recipient, AbstractMessage payload) {
this.sender = sender;
this.recipient = recipient;
this.payload = payload;
}
public MemberEndpoint getSender() {
return sender;
}
public MemberEndpoint getRecipient() {
return recipient;
}
public AbstractMessage getPayload() {
return payload;
}
}
}
| 23.957447
| 95
| 0.648313
|
50175d449790eb6fa45789f70af1fbf421642039
| 7,715
|
package com.xzchaoo.asyncexecutor;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import org.jctools.queues.MpscArrayQueue;
/**
* 缺点加入command队列就算是成功, 但其实后面可能会因为加不进去队列而失败...
*
* @author xiangfeng.xzc
* @date 2020-06-11
*/
public class LockFreeTypeExecutor extends AbstractTypeExecutor {
// configs
private final int bufferSize;
private final LimitProvider limitProvider;
// state
/**
* Current executing type.
*/
private int executingType = 0;
private int maxBatch;
private int maxConcurrency;
/**
* Current executed task count of currentType.
*/
private int executed;
/**
* Current work in progress task count of currentType.
*/
private AtomicInteger wip = new AtomicInteger();
/**
* Total delayed task count of all types.
*/
private AtomicInteger delayedCount = new AtomicInteger();
/**
* Current executingType's index of types array.
*/
private int typeIndex = -1;
/**
* Indicate that other type has delayed tasks. Current type should give up when 'executed' reach 'maxBatch'.
*/
private boolean otherTypeHasDelayed;
private final ConcurrentHashMap<Integer, MpscArrayQueue<Runnable>> delayed = new ConcurrentHashMap<>();
private final CopyOnWriteArrayList<Integer> types = new CopyOnWriteArrayList<>();
private final MpscArrayQueue<Integer> cmdQueue;
private final AtomicInteger drainLoopWip = new AtomicInteger(0);
public LockFreeTypeExecutor(int commandBufferSize, int taskMaxDelaySize,
LimitProvider limitProvider) {
if (commandBufferSize <= 0) {
throw new IllegalArgumentException();
}
if (taskMaxDelaySize <= 0) {
throw new IllegalArgumentException();
}
this.limitProvider = limitProvider;
this.cmdQueue = new MpscArrayQueue<>(commandBufferSize);
this.bufferSize = taskMaxDelaySize;
}
@Override
public void start() {
// nothing todo
}
@Override
public void stop() {
// nothing todo
}
/**
* 这里我想了一下, 我们需要确保: 如果任务能放到delayed里就一定能被执行正常(除了stop调用外), 如果放不进去(队列满)就应该立即抛异常
*
* @param type type
* @param asyncTask asyncTask
*/
@Override
protected void execute(int type, Runnable asyncTask) {
MpscArrayQueue<Runnable> q = delayed.get(type);
if (q == null) {
q = new MpscArrayQueue<>(bufferSize);
MpscArrayQueue<Runnable> oldQ = delayed.putIfAbsent(type, q);
if (oldQ == null) {
// TODO 这里原子性问题
types.add(type);
} else {
q = oldQ;
}
}
if (!q.offer(asyncTask)) {
throw new IllegalStateException("task queue full");
}
delayedCount.incrementAndGet();
// TODO 理论上这里也可能爆掉... 但可能性比较小, 因为处理比较快, 此时有可能导致Executor进入不一致的状态(还有数据delay, 但却不继续往下走)
if (!cmdQueue.offer(type)) {
throw new IllegalStateException("cmdQueue is full");
}
drainLoop();
}
@Override
protected boolean tryExecute(int type, Runnable safeAsyncTask) {
MpscArrayQueue<Runnable> q = delayed.get(type);
if (q == null) {
q = new MpscArrayQueue<>(bufferSize);
MpscArrayQueue<Runnable> oldQ = delayed.putIfAbsent(type, q);
if (oldQ == null) {
// TODO 这里原子性问题
types.add(type);
} else {
q = oldQ;
}
}
if (!q.offer(safeAsyncTask)) {
return false;
}
delayedCount.incrementAndGet();
// TODO 理论上这里也可能爆掉... 但可能性比较小, 因为处理比较快, 此时有可能导致Executor进入不一致的状态(还有数据delay, 但却不继续往下走)
if (!cmdQueue.offer(type)) {
throw new IllegalStateException("cmdQueue is full");
}
drainLoop();
return true;
}
private boolean canExecute() {
// <=0 means no limit
return (maxConcurrency <= 0 || wip.get() < maxConcurrency)
&& (maxBatch <= 0 || executed < maxBatch || !otherTypeHasDelayed);
}
private void drainLoop() {
if (drainLoopWip.getAndIncrement() != 0) {
return;
}
int delta = drainLoopWip.get();
do {
for (; ; ) {
// type0 新增了一个task
Integer type0 = cmdQueue.relaxedPoll();
if (type0 == null) {
// 没有任务了 break
break;
}
int type = type0;
MpscArrayQueue<Runnable> q = delayed.get(type0);
if (executingType == 0) {
executingType = type;
maxBatch = limitProvider.getMaxBatch(type);
maxConcurrency = limitProvider.getMaxConcurrency(type);
drainQueue(q);
} else if (executingType == type) {
drainQueue(q);
} else {
otherTypeHasDelayed = true;
}
}
if (executingType > 0) {
MpscArrayQueue<Runnable> q = delayed.get(executingType);
if (wip.get() == 0 && (q.isEmpty() || !canExecute())) {
// 当前queue已经空了 或者超过maxBatch限制, 切换到下个queue去执行
switchToOtherType();
} else {
// 否则可能还有继续执行的余地
drainQueue(q);
}
}
delta = drainLoopWip.addAndGet(-delta);
} while (delta != 0);
}
private void switchToOtherType() {
executingType = 0;
executed = 0;
otherTypeHasDelayed = false;
// 这里也不对 有并发问题...
if (delayedCount.get() == 0) {
return;
}
int size = types.size();
for (int i = 0; i < size; ++i) {
if (++typeIndex == size) {
typeIndex = 0;
}
int type = types.get(typeIndex);
MpscArrayQueue<Runnable> q = delayed.get(type);
if (!q.isEmpty()) {
executingType = type;
int typeIndex2 = typeIndex;
for (int j = i + 1; j < size; ++j) {
if (++typeIndex2 == size) {
typeIndex2 = 0;
}
MpscArrayQueue<Runnable> q2 = delayed.get(types.get(typeIndex2));
if (!q2.isEmpty()) {
otherTypeHasDelayed = true;
break;
}
}
maxConcurrency = limitProvider.getMaxConcurrency(type);
maxBatch = limitProvider.getMaxBatch(type);
drainQueue(q);
return;
}
}
}
private void drainQueue(MpscArrayQueue<Runnable> q) {
for (; canExecute(); ) {
Runnable task = q.relaxedPoll();
if (task == null) {
break;
}
wip.incrementAndGet();
++executed;
delayedCount.decrementAndGet();
safeExecute(task);
}
}
@Override
protected void ack(int type) {
wip.decrementAndGet();
drainLoop();
}
@Override
public Stat stat() {
Stat stat = new Stat();
stat.setDelayedSize(delayedCount.get());
stat.setWip(wip.get());
return stat;
}
}
| 31.108871
| 112
| 0.520156
|
3149ed0d88808b66e9e56ba434b9e878b23f8ccf
| 8,185
|
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.subsystems;
import com.ctre.phoenix.motorcontrol.StatusFrame;
import com.ctre.phoenix.sensors.CANCoder;
import com.kauailabs.navx.frc.AHRS;
import com.revrobotics.CANSparkMax;
import com.revrobotics.RelativeEncoder;
import com.revrobotics.SparkMaxLimitSwitch;
import com.revrobotics.SparkMaxPIDController;
import com.revrobotics.CANSparkMax.ControlType;
import com.revrobotics.CANSparkMaxLowLevel.MotorType;
import com.revrobotics.SparkMaxLimitSwitch.Type;
import edu.wpi.first.math.geometry.Pose2d;
import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.math.kinematics.ChassisSpeeds;
import edu.wpi.first.math.kinematics.SwerveDriveKinematics;
import edu.wpi.first.math.kinematics.SwerveDriveOdometry;
import edu.wpi.first.math.kinematics.SwerveModuleState;
import edu.wpi.first.math.trajectory.Trajectory;
import edu.wpi.first.util.sendable.SendableBuilder;
import edu.wpi.first.wpilibj.I2C;
import edu.wpi.first.wpilibj.shuffleboard.Shuffleboard;
import edu.wpi.first.wpilibj.smartdashboard.Field2d;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import static frc.robot.Constants.DriveConstants.*;
public class Drivetrain extends SubsystemBase {
boolean m_allCalibrated = false;
final SwerveDriveKinematics m_kinematics;
final Module[] m_modules = new Module[4];
final AHRS m_gyro;
final SwerveDriveOdometry m_odometry;
SwerveModuleState[] m_lastMeasuredStates = new SwerveModuleState[4];
private Pose2d m_relativePoseOffset = new Pose2d();
private final Field2d m_fieldTracker;
/** Creates a new Drivetrain. */
public Drivetrain() {
m_kinematics = KINEMATICS;
m_modules[0] = new Module(CANChannels.FRONT_RIGHT_VELOCITY, CANChannels.FRONT_RIGHT_ROTATION, CANChannels.FRONT_RIGHT_CALIBRATION);
m_modules[1] = new Module(CANChannels.REAR_RIGHT_VELOCITY, CANChannels.REAR_RIGHT_ROTATION, CANChannels.REAR_RIGHT_CALIBRATION);
m_modules[2] = new Module(CANChannels.REAR_LEFT_VELOCITY, CANChannels.REAR_LEFT_ROTATION, CANChannels.REAR_LEFT_CALIBRATION);
m_modules[3] = new Module(CANChannels.FRONT_LEFT_VELOCITY, CANChannels.FRONT_LEFT_ROTATION, CANChannels.FRONT_LEFT_CALIBRATION);
m_gyro = new AHRS(I2C.Port.kMXP,(byte)200);
m_odometry = new SwerveDriveOdometry(m_kinematics, m_gyro.getRotation2d());
m_fieldTracker = new Field2d();
addChild("Field Position",m_fieldTracker);
}
public void setSpeedFieldRelative(ChassisSpeeds speeds){
speeds = ChassisSpeeds.fromFieldRelativeSpeeds(speeds.vxMetersPerSecond, speeds.vyMetersPerSecond,
speeds.omegaRadiansPerSecond, Rotation2d.fromDegrees(-m_gyro.getYaw()));
setChassisSpeed(speeds);
}
public void setDisplayTrajectory(Trajectory t){
m_fieldTracker.getObject("traj").setTrajectory(t);
}
public void setChassisSpeed(ChassisSpeeds speeds){
SwerveModuleState[] states = m_kinematics.toSwerveModuleStates(speeds);
setStates(states);
}
public void setStates(SwerveModuleState[] states){
if(m_allCalibrated){
SwerveDriveKinematics.desaturateWheelSpeeds(states, MAX_WHEEL_SPEED);
for(int i=0;i<4;i++){
m_modules[i].setState(states[i]);
}
}
}
public boolean getAllCalibrated(){
return m_allCalibrated;
}
public void calibrate(){
for(Module m : m_modules){
m.calibrate();
}
m_allCalibrated = true;
}
public Pose2d getPoseRelative(){
return m_odometry.getPoseMeters().relativeTo(m_relativePoseOffset);
}
public void setPoseRelative(){
m_relativePoseOffset = m_odometry.getPoseMeters();
}
public void resetGyro(){
//m_gyro.reset();
m_gyro.zeroYaw();
m_odometry.resetPosition(new Pose2d(), m_gyro.getRotation2d());
}
public void setGyroAngleAdjustment(double angle){
m_gyro.setAngleAdjustment(angle);
}
public Pose2d getCurrentPoseEstimate(){
return m_odometry.getPoseMeters();
}
void measureCurrentStates(){
for(int i=0;i<4;i++){
m_lastMeasuredStates[i] = m_modules[i].measureState();
}
}
@Override
public void periodic() {
// This method will be called once per scheduler run
measureCurrentStates();
m_odometry.update(Rotation2d.fromDegrees(-m_gyro.getAngle()), m_lastMeasuredStates);
m_fieldTracker.setRobotPose(getPoseRelative());
}
//TODO:
@Override
public void initSendable(SendableBuilder builder){
super.initSendable(builder);
builder.addDoubleProperty("X location", ()->m_odometry.getPoseMeters().getX(), null);
builder.addDoubleProperty("Y location", ()->m_odometry.getPoseMeters().getY(), null);
}
private class Module{
private CANSparkMax m_rotationMotor;
private RelativeEncoder m_rotationEncoder;
private SparkMaxPIDController m_rotationController;
private CANSparkMax m_velocityMotor;
private RelativeEncoder m_velocityEncoder;
private SparkMaxPIDController m_velocityController;
private CANCoder m_calibrateEncoder;
Module(int velocityChannel,int rotationChannel, int calibrationChannel){
m_rotationMotor = new CANSparkMax(rotationChannel, MotorType.kBrushless);
m_rotationEncoder = m_rotationMotor.getEncoder();
m_rotationController = m_rotationMotor.getPIDController();
//m_rotationMotor.setInverted(true);
m_rotationMotor.setInverted(false);
// m_rotationEncoder.setInverted(true);
m_rotationEncoder.setPositionConversionFactor(ROTATION_GEARING * Math.PI*2);
m_rotationController.setFeedbackDevice(m_rotationEncoder);
m_rotationController.setP(0.6);
m_rotationController.setI(0);
m_rotationController.setD(0);
m_rotationController.setFF(0);
m_velocityMotor = new CANSparkMax(velocityChannel, MotorType.kBrushless);
m_velocityEncoder = m_velocityMotor.getEncoder();
m_velocityController = m_velocityMotor.getPIDController();
m_velocityMotor.setInverted(false);
m_velocityEncoder.setVelocityConversionFactor(VELOCITY_GEARING*WHEEL_CIRCUMFRENCE * (1.0/60.0));
m_velocityController.setP(0.22);
m_velocityController.setI(0);
m_velocityController.setD(1.2);
m_velocityController.setFF(0.23);
m_calibrateEncoder = new CANCoder(calibrationChannel);
Shuffleboard.getTab("Tab 5").addNumber("Can bus voltage "+m_rotationMotor.getDeviceId(), m_calibrateEncoder::getBusVoltage);
//TODO: remove
// Shuffleboard.getTab("Tab 5").addNumber("Rotation encoder "+m_rotationMotor.getDeviceId(), m_rotationEncoder::getPosition);
// Shuffleboard.getTab("Tab 5").addNumber("Calibrate encoder "+m_rotationMotor.getDeviceId(), m_calibrateEncoder::getAbsolutePosition);
}
public SwerveModuleState measureState(){
return new SwerveModuleState(m_velocityEncoder.getVelocity(),new Rotation2d(m_rotationEncoder.getPosition()));
}
public void setState(SwerveModuleState state){
state = SwerveModuleState.optimize(state, new Rotation2d(m_rotationEncoder.getPosition()));
m_velocityController.setReference(state.speedMetersPerSecond, ControlType.kVelocity);
m_rotationController.setReference(
mapAngleToNearContinuous(state.angle.getRadians()),
ControlType.kPosition);
}
public void calibrate(){
m_rotationEncoder.setPosition(m_calibrateEncoder.getAbsolutePosition()*Math.PI/180.0);
//System.out.println("Calibrated wheel"+m_rotationMotor.getDeviceId()+" to "+m_rotationEncoder.getPosition());
}
double mapAngleToNearContinuous(double newAngle){
double currentAngle = m_rotationEncoder.getPosition();
long completedRotations = Math.round(currentAngle / (Math.PI*2));
double offsetAngle = newAngle%(Math.PI*2) + (2*Math.PI*completedRotations);
if(Math.abs(currentAngle - offsetAngle) < Math.PI){
return offsetAngle;
}else if(offsetAngle > currentAngle){
return offsetAngle - Math.PI*2;
}else{
return offsetAngle + Math.PI*2;
}
}
}
}
| 34.535865
| 141
| 0.753696
|
bbc321fbe1372f4a42f53e6ce5e55a941f55fde3
| 1,604
|
package org.sif.beans;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
@Entity
public class Department implements Serializable {
private static final long serialVersionUID = 1L;
@Version
private Long versionNumber;
@Id
@GeneratedValue
private Long id;
@OneToMany(targetEntity = Employee.class)
private Set<Employee> employeelist = new HashSet<>();
@ManyToOne
private Employee coordinator;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean equals(Object other) {
if (other == null) {
return false;
}
if (this == other) {
return true;
}
if (!(other instanceof Department)) {
return false;
}
final Department department = (Department) other;
return new EqualsBuilder()
.appendSuper(super.equals(other))
.append(name, department.name)
.isEquals();
}
public int hashCode() {
return new HashCodeBuilder(17, 37).
appendSuper(37).
append(name).
toHashCode();
}
public Set<Employee> getEmployeelist() {
return employeelist;
}
public void setEmployeelist(Set<Employee> employeelist) {
this.employeelist = employeelist;
}
public Employee getCoordinator() {
return coordinator;
}
public void setCoordinator(Employee coordinator) {
this.coordinator = coordinator;
}
}
| 18.227273
| 58
| 0.712594
|
42c7319636906b63a91ff3c2693cf7434493299e
| 2,468
|
import java.util.Scanner;
/*Scrivere un programma per giocare a "tris" (tic-tac-toe in inglese), il classico gioco in cui due giocatori
dispongono alternativamente un proprio contrassegno in una casella di una scacchiera 3 x 3 finché uno dei due
non pone tre contrassegni in una fila orizzontale, verticale o diagonale.
Risolvere il problema in due passi
Scrivere una classe MyTris che rappresenti la scacchiera e la cui interfaccia pubblica è definita
https://elearning.dei.unipd.it/pluginfile.php/829897/mod_book/chapter/5083/MyTris.html
Scrivere poi una classe eseguibile che usi MyTris, e che gestisca una partita a tris tra due giocatori,
seguendo il comportamento descritto sopra.
*/
public class Main {
public static int[] move(String playerName, char token) {
Scanner scanner = new Scanner(System.in);
System.out.println(playerName + " dove vuoi inserire " + token + "?");
String position = scanner.nextLine();
int row = Character.getNumericValue(position.charAt(0));
int column = Character.getNumericValue(position.charAt(2));
return new int[] { row, column };
}
public static void checkWin(String playerName, boolean won) {
if (won) {
System.out.println(playerName + " ha vinto");
}
}
public static void main(String[] args) {
MyTris myTris = new MyTris();
int move[];
boolean won = false;
int moves = 0;
while (!won) {
// printing the board for the players
System.out.println(myTris.toString());
// player 1 moves
move = move("Player1", 'X');
myTris.setCharInPosition(move[0], move[1], 'X');
moves++;
// check win (after 5 moves)
if (moves > 4) {
won = myTris.isWinning('X');
System.out.println(myTris.toString());
checkWin("Player1", won);
break;
}
// printboard
System.out.println(myTris.toString());
// player 2 moves
move = move("Player2", 'O');
myTris.setCharInPosition(move[0], move[1], 'O');
moves++;
// check win (after 5 moves)
if (moves >= 5) {
won = myTris.isWinning('O');
System.out.println(myTris.toString());
checkWin("Player2", won);
}
}
}
}
| 37.969231
| 110
| 0.58671
|
b3d67679f6a4e2a79568ff60e76aa991eac4b635
| 4,592
|
package br.com.processboss.core.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import br.com.processboss.core.bean.Resources;
import br.com.processboss.core.bean.ServerState;
import br.com.processboss.core.model.ProcessInTask;
import br.com.processboss.core.service.IServerStateService;
/**
* Servico que obtem as informacoes de hardware
* do servidor no momento solicitado
*/
public class ServerStateService implements IServerStateService {
private static final Logger LOG = LoggerFactory.getLogger(ServerStateService.class);
private static final Map<String, ProcessInTask> IN_PROGRESS = new HashMap<String, ProcessInTask>();
private static final List<ProcessInTask> WAITING = new ArrayList<ProcessInTask>();
private static final Map<Integer, Resources> resourcesConsumption = new HashMap<Integer, Resources>();
/**
* Le as informacoes de hardware do servidor
*
* @return
*/
@Override
public ServerState read() {
ServerState serverState = new ServerState();
try {
Sigar.load();
Sigar sigar = new Sigar();
/**
* Informacoes da CPU
*/
serverState.setCpuInfo(sigar.getCpuInfoList());
serverState.setCpuPerc(sigar.getCpuPerc());
/**
* Informacoes da Memoria
*/
serverState.setMemory(sigar.getMem());
/**
* Consumo de recursos pelos processos
*/
serverState.setResourcesConsumption(getResourcesConsumption());
} catch (SigarException e) {
LOG.error("Ocorreu um erro ao obter as informacoes do servidor.");
e.printStackTrace();
}
return serverState;
}
@Override
public Resources getAlocatedResources(){
double memory = 0.0D;
double cpu = 0.0D;
for (ProcessInTask process : IN_PROGRESS.values()) {
Resources resources = new Resources(process.getExecutionDetails());
memory += resources.getMemory();
cpu += resources.getCpu();
}
return new Resources(memory, cpu);
}
@Override
public String addProcessExecution(ProcessInTask processInTask) {
String key = processInTask.getId() + "_" + new Date().getTime();
IN_PROGRESS.put(key, processInTask);
return key;
}
@Override
public void removeProcessExecution(String processExecutionKey) {
IN_PROGRESS.remove(processExecutionKey);
}
@Override
public void addProcessWaiting(ProcessInTask processInTask) {
WAITING.add(processInTask);
}
@Override
public void removeProcessWaiting(ProcessInTask processInTask) {
WAITING.remove(processInTask);
}
@Override
public List<ProcessInTask> getInProgressProcess(){
List<ProcessInTask> list = new ArrayList<ProcessInTask>();
for (ProcessInTask process : IN_PROGRESS.values()) {
list.add(process);
}
return list;
}
@Override
public List<ProcessInTask> getWaitingProcess(){
List<ProcessInTask> list = new ArrayList<ProcessInTask>();
for (ProcessInTask process : WAITING) {
list.add(process);
}
return list;
}
@Override
public synchronized void updateResourcesConsumption(int pid, Resources resources) {
resourcesConsumption.put(pid, resources);
}
@Override
public synchronized void removeResourcesConsumption(int pid) {
resourcesConsumption.remove(pid);
}
@Override
public Resources getResourcesConsumption() {
double mem = 0D, cpu=0D;
for (Resources resources : resourcesConsumption.values()) {
mem += resources.getMemory();
cpu += resources.getCpu();
}
return new Resources(mem, cpu);
}
@Override
public Resources getAvaiableResources() {
ServerState serverState = read();
Resources alocatedResources = getAlocatedResources();
long totalMemory = serverState.getMemory().getTotal();
long usedMemory = serverState.getMemory().getUsed();
Double consumedMemory = serverState.getResourcesConsumption().getMemory();
Double alocatedMemory = alocatedResources.getMemory();
Double freeMemory = totalMemory - ((usedMemory - consumedMemory) + alocatedMemory);
int totalCpu = 100;
double usedCpu = serverState.getCpuUsed();
Double consumedCpu = serverState.getResourcesConsumption().getCpu();
Double alocatedCpu = alocatedResources.getCpu();
Double freeCpu = totalCpu - ((usedCpu - consumedCpu) + alocatedCpu);
return new Resources(freeMemory, freeCpu);
}
}
| 27.497006
| 104
| 0.710584
|
a45f1d5f8dec1d643303cb2e64daaefb8bde93f0
| 3,901
|
/*
* Copyright (c) 2014-2016 Jan Strauß <jan[at]over9000.eu>
*
* 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 eu.over9000.skadi.io;
import eu.over9000.skadi.model.StateContainer;
import org.apache.commons.lang3.SystemUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public final class PersistenceHandler {
public static final String SKADI_DIRECTORY_NAME = ".skadi";
public static final String PERSISTENCE_DIRECTORY = SystemUtils.USER_HOME + File.separator + SKADI_DIRECTORY_NAME + File.separator;
public static final String PERSISTENCE_FILE = "skadi_state.xml";
private static final Logger LOGGER = LoggerFactory.getLogger(PersistenceHandler.class);
private final Object fileLock = new Object();
private Marshaller marshaller;
private Unmarshaller unmarshaller;
public PersistenceHandler() {
try {
final JAXBContext context = JAXBContext.newInstance(StateContainer.class);
marshaller = context.createMarshaller();
unmarshaller = context.createUnmarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
} catch (final JAXBException e) {
LOGGER.error("exception construction persistence handler", e);
}
}
public StateContainer loadState() {
StateContainer result;
try {
if (Files.exists(getStateFilePath())) {
result = readFromFile();
} else {
checkDir();
result = new StateContainer();
writeToFile(result);
}
} catch (IOException | JAXBException e) {
LOGGER.error("exception loading state, will fallback to default settings", e);
result = new StateContainer();
}
return result;
}
public void saveState(final StateContainer state) {
try {
checkDir();
writeToFile(state);
} catch (IOException | JAXBException e) {
LOGGER.error("exception saving state", e);
}
}
private Path getStateFilePath() {
return Paths.get(PERSISTENCE_DIRECTORY, PERSISTENCE_FILE);
}
private void writeToFile(final StateContainer state) throws IOException, JAXBException {
final Path stateFile = getStateFilePath();
synchronized (fileLock) {
marshaller.marshal(state, stateFile.toFile());
}
LOGGER.debug("wrote state to file");
}
private StateContainer readFromFile() throws IOException, JAXBException {
final Path stateFile = getStateFilePath();
final StateContainer state;
synchronized (fileLock) {
state = (StateContainer) unmarshaller.unmarshal(stateFile.toFile());
}
LOGGER.debug("load state from file");
return state;
}
private void checkDir() throws IOException {
Files.createDirectories(Paths.get(PERSISTENCE_DIRECTORY));
}
}
| 34.219298
| 131
| 0.757498
|
68d5321e8dfc0c587a44d6e6f3fe08afec4cbf3a
| 700
|
package me.ele.jarch.athena.util.deploy;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import me.ele.jarch.athena.util.deploy.dalgroupcfg.Org;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.IOException;
public class OrgTest {
@Test public void testOrgLoad() throws IOException {
ObjectMapper objectMapper =
new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Org org = objectMapper
.readValue(getClass().getClassLoader().getResourceAsStream("org.json"), Org.class);
Assert.assertTrue(org.shouldLoad());
}
}
| 35
| 99
| 0.751429
|
e1c9ada7ae4d7e4be9136683f40dfb231dc14ea7
| 38,095
|
package shentu.oracle.v1alpha1;
import static io.grpc.MethodDescriptor.generateFullMethodName;
import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ClientCalls.asyncClientStreamingCall;
import static io.grpc.stub.ClientCalls.asyncServerStreamingCall;
import static io.grpc.stub.ClientCalls.asyncUnaryCall;
import static io.grpc.stub.ClientCalls.blockingServerStreamingCall;
import static io.grpc.stub.ClientCalls.blockingUnaryCall;
import static io.grpc.stub.ClientCalls.futureUnaryCall;
import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ServerCalls.asyncClientStreamingCall;
import static io.grpc.stub.ServerCalls.asyncServerStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnaryCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;
/**
* <pre>
* Msg defines the shield Msg service.
* </pre>
*/
@javax.annotation.Generated(
value = "by gRPC proto compiler (version 1.33.1)",
comments = "Source: shentu/oracle/v1alpha1/tx.proto")
public final class MsgGrpc {
private MsgGrpc() {}
public static final String SERVICE_NAME = "shentu.oracle.v1alpha1.Msg";
// Static method descriptors that strictly reflect the proto.
private static volatile io.grpc.MethodDescriptor<shentu.oracle.v1alpha1.Tx.MsgCreateOperator,
shentu.oracle.v1alpha1.Tx.MsgCreateOperatorResponse> getCreateOperatorMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "CreateOperator",
requestType = shentu.oracle.v1alpha1.Tx.MsgCreateOperator.class,
responseType = shentu.oracle.v1alpha1.Tx.MsgCreateOperatorResponse.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<shentu.oracle.v1alpha1.Tx.MsgCreateOperator,
shentu.oracle.v1alpha1.Tx.MsgCreateOperatorResponse> getCreateOperatorMethod() {
io.grpc.MethodDescriptor<shentu.oracle.v1alpha1.Tx.MsgCreateOperator, shentu.oracle.v1alpha1.Tx.MsgCreateOperatorResponse> getCreateOperatorMethod;
if ((getCreateOperatorMethod = MsgGrpc.getCreateOperatorMethod) == null) {
synchronized (MsgGrpc.class) {
if ((getCreateOperatorMethod = MsgGrpc.getCreateOperatorMethod) == null) {
MsgGrpc.getCreateOperatorMethod = getCreateOperatorMethod =
io.grpc.MethodDescriptor.<shentu.oracle.v1alpha1.Tx.MsgCreateOperator, shentu.oracle.v1alpha1.Tx.MsgCreateOperatorResponse>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "CreateOperator"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
shentu.oracle.v1alpha1.Tx.MsgCreateOperator.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
shentu.oracle.v1alpha1.Tx.MsgCreateOperatorResponse.getDefaultInstance()))
.setSchemaDescriptor(new MsgMethodDescriptorSupplier("CreateOperator"))
.build();
}
}
}
return getCreateOperatorMethod;
}
private static volatile io.grpc.MethodDescriptor<shentu.oracle.v1alpha1.Tx.MsgRemoveOperator,
shentu.oracle.v1alpha1.Tx.MsgRemoveOperatorResponse> getRemoveOperatorMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "RemoveOperator",
requestType = shentu.oracle.v1alpha1.Tx.MsgRemoveOperator.class,
responseType = shentu.oracle.v1alpha1.Tx.MsgRemoveOperatorResponse.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<shentu.oracle.v1alpha1.Tx.MsgRemoveOperator,
shentu.oracle.v1alpha1.Tx.MsgRemoveOperatorResponse> getRemoveOperatorMethod() {
io.grpc.MethodDescriptor<shentu.oracle.v1alpha1.Tx.MsgRemoveOperator, shentu.oracle.v1alpha1.Tx.MsgRemoveOperatorResponse> getRemoveOperatorMethod;
if ((getRemoveOperatorMethod = MsgGrpc.getRemoveOperatorMethod) == null) {
synchronized (MsgGrpc.class) {
if ((getRemoveOperatorMethod = MsgGrpc.getRemoveOperatorMethod) == null) {
MsgGrpc.getRemoveOperatorMethod = getRemoveOperatorMethod =
io.grpc.MethodDescriptor.<shentu.oracle.v1alpha1.Tx.MsgRemoveOperator, shentu.oracle.v1alpha1.Tx.MsgRemoveOperatorResponse>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "RemoveOperator"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
shentu.oracle.v1alpha1.Tx.MsgRemoveOperator.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
shentu.oracle.v1alpha1.Tx.MsgRemoveOperatorResponse.getDefaultInstance()))
.setSchemaDescriptor(new MsgMethodDescriptorSupplier("RemoveOperator"))
.build();
}
}
}
return getRemoveOperatorMethod;
}
private static volatile io.grpc.MethodDescriptor<shentu.oracle.v1alpha1.Tx.MsgAddCollateral,
shentu.oracle.v1alpha1.Tx.MsgAddCollateralResponse> getAddCollateralMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "AddCollateral",
requestType = shentu.oracle.v1alpha1.Tx.MsgAddCollateral.class,
responseType = shentu.oracle.v1alpha1.Tx.MsgAddCollateralResponse.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<shentu.oracle.v1alpha1.Tx.MsgAddCollateral,
shentu.oracle.v1alpha1.Tx.MsgAddCollateralResponse> getAddCollateralMethod() {
io.grpc.MethodDescriptor<shentu.oracle.v1alpha1.Tx.MsgAddCollateral, shentu.oracle.v1alpha1.Tx.MsgAddCollateralResponse> getAddCollateralMethod;
if ((getAddCollateralMethod = MsgGrpc.getAddCollateralMethod) == null) {
synchronized (MsgGrpc.class) {
if ((getAddCollateralMethod = MsgGrpc.getAddCollateralMethod) == null) {
MsgGrpc.getAddCollateralMethod = getAddCollateralMethod =
io.grpc.MethodDescriptor.<shentu.oracle.v1alpha1.Tx.MsgAddCollateral, shentu.oracle.v1alpha1.Tx.MsgAddCollateralResponse>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "AddCollateral"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
shentu.oracle.v1alpha1.Tx.MsgAddCollateral.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
shentu.oracle.v1alpha1.Tx.MsgAddCollateralResponse.getDefaultInstance()))
.setSchemaDescriptor(new MsgMethodDescriptorSupplier("AddCollateral"))
.build();
}
}
}
return getAddCollateralMethod;
}
private static volatile io.grpc.MethodDescriptor<shentu.oracle.v1alpha1.Tx.MsgReduceCollateral,
shentu.oracle.v1alpha1.Tx.MsgReduceCollateralResponse> getReduceCollateralMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "ReduceCollateral",
requestType = shentu.oracle.v1alpha1.Tx.MsgReduceCollateral.class,
responseType = shentu.oracle.v1alpha1.Tx.MsgReduceCollateralResponse.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<shentu.oracle.v1alpha1.Tx.MsgReduceCollateral,
shentu.oracle.v1alpha1.Tx.MsgReduceCollateralResponse> getReduceCollateralMethod() {
io.grpc.MethodDescriptor<shentu.oracle.v1alpha1.Tx.MsgReduceCollateral, shentu.oracle.v1alpha1.Tx.MsgReduceCollateralResponse> getReduceCollateralMethod;
if ((getReduceCollateralMethod = MsgGrpc.getReduceCollateralMethod) == null) {
synchronized (MsgGrpc.class) {
if ((getReduceCollateralMethod = MsgGrpc.getReduceCollateralMethod) == null) {
MsgGrpc.getReduceCollateralMethod = getReduceCollateralMethod =
io.grpc.MethodDescriptor.<shentu.oracle.v1alpha1.Tx.MsgReduceCollateral, shentu.oracle.v1alpha1.Tx.MsgReduceCollateralResponse>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "ReduceCollateral"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
shentu.oracle.v1alpha1.Tx.MsgReduceCollateral.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
shentu.oracle.v1alpha1.Tx.MsgReduceCollateralResponse.getDefaultInstance()))
.setSchemaDescriptor(new MsgMethodDescriptorSupplier("ReduceCollateral"))
.build();
}
}
}
return getReduceCollateralMethod;
}
private static volatile io.grpc.MethodDescriptor<shentu.oracle.v1alpha1.Tx.MsgWithdrawReward,
shentu.oracle.v1alpha1.Tx.MsgWithdrawRewardResponse> getWithdrawRewardMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "WithdrawReward",
requestType = shentu.oracle.v1alpha1.Tx.MsgWithdrawReward.class,
responseType = shentu.oracle.v1alpha1.Tx.MsgWithdrawRewardResponse.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<shentu.oracle.v1alpha1.Tx.MsgWithdrawReward,
shentu.oracle.v1alpha1.Tx.MsgWithdrawRewardResponse> getWithdrawRewardMethod() {
io.grpc.MethodDescriptor<shentu.oracle.v1alpha1.Tx.MsgWithdrawReward, shentu.oracle.v1alpha1.Tx.MsgWithdrawRewardResponse> getWithdrawRewardMethod;
if ((getWithdrawRewardMethod = MsgGrpc.getWithdrawRewardMethod) == null) {
synchronized (MsgGrpc.class) {
if ((getWithdrawRewardMethod = MsgGrpc.getWithdrawRewardMethod) == null) {
MsgGrpc.getWithdrawRewardMethod = getWithdrawRewardMethod =
io.grpc.MethodDescriptor.<shentu.oracle.v1alpha1.Tx.MsgWithdrawReward, shentu.oracle.v1alpha1.Tx.MsgWithdrawRewardResponse>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "WithdrawReward"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
shentu.oracle.v1alpha1.Tx.MsgWithdrawReward.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
shentu.oracle.v1alpha1.Tx.MsgWithdrawRewardResponse.getDefaultInstance()))
.setSchemaDescriptor(new MsgMethodDescriptorSupplier("WithdrawReward"))
.build();
}
}
}
return getWithdrawRewardMethod;
}
private static volatile io.grpc.MethodDescriptor<shentu.oracle.v1alpha1.Tx.MsgCreateTask,
shentu.oracle.v1alpha1.Tx.MsgCreateTaskResponse> getCreateTaskMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "CreateTask",
requestType = shentu.oracle.v1alpha1.Tx.MsgCreateTask.class,
responseType = shentu.oracle.v1alpha1.Tx.MsgCreateTaskResponse.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<shentu.oracle.v1alpha1.Tx.MsgCreateTask,
shentu.oracle.v1alpha1.Tx.MsgCreateTaskResponse> getCreateTaskMethod() {
io.grpc.MethodDescriptor<shentu.oracle.v1alpha1.Tx.MsgCreateTask, shentu.oracle.v1alpha1.Tx.MsgCreateTaskResponse> getCreateTaskMethod;
if ((getCreateTaskMethod = MsgGrpc.getCreateTaskMethod) == null) {
synchronized (MsgGrpc.class) {
if ((getCreateTaskMethod = MsgGrpc.getCreateTaskMethod) == null) {
MsgGrpc.getCreateTaskMethod = getCreateTaskMethod =
io.grpc.MethodDescriptor.<shentu.oracle.v1alpha1.Tx.MsgCreateTask, shentu.oracle.v1alpha1.Tx.MsgCreateTaskResponse>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "CreateTask"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
shentu.oracle.v1alpha1.Tx.MsgCreateTask.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
shentu.oracle.v1alpha1.Tx.MsgCreateTaskResponse.getDefaultInstance()))
.setSchemaDescriptor(new MsgMethodDescriptorSupplier("CreateTask"))
.build();
}
}
}
return getCreateTaskMethod;
}
private static volatile io.grpc.MethodDescriptor<shentu.oracle.v1alpha1.Tx.MsgTaskResponse,
shentu.oracle.v1alpha1.Tx.MsgTaskResponseResponse> getTaskResponseMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "TaskResponse",
requestType = shentu.oracle.v1alpha1.Tx.MsgTaskResponse.class,
responseType = shentu.oracle.v1alpha1.Tx.MsgTaskResponseResponse.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<shentu.oracle.v1alpha1.Tx.MsgTaskResponse,
shentu.oracle.v1alpha1.Tx.MsgTaskResponseResponse> getTaskResponseMethod() {
io.grpc.MethodDescriptor<shentu.oracle.v1alpha1.Tx.MsgTaskResponse, shentu.oracle.v1alpha1.Tx.MsgTaskResponseResponse> getTaskResponseMethod;
if ((getTaskResponseMethod = MsgGrpc.getTaskResponseMethod) == null) {
synchronized (MsgGrpc.class) {
if ((getTaskResponseMethod = MsgGrpc.getTaskResponseMethod) == null) {
MsgGrpc.getTaskResponseMethod = getTaskResponseMethod =
io.grpc.MethodDescriptor.<shentu.oracle.v1alpha1.Tx.MsgTaskResponse, shentu.oracle.v1alpha1.Tx.MsgTaskResponseResponse>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "TaskResponse"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
shentu.oracle.v1alpha1.Tx.MsgTaskResponse.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
shentu.oracle.v1alpha1.Tx.MsgTaskResponseResponse.getDefaultInstance()))
.setSchemaDescriptor(new MsgMethodDescriptorSupplier("TaskResponse"))
.build();
}
}
}
return getTaskResponseMethod;
}
private static volatile io.grpc.MethodDescriptor<shentu.oracle.v1alpha1.Tx.MsgDeleteTask,
shentu.oracle.v1alpha1.Tx.MsgDeleteTaskResponse> getDeleteTaskMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "DeleteTask",
requestType = shentu.oracle.v1alpha1.Tx.MsgDeleteTask.class,
responseType = shentu.oracle.v1alpha1.Tx.MsgDeleteTaskResponse.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<shentu.oracle.v1alpha1.Tx.MsgDeleteTask,
shentu.oracle.v1alpha1.Tx.MsgDeleteTaskResponse> getDeleteTaskMethod() {
io.grpc.MethodDescriptor<shentu.oracle.v1alpha1.Tx.MsgDeleteTask, shentu.oracle.v1alpha1.Tx.MsgDeleteTaskResponse> getDeleteTaskMethod;
if ((getDeleteTaskMethod = MsgGrpc.getDeleteTaskMethod) == null) {
synchronized (MsgGrpc.class) {
if ((getDeleteTaskMethod = MsgGrpc.getDeleteTaskMethod) == null) {
MsgGrpc.getDeleteTaskMethod = getDeleteTaskMethod =
io.grpc.MethodDescriptor.<shentu.oracle.v1alpha1.Tx.MsgDeleteTask, shentu.oracle.v1alpha1.Tx.MsgDeleteTaskResponse>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "DeleteTask"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
shentu.oracle.v1alpha1.Tx.MsgDeleteTask.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
shentu.oracle.v1alpha1.Tx.MsgDeleteTaskResponse.getDefaultInstance()))
.setSchemaDescriptor(new MsgMethodDescriptorSupplier("DeleteTask"))
.build();
}
}
}
return getDeleteTaskMethod;
}
/**
* Creates a new async stub that supports all call types for the service
*/
public static MsgStub newStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<MsgStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<MsgStub>() {
@java.lang.Override
public MsgStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new MsgStub(channel, callOptions);
}
};
return MsgStub.newStub(factory, channel);
}
/**
* Creates a new blocking-style stub that supports unary and streaming output calls on the service
*/
public static MsgBlockingStub newBlockingStub(
io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<MsgBlockingStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<MsgBlockingStub>() {
@java.lang.Override
public MsgBlockingStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new MsgBlockingStub(channel, callOptions);
}
};
return MsgBlockingStub.newStub(factory, channel);
}
/**
* Creates a new ListenableFuture-style stub that supports unary calls on the service
*/
public static MsgFutureStub newFutureStub(
io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<MsgFutureStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<MsgFutureStub>() {
@java.lang.Override
public MsgFutureStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new MsgFutureStub(channel, callOptions);
}
};
return MsgFutureStub.newStub(factory, channel);
}
/**
* <pre>
* Msg defines the shield Msg service.
* </pre>
*/
public static abstract class MsgImplBase implements io.grpc.BindableService {
/**
*/
public void createOperator(shentu.oracle.v1alpha1.Tx.MsgCreateOperator request,
io.grpc.stub.StreamObserver<shentu.oracle.v1alpha1.Tx.MsgCreateOperatorResponse> responseObserver) {
asyncUnimplementedUnaryCall(getCreateOperatorMethod(), responseObserver);
}
/**
*/
public void removeOperator(shentu.oracle.v1alpha1.Tx.MsgRemoveOperator request,
io.grpc.stub.StreamObserver<shentu.oracle.v1alpha1.Tx.MsgRemoveOperatorResponse> responseObserver) {
asyncUnimplementedUnaryCall(getRemoveOperatorMethod(), responseObserver);
}
/**
*/
public void addCollateral(shentu.oracle.v1alpha1.Tx.MsgAddCollateral request,
io.grpc.stub.StreamObserver<shentu.oracle.v1alpha1.Tx.MsgAddCollateralResponse> responseObserver) {
asyncUnimplementedUnaryCall(getAddCollateralMethod(), responseObserver);
}
/**
*/
public void reduceCollateral(shentu.oracle.v1alpha1.Tx.MsgReduceCollateral request,
io.grpc.stub.StreamObserver<shentu.oracle.v1alpha1.Tx.MsgReduceCollateralResponse> responseObserver) {
asyncUnimplementedUnaryCall(getReduceCollateralMethod(), responseObserver);
}
/**
*/
public void withdrawReward(shentu.oracle.v1alpha1.Tx.MsgWithdrawReward request,
io.grpc.stub.StreamObserver<shentu.oracle.v1alpha1.Tx.MsgWithdrawRewardResponse> responseObserver) {
asyncUnimplementedUnaryCall(getWithdrawRewardMethod(), responseObserver);
}
/**
*/
public void createTask(shentu.oracle.v1alpha1.Tx.MsgCreateTask request,
io.grpc.stub.StreamObserver<shentu.oracle.v1alpha1.Tx.MsgCreateTaskResponse> responseObserver) {
asyncUnimplementedUnaryCall(getCreateTaskMethod(), responseObserver);
}
/**
*/
public void taskResponse(shentu.oracle.v1alpha1.Tx.MsgTaskResponse request,
io.grpc.stub.StreamObserver<shentu.oracle.v1alpha1.Tx.MsgTaskResponseResponse> responseObserver) {
asyncUnimplementedUnaryCall(getTaskResponseMethod(), responseObserver);
}
/**
*/
public void deleteTask(shentu.oracle.v1alpha1.Tx.MsgDeleteTask request,
io.grpc.stub.StreamObserver<shentu.oracle.v1alpha1.Tx.MsgDeleteTaskResponse> responseObserver) {
asyncUnimplementedUnaryCall(getDeleteTaskMethod(), responseObserver);
}
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
getCreateOperatorMethod(),
asyncUnaryCall(
new MethodHandlers<
shentu.oracle.v1alpha1.Tx.MsgCreateOperator,
shentu.oracle.v1alpha1.Tx.MsgCreateOperatorResponse>(
this, METHODID_CREATE_OPERATOR)))
.addMethod(
getRemoveOperatorMethod(),
asyncUnaryCall(
new MethodHandlers<
shentu.oracle.v1alpha1.Tx.MsgRemoveOperator,
shentu.oracle.v1alpha1.Tx.MsgRemoveOperatorResponse>(
this, METHODID_REMOVE_OPERATOR)))
.addMethod(
getAddCollateralMethod(),
asyncUnaryCall(
new MethodHandlers<
shentu.oracle.v1alpha1.Tx.MsgAddCollateral,
shentu.oracle.v1alpha1.Tx.MsgAddCollateralResponse>(
this, METHODID_ADD_COLLATERAL)))
.addMethod(
getReduceCollateralMethod(),
asyncUnaryCall(
new MethodHandlers<
shentu.oracle.v1alpha1.Tx.MsgReduceCollateral,
shentu.oracle.v1alpha1.Tx.MsgReduceCollateralResponse>(
this, METHODID_REDUCE_COLLATERAL)))
.addMethod(
getWithdrawRewardMethod(),
asyncUnaryCall(
new MethodHandlers<
shentu.oracle.v1alpha1.Tx.MsgWithdrawReward,
shentu.oracle.v1alpha1.Tx.MsgWithdrawRewardResponse>(
this, METHODID_WITHDRAW_REWARD)))
.addMethod(
getCreateTaskMethod(),
asyncUnaryCall(
new MethodHandlers<
shentu.oracle.v1alpha1.Tx.MsgCreateTask,
shentu.oracle.v1alpha1.Tx.MsgCreateTaskResponse>(
this, METHODID_CREATE_TASK)))
.addMethod(
getTaskResponseMethod(),
asyncUnaryCall(
new MethodHandlers<
shentu.oracle.v1alpha1.Tx.MsgTaskResponse,
shentu.oracle.v1alpha1.Tx.MsgTaskResponseResponse>(
this, METHODID_TASK_RESPONSE)))
.addMethod(
getDeleteTaskMethod(),
asyncUnaryCall(
new MethodHandlers<
shentu.oracle.v1alpha1.Tx.MsgDeleteTask,
shentu.oracle.v1alpha1.Tx.MsgDeleteTaskResponse>(
this, METHODID_DELETE_TASK)))
.build();
}
}
/**
* <pre>
* Msg defines the shield Msg service.
* </pre>
*/
public static final class MsgStub extends io.grpc.stub.AbstractAsyncStub<MsgStub> {
private MsgStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected MsgStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new MsgStub(channel, callOptions);
}
/**
*/
public void createOperator(shentu.oracle.v1alpha1.Tx.MsgCreateOperator request,
io.grpc.stub.StreamObserver<shentu.oracle.v1alpha1.Tx.MsgCreateOperatorResponse> responseObserver) {
asyncUnaryCall(
getChannel().newCall(getCreateOperatorMethod(), getCallOptions()), request, responseObserver);
}
/**
*/
public void removeOperator(shentu.oracle.v1alpha1.Tx.MsgRemoveOperator request,
io.grpc.stub.StreamObserver<shentu.oracle.v1alpha1.Tx.MsgRemoveOperatorResponse> responseObserver) {
asyncUnaryCall(
getChannel().newCall(getRemoveOperatorMethod(), getCallOptions()), request, responseObserver);
}
/**
*/
public void addCollateral(shentu.oracle.v1alpha1.Tx.MsgAddCollateral request,
io.grpc.stub.StreamObserver<shentu.oracle.v1alpha1.Tx.MsgAddCollateralResponse> responseObserver) {
asyncUnaryCall(
getChannel().newCall(getAddCollateralMethod(), getCallOptions()), request, responseObserver);
}
/**
*/
public void reduceCollateral(shentu.oracle.v1alpha1.Tx.MsgReduceCollateral request,
io.grpc.stub.StreamObserver<shentu.oracle.v1alpha1.Tx.MsgReduceCollateralResponse> responseObserver) {
asyncUnaryCall(
getChannel().newCall(getReduceCollateralMethod(), getCallOptions()), request, responseObserver);
}
/**
*/
public void withdrawReward(shentu.oracle.v1alpha1.Tx.MsgWithdrawReward request,
io.grpc.stub.StreamObserver<shentu.oracle.v1alpha1.Tx.MsgWithdrawRewardResponse> responseObserver) {
asyncUnaryCall(
getChannel().newCall(getWithdrawRewardMethod(), getCallOptions()), request, responseObserver);
}
/**
*/
public void createTask(shentu.oracle.v1alpha1.Tx.MsgCreateTask request,
io.grpc.stub.StreamObserver<shentu.oracle.v1alpha1.Tx.MsgCreateTaskResponse> responseObserver) {
asyncUnaryCall(
getChannel().newCall(getCreateTaskMethod(), getCallOptions()), request, responseObserver);
}
/**
*/
public void taskResponse(shentu.oracle.v1alpha1.Tx.MsgTaskResponse request,
io.grpc.stub.StreamObserver<shentu.oracle.v1alpha1.Tx.MsgTaskResponseResponse> responseObserver) {
asyncUnaryCall(
getChannel().newCall(getTaskResponseMethod(), getCallOptions()), request, responseObserver);
}
/**
*/
public void deleteTask(shentu.oracle.v1alpha1.Tx.MsgDeleteTask request,
io.grpc.stub.StreamObserver<shentu.oracle.v1alpha1.Tx.MsgDeleteTaskResponse> responseObserver) {
asyncUnaryCall(
getChannel().newCall(getDeleteTaskMethod(), getCallOptions()), request, responseObserver);
}
}
/**
* <pre>
* Msg defines the shield Msg service.
* </pre>
*/
public static final class MsgBlockingStub extends io.grpc.stub.AbstractBlockingStub<MsgBlockingStub> {
private MsgBlockingStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected MsgBlockingStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new MsgBlockingStub(channel, callOptions);
}
/**
*/
public shentu.oracle.v1alpha1.Tx.MsgCreateOperatorResponse createOperator(shentu.oracle.v1alpha1.Tx.MsgCreateOperator request) {
return blockingUnaryCall(
getChannel(), getCreateOperatorMethod(), getCallOptions(), request);
}
/**
*/
public shentu.oracle.v1alpha1.Tx.MsgRemoveOperatorResponse removeOperator(shentu.oracle.v1alpha1.Tx.MsgRemoveOperator request) {
return blockingUnaryCall(
getChannel(), getRemoveOperatorMethod(), getCallOptions(), request);
}
/**
*/
public shentu.oracle.v1alpha1.Tx.MsgAddCollateralResponse addCollateral(shentu.oracle.v1alpha1.Tx.MsgAddCollateral request) {
return blockingUnaryCall(
getChannel(), getAddCollateralMethod(), getCallOptions(), request);
}
/**
*/
public shentu.oracle.v1alpha1.Tx.MsgReduceCollateralResponse reduceCollateral(shentu.oracle.v1alpha1.Tx.MsgReduceCollateral request) {
return blockingUnaryCall(
getChannel(), getReduceCollateralMethod(), getCallOptions(), request);
}
/**
*/
public shentu.oracle.v1alpha1.Tx.MsgWithdrawRewardResponse withdrawReward(shentu.oracle.v1alpha1.Tx.MsgWithdrawReward request) {
return blockingUnaryCall(
getChannel(), getWithdrawRewardMethod(), getCallOptions(), request);
}
/**
*/
public shentu.oracle.v1alpha1.Tx.MsgCreateTaskResponse createTask(shentu.oracle.v1alpha1.Tx.MsgCreateTask request) {
return blockingUnaryCall(
getChannel(), getCreateTaskMethod(), getCallOptions(), request);
}
/**
*/
public shentu.oracle.v1alpha1.Tx.MsgTaskResponseResponse taskResponse(shentu.oracle.v1alpha1.Tx.MsgTaskResponse request) {
return blockingUnaryCall(
getChannel(), getTaskResponseMethod(), getCallOptions(), request);
}
/**
*/
public shentu.oracle.v1alpha1.Tx.MsgDeleteTaskResponse deleteTask(shentu.oracle.v1alpha1.Tx.MsgDeleteTask request) {
return blockingUnaryCall(
getChannel(), getDeleteTaskMethod(), getCallOptions(), request);
}
}
/**
* <pre>
* Msg defines the shield Msg service.
* </pre>
*/
public static final class MsgFutureStub extends io.grpc.stub.AbstractFutureStub<MsgFutureStub> {
private MsgFutureStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected MsgFutureStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new MsgFutureStub(channel, callOptions);
}
/**
*/
public com.google.common.util.concurrent.ListenableFuture<shentu.oracle.v1alpha1.Tx.MsgCreateOperatorResponse> createOperator(
shentu.oracle.v1alpha1.Tx.MsgCreateOperator request) {
return futureUnaryCall(
getChannel().newCall(getCreateOperatorMethod(), getCallOptions()), request);
}
/**
*/
public com.google.common.util.concurrent.ListenableFuture<shentu.oracle.v1alpha1.Tx.MsgRemoveOperatorResponse> removeOperator(
shentu.oracle.v1alpha1.Tx.MsgRemoveOperator request) {
return futureUnaryCall(
getChannel().newCall(getRemoveOperatorMethod(), getCallOptions()), request);
}
/**
*/
public com.google.common.util.concurrent.ListenableFuture<shentu.oracle.v1alpha1.Tx.MsgAddCollateralResponse> addCollateral(
shentu.oracle.v1alpha1.Tx.MsgAddCollateral request) {
return futureUnaryCall(
getChannel().newCall(getAddCollateralMethod(), getCallOptions()), request);
}
/**
*/
public com.google.common.util.concurrent.ListenableFuture<shentu.oracle.v1alpha1.Tx.MsgReduceCollateralResponse> reduceCollateral(
shentu.oracle.v1alpha1.Tx.MsgReduceCollateral request) {
return futureUnaryCall(
getChannel().newCall(getReduceCollateralMethod(), getCallOptions()), request);
}
/**
*/
public com.google.common.util.concurrent.ListenableFuture<shentu.oracle.v1alpha1.Tx.MsgWithdrawRewardResponse> withdrawReward(
shentu.oracle.v1alpha1.Tx.MsgWithdrawReward request) {
return futureUnaryCall(
getChannel().newCall(getWithdrawRewardMethod(), getCallOptions()), request);
}
/**
*/
public com.google.common.util.concurrent.ListenableFuture<shentu.oracle.v1alpha1.Tx.MsgCreateTaskResponse> createTask(
shentu.oracle.v1alpha1.Tx.MsgCreateTask request) {
return futureUnaryCall(
getChannel().newCall(getCreateTaskMethod(), getCallOptions()), request);
}
/**
*/
public com.google.common.util.concurrent.ListenableFuture<shentu.oracle.v1alpha1.Tx.MsgTaskResponseResponse> taskResponse(
shentu.oracle.v1alpha1.Tx.MsgTaskResponse request) {
return futureUnaryCall(
getChannel().newCall(getTaskResponseMethod(), getCallOptions()), request);
}
/**
*/
public com.google.common.util.concurrent.ListenableFuture<shentu.oracle.v1alpha1.Tx.MsgDeleteTaskResponse> deleteTask(
shentu.oracle.v1alpha1.Tx.MsgDeleteTask request) {
return futureUnaryCall(
getChannel().newCall(getDeleteTaskMethod(), getCallOptions()), request);
}
}
private static final int METHODID_CREATE_OPERATOR = 0;
private static final int METHODID_REMOVE_OPERATOR = 1;
private static final int METHODID_ADD_COLLATERAL = 2;
private static final int METHODID_REDUCE_COLLATERAL = 3;
private static final int METHODID_WITHDRAW_REWARD = 4;
private static final int METHODID_CREATE_TASK = 5;
private static final int METHODID_TASK_RESPONSE = 6;
private static final int METHODID_DELETE_TASK = 7;
private static final class MethodHandlers<Req, Resp> implements
io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
private final MsgImplBase serviceImpl;
private final int methodId;
MethodHandlers(MsgImplBase serviceImpl, int methodId) {
this.serviceImpl = serviceImpl;
this.methodId = methodId;
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
case METHODID_CREATE_OPERATOR:
serviceImpl.createOperator((shentu.oracle.v1alpha1.Tx.MsgCreateOperator) request,
(io.grpc.stub.StreamObserver<shentu.oracle.v1alpha1.Tx.MsgCreateOperatorResponse>) responseObserver);
break;
case METHODID_REMOVE_OPERATOR:
serviceImpl.removeOperator((shentu.oracle.v1alpha1.Tx.MsgRemoveOperator) request,
(io.grpc.stub.StreamObserver<shentu.oracle.v1alpha1.Tx.MsgRemoveOperatorResponse>) responseObserver);
break;
case METHODID_ADD_COLLATERAL:
serviceImpl.addCollateral((shentu.oracle.v1alpha1.Tx.MsgAddCollateral) request,
(io.grpc.stub.StreamObserver<shentu.oracle.v1alpha1.Tx.MsgAddCollateralResponse>) responseObserver);
break;
case METHODID_REDUCE_COLLATERAL:
serviceImpl.reduceCollateral((shentu.oracle.v1alpha1.Tx.MsgReduceCollateral) request,
(io.grpc.stub.StreamObserver<shentu.oracle.v1alpha1.Tx.MsgReduceCollateralResponse>) responseObserver);
break;
case METHODID_WITHDRAW_REWARD:
serviceImpl.withdrawReward((shentu.oracle.v1alpha1.Tx.MsgWithdrawReward) request,
(io.grpc.stub.StreamObserver<shentu.oracle.v1alpha1.Tx.MsgWithdrawRewardResponse>) responseObserver);
break;
case METHODID_CREATE_TASK:
serviceImpl.createTask((shentu.oracle.v1alpha1.Tx.MsgCreateTask) request,
(io.grpc.stub.StreamObserver<shentu.oracle.v1alpha1.Tx.MsgCreateTaskResponse>) responseObserver);
break;
case METHODID_TASK_RESPONSE:
serviceImpl.taskResponse((shentu.oracle.v1alpha1.Tx.MsgTaskResponse) request,
(io.grpc.stub.StreamObserver<shentu.oracle.v1alpha1.Tx.MsgTaskResponseResponse>) responseObserver);
break;
case METHODID_DELETE_TASK:
serviceImpl.deleteTask((shentu.oracle.v1alpha1.Tx.MsgDeleteTask) request,
(io.grpc.stub.StreamObserver<shentu.oracle.v1alpha1.Tx.MsgDeleteTaskResponse>) responseObserver);
break;
default:
throw new AssertionError();
}
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public io.grpc.stub.StreamObserver<Req> invoke(
io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
default:
throw new AssertionError();
}
}
}
private static abstract class MsgBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier {
MsgBaseDescriptorSupplier() {}
@java.lang.Override
public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() {
return shentu.oracle.v1alpha1.Tx.getDescriptor();
}
@java.lang.Override
public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() {
return getFileDescriptor().findServiceByName("Msg");
}
}
private static final class MsgFileDescriptorSupplier
extends MsgBaseDescriptorSupplier {
MsgFileDescriptorSupplier() {}
}
private static final class MsgMethodDescriptorSupplier
extends MsgBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoMethodDescriptorSupplier {
private final String methodName;
MsgMethodDescriptorSupplier(String methodName) {
this.methodName = methodName;
}
@java.lang.Override
public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() {
return getServiceDescriptor().findMethodByName(methodName);
}
}
private static volatile io.grpc.ServiceDescriptor serviceDescriptor;
public static io.grpc.ServiceDescriptor getServiceDescriptor() {
io.grpc.ServiceDescriptor result = serviceDescriptor;
if (result == null) {
synchronized (MsgGrpc.class) {
result = serviceDescriptor;
if (result == null) {
serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME)
.setSchemaDescriptor(new MsgFileDescriptorSupplier())
.addMethod(getCreateOperatorMethod())
.addMethod(getRemoveOperatorMethod())
.addMethod(getAddCollateralMethod())
.addMethod(getReduceCollateralMethod())
.addMethod(getWithdrawRewardMethod())
.addMethod(getCreateTaskMethod())
.addMethod(getTaskResponseMethod())
.addMethod(getDeleteTaskMethod())
.build();
}
}
}
return result;
}
}
| 46.344282
| 157
| 0.716761
|
c648b930017811ca81aab27d7e036c382e9896c1
| 146
|
package de.tum.in.www1.artemis.domain.enumeration;
/**
* The SubmissionType enumeration.
*/
public enum SubmissionType {
MANUAL, TIMEOUT
}
| 16.222222
| 50
| 0.732877
|
35c8f4e7bca975dec30675c764f3e7f999dc6523
| 317
|
package com.example.demo.net;
import com.example.demo.bean.User;
import io.reactivex.Observable;
import okhttp3.ResponseBody;
import retrofit2.Response;
import retrofit2.http.GET;
/**
* Created by Pen on 2017/9/22.
*/
public interface Apis3 {
@GET("test/user.xml")
Observable<ResponseBody> getXml();
}
| 16.684211
| 38
| 0.731861
|
d85032816e5094c95214916ce374b87ff84781bd
| 975
|
/*
* Copyright (C) 2016 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.strata.calc;
import static com.opengamma.strata.collect.TestHelper.assertJodaConvert;
import static com.opengamma.strata.collect.TestHelper.assertSerialization;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
/**
* Test {@link ColumnName}.
*/
public class ColumnNameTest {
//-------------------------------------------------------------------------
@Test
public void test_builder_columnNameFromMeasure() {
ColumnName test = ColumnName.of("Test");
assertThat(test.getName()).isEqualTo("Test");
}
//-------------------------------------------------------------------------
@Test
public void test_serialization() {
ColumnName test = ColumnName.of("Test");
assertSerialization(test);
assertJodaConvert(ColumnName.class, test);
}
}
| 27.857143
| 86
| 0.624615
|
e7094a51a1d776af5683616d72c3c3ef22ff9853
| 3,386
|
package com.helospark.SparkTemplatingPlugin.integration.exportimport;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.verify;
import static org.mockito.MockitoAnnotations.initMocks;
import java.util.Arrays;
import java.util.Optional;
import org.eclipse.core.runtime.IProgressMonitor;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.helospark.sparktemplatingplugin.DiContainer;
import com.helospark.sparktemplatingplugin.repository.ScriptRepository;
import com.helospark.sparktemplatingplugin.repository.domain.ScriptEntity;
import com.helospark.sparktemplatingplugin.scriptexport.job.ExportJobWorker;
import com.helospark.sparktemplatingplugin.scriptimport.job.ImportJobWorker;
import com.helospark.sparktemplatingplugin.support.fileoperation.FileContentReader;
import com.helospark.sparktemplatingplugin.support.fileoperation.FileOutputWriter;
public class ExportImportIT {
private ImportJobWorker importJobWorker;
private ExportJobWorker exportJobWorker;
private ScriptEntity firstScript = new ScriptEntity("commandName1", "script1", 1);
private ScriptEntity secondScript = new ScriptEntity("commandName2", "script2", 2);
@Mock
private IProgressMonitor progressMonitor;
@Mock
private FileContentReader fileContentReader;
@Mock
private FileOutputWriter fileOutputWriter;
@Mock
private ScriptRepository scriptRepository;
@BeforeMethod
public void setUp() {
initMocks(this);
DiContainer.clearDiContainer();
// Override real dependencies with mocks
DiContainer.addDependency(fileContentReader);
DiContainer.addDependency(fileOutputWriter);
DiContainer.addDependency(fileContentReader);
DiContainer.addDependency(scriptRepository);
// end of overrides
DiContainer.initializeDiContainer();
importJobWorker = DiContainer.getDependency(ImportJobWorker.class);
exportJobWorker = DiContainer.getDependency(ExportJobWorker.class);
}
@Test
public void testExportThenImportShouldLoadSameDataAsExported() {
// GIVEN that we have some script
given(scriptRepository.loadAll()).willReturn(Arrays.asList(firstScript, secondScript));
// WHEN we export these scripts
exportJobWorker.export("fileName");
byte[] exportedByteData = extractSavedZipBytes();
// AND then importing the exported bytes when no commands exists
given(fileContentReader.loadContent("fileName")).willReturn(exportedByteData);
given(scriptRepository.loadByCommandName(anyString())).willReturn(Optional.empty());
importJobWorker.importToScriptRepository("fileName");
// THEN we get back the same scripts
verify(scriptRepository).saveNewScript(firstScript);
verify(scriptRepository).saveNewScript(secondScript);
}
private byte[] extractSavedZipBytes() {
ArgumentCaptor<byte[]> byteDataCaptor = ArgumentCaptor.forClass(byte[].class);
ArgumentCaptor<String> commandNameCaptor = ArgumentCaptor.forClass(String.class);
verify(fileOutputWriter).saveFile(byteDataCaptor.capture(), commandNameCaptor.capture());
return byteDataCaptor.getValue();
}
}
| 38.91954
| 97
| 0.768458
|
89bfad1f1182976df96bf7fca7bd2960f1e293dc
| 2,801
|
package gov.faa.airport.status.test;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import static org.junit.Assert.assertNotNull;
import java.io.StringReader;
import javax.json.Json;
import javax.json.JsonReader;
import javax.json.JsonObject;
import org.junit.Test;
// This is a simple test class that shows how to use the JAX-RS API to call the Airport Status service
public class RemoteCallTest {
@Test
public void getDullesProd () {
String response = new String("Empty");
try {
String token = getAuthorization();
assertNotNull(token);
Client client = ClientBuilder.newClient();
// The target for external services is soa.smext.faa.gov. The URI path depends on the service being called, obviously
WebTarget webTarget = client.target("https://soa.smext.faa.gov/api/airport/status");
WebTarget dulles = webTarget.path("IAD");
// The media type is optional. Here we specify JSON, but could have also specified APPLICATION_XML instead
Invocation.Builder invoke = dulles.request(MediaType.APPLICATION_JSON);
// The Authorization header must be obtained from the OAuth authentication / identity provider.
// This is for illustrative purposes only.
invoke.header("Authorization", "Bearer "+token);
response = invoke.get(String.class);
System.out.println(response);
}
catch (Exception exGet) {
exGet.printStackTrace();
System.out.println(response);
}
}
public String getAuthorization () {
String token = new String ();
String emptyJson = new String ("{}");
Client client = ClientBuilder.newClient();
// Setup the target of the API gateway server that issues tokens
WebTarget base = client.target("https://soa.smext.faa.gov/auth/oauth/v2/token");
// Here we supply the client identifier and secret as provided by the
// API registrar
WebTarget oauth = base.queryParam("client_id", "ADE320@faa.gov")
.queryParam("client_secret", "770260e9-5584-4270-905f-efea7713c1b5")
.queryParam("grant_type", "client_credentials");
Invocation.Builder invoke = oauth.request(MediaType.APPLICATION_JSON);
// Have to make sure the request is a POST as the GET verb is not supported
String response = invoke.post(Entity.entity(emptyJson, MediaType.APPLICATION_JSON), String.class);
JsonReader jr = Json.createReader(new StringReader(response.toString()));
JsonObject jobject = jr.readObject();
// Finally get the token out of the JSON response string
token = jobject.getString("access_token");
return token;
}
}
| 33.746988
| 121
| 0.712603
|
652e90fa9997c2c725531f125ca9359a7489869d
| 367
|
package ro.asee.csie.cts.g1093.dp.chain;
public class GroupMessageModule extends GenericMessageHandler{
@Override
public void processMessage(Message message) {
if(message.destination.toLowerCase().equals("@everyone")) {
System.out.println("Group message: " + message.text);
}
if(this.next != null) {
this.next.processMessage(message);
}
}
}
| 20.388889
| 62
| 0.713896
|
90b7d4a402aecf75b14340a036deb2f3d897cba3
| 1,879
|
import java.util.Comparator;
public class testHeap {
public static void main(String[] args) {
Heap heap = new Heap(new compare());
// numbers 35 33 42 10 14 19 27 44 26 31
// min-heap should be 10 14 19 26 31 42 27 44 35 33
// max-heap should be 44 42 35 33 31 19 27 10 26 14
myObj o1 = new myObj(35);
myObj o2 = new myObj(33);
myObj o3 = new myObj(42);
myObj o4 = new myObj(10);
myObj o5 = new myObj(14);
myObj o6 = new myObj(19);
myObj o7 = new myObj(27);
myObj o8 = new myObj(44);
myObj o9 = new myObj(26);
myObj o10 = new myObj(31);
heap.insert(o1);
heap.insert(o2);
heap.insert(o3);
heap.insert(o4);
heap.insert(o5);
heap.insert(o6);
heap.insert(o7);
heap.insert(o8);
heap.insert(o9);
heap.insert(o10);
return;
}
}
class myObj {
int x;
public myObj(int x) {
this.x = x;
}
}
class compare implements Comparator<Object> {
@Override
public int compare(Object o1, Object o2) {
if(o1 instanceof myObj) // <---------------- use instanceof 'myObject' with the Object you want to use in your heap
return compare((myObj) o1, (myObj) o2); // <---------------- replace 'myObject' with the Object you want to use
else
return 0;
}
public int compare(myObj o1, myObj o2) { // <---------------- replace 'myObject' with the Object you want to use
/*
--------------------------------
Your compare function goes here!
--------------------------------
example:
if(o1.x > o2.x)
return -1;
if(o1.x < o2.x)
return 1;
*/
return 0;
}
}
| 23.197531
| 147
| 0.478978
|
c1f689bbecb88c0ab71ff4afa63f06a804e982c5
| 2,570
|
package nl.vu.cs.amstel;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Map;
import org.apache.log4j.Logger;
import nl.vu.cs.amstel.user.Aggregator;
/**
* Class used for packing and unpacking aggregated values over the network.
* It is ought to be used in both master and worker nodes similarly, with
* and exception at unpacking, where the actions for the received values is
* different.
*
* @author claudiugh
*
*/
public class AggregatorStream {
protected Logger logger = Logger.getLogger("nl.vu.cs.amstel");
private static final int BUFFER_SIZE = 128;
private Map<String, AggregatorState> aggregators;
private ByteArrayOutputStream aggSendBuffer =
new ByteArrayOutputStream(BUFFER_SIZE);
private DataOutputStream aggStream = new DataOutputStream(aggSendBuffer);
public AggregatorStream(Map<String, AggregatorState> aggregators) {
this.aggregators = aggregators;
}
public byte[] pack() throws IOException {
aggSendBuffer.reset();
for (AggregatorState aggState : aggregators.values()) {
if (aggState.aggregator.hasValue()) {
aggStream.writeUTF(aggState.aggregator.getName());
aggState.aggregator.getValue().serialize(aggStream);
}
}
return aggSendBuffer.toByteArray();
}
@SuppressWarnings("unchecked")
private void unpack(byte[] buffer, boolean combine) throws IOException {
ByteArrayInputStream aggByteStream = new ByteArrayInputStream(buffer);
DataInputStream aggDataStream = new DataInputStream(aggByteStream);
while (aggByteStream.available() > 0) {
String aggKey = aggDataStream.readUTF();
if (!aggregators.containsKey(aggKey)) {
logger.error("Unknown aggregator: " + aggKey);
break;
}
AggregatorState aggState = aggregators.get(aggKey);
// using the current value to deserialize value
Aggregator agg = aggState.aggregator;
if (aggState.currentValue == null) {
aggState.currentValue = agg.newValue();
}
aggState.currentValue.deserialize(aggDataStream);
if (combine) {
if (agg.hasValue()) {
agg.combine(aggState.currentValue);
} else {
agg.init(aggState.currentValue);
}
}
}
}
/**
* unpack for worker node
*/
public void unpackAndUpdate(byte[] buffer) throws IOException {
unpack(buffer, false);
}
/**
* unpack for master node
* @param buffer
* @throws IOException
*/
public void unpackAndCombine(byte[] buffer) throws IOException {
unpack(buffer, true);
}
}
| 27.934783
| 75
| 0.732296
|
20622ff0696d70df49a87dc9f38e8016130ffed5
| 1,826
|
package com.glaurung.batMap.io;
import java.awt.Dimension;
import java.awt.Point;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import com.glaurung.batMap.vo.GuiData;
/**
* 数据持久化
*/
public class GuiDataPersister {
private final static String FILENAME = "batMap.conf";
private final static String DIRNAME = "conf";
/**
* 保存数据
* @param baseDir
* @param location
* @param size
*/
public static void save( String baseDir, Point location, Dimension size ) {
GuiData data = new GuiData( location, size );
FileOutputStream fileOutputStream;
try {
fileOutputStream = new FileOutputStream( getFile( baseDir ) );
ObjectOutputStream objectOutputStream = new ObjectOutputStream( fileOutputStream );
objectOutputStream.writeObject( data );
fileOutputStream.close();
} catch (IOException e) {
System.out.println( e );
}
}
public static GuiData load( String basedir ) {
try {
FileInputStream fileInputStream = new FileInputStream( getFile( basedir ) );
ObjectInputStream objectInputStream = new ObjectInputStream( fileInputStream );
GuiData data = (GuiData) objectInputStream.readObject();
return data;
} catch (IOException e) {
System.out.println( e );
} catch (ClassNotFoundException e) {
System.out.println( e );
}
return null;
}
private static File getFile( String basedir ) {
File dirFile = new File( basedir, DIRNAME );
File saveFile = new File( dirFile, FILENAME );
return saveFile;
}
}
| 28.092308
| 95
| 0.638554
|
9cb911b1d6e8722b569b8f5b36dd47fbf683ccba
| 800
|
package com.java110.things.entity.attendance;
import java.io.Serializable;
/**
* @ClassName ClockInDto 考勤对象类
* @Description TODO
* @Author wuxw
* @Date 2020/6/9 0:00
* @Version 1.0
* add by wuxw 2020/6/9
**/
public class ClockInDto implements Serializable {
private String staffId;
private String pic;
private String clockInTime;
public String getStaffId() {
return staffId;
}
public void setStaffId(String staffId) {
this.staffId = staffId;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public String getClockInTime() {
return clockInTime;
}
public void setClockInTime(String clockInTime) {
this.clockInTime = clockInTime;
}
}
| 17.777778
| 52
| 0.6375
|
75032075b17de9e788ee1465185404db2923e052
| 4,012
|
/*
* Copyright (c) 2020 Network New Technologies Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.networknt.schema;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Context for holding the output returned by the {@link Collector}
* implementations.
*/
public class CollectorContext {
// Using a namespace string as key in ThreadLocal so that it is unique in
// ThreadLocal.
static final String COLLECTOR_CONTEXT_THREAD_LOCAL_KEY = "com.networknt.schema.CollectorKey";
// Get an instance from thread info (which uses ThreadLocal).
public static CollectorContext getInstance() {
return (CollectorContext) ThreadInfo.get(COLLECTOR_CONTEXT_THREAD_LOCAL_KEY);
}
/**
* Map for holding the name and {@link Collector} or a simple Object.
*/
private Map<String, Object> collectorMap = new HashMap<String, Object>();
/**
* Map for holding the name and {@link Collector} class collect method output.
*/
private Map<String, Object> collectorLoadMap = new HashMap<String, Object>();
/**
* Adds a collector with give name. Preserving this method for backward
* compatibility.
*
* @param <E> element
* @param name String
* @param collector Collector
*/
public <E> void add(String name, Collector<E> collector) {
collectorMap.put(name, collector);
}
/**
* Adds a collector or a simple object with give name.
*
* @param <E> element
* @param object Object
* @param name String
*
*/
public <E> void add(String name, Object object) {
collectorMap.put(name, object);
}
/**
* Gets the data associated with a given name. Please note if you are using a
* Collector you should wait till the validation is complete to gather all data.
* <p>
* For a Collector, this method will return the collector as long as load method
* is not called. Once the load method is called this method will return the
* actual data collected by collector.
*
* @param name String
* @return Object
*/
public Object get(String name) {
Object object = collectorMap.get(name);
if (object instanceof Collector<?> && (collectorLoadMap.get(name) != null)) {
return collectorLoadMap.get(name);
}
return collectorMap.get(name);
}
/**
* Combines data with Collector identified by the given name.
*
* @param name String
* @param data Object
*/
public void combineWithCollector(String name, Object data) {
Object object = collectorMap.get(name);
if (object instanceof Collector<?>) {
Collector<?> collector = (Collector<?>) object;
collector.combine(data);
}
}
/**
* Reset the context
*/
void reset() {
this.collectorMap = new HashMap<String, Object>();
this.collectorLoadMap = new HashMap<String, Object>();
}
/**
* Loads data from all collectors.
*/
void loadCollectors() {
Set<Entry<String, Object>> entrySet = collectorMap.entrySet();
for (Entry<String, Object> entry : entrySet) {
if (entry.getValue() instanceof Collector<?>) {
Collector<?> collector = (Collector<?>) entry.getValue();
collectorLoadMap.put(entry.getKey(), collector.collect());
}
}
}
}
| 31.34375
| 97
| 0.642323
|
ae1380e94b1663ffdfd0d44dacc54c0fd602145b
| 1,054
|
package ix.ginas.models.serialization;
import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.Set;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import ix.core.models.Keyword;
import ix.ginas.models.GinasCommonSubData;
public class ReferenceSetSerializer extends JsonSerializer<Set<Keyword>> {
public ReferenceSetSerializer () {}
public void serialize (Set<Keyword> list, JsonGenerator jgen,
SerializerProvider provider)
throws IOException, JsonProcessingException {
Set<String> refs = new LinkedHashSet<String>();
for (Keyword val : list) {
if (GinasCommonSubData.REFERENCE.equals(val.label) || val.label==null) {
Keyword kw = (Keyword)val;
refs.add(kw.term);
}
}
provider.defaultSerializeValue(refs, jgen);
}
}
| 34
| 84
| 0.70019
|
39eccf7ec56603dbbbdd788a23654f3b66cb8975
| 14,658
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.management.monitor.models;
import com.azure.core.annotation.Immutable;
import com.azure.core.util.logging.ClientLogger;
import com.azure.management.monitor.EventLevel;
import com.azure.management.monitor.HttpRequestInfo;
import com.azure.management.monitor.SenderAuthorization;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.OffsetDateTime;
import java.util.Map;
/** The EventData model. */
@Immutable
public final class EventDataInner {
@JsonIgnore private final ClientLogger logger = new ClientLogger(EventDataInner.class);
/*
* The sender authorization information.
*/
@JsonProperty(value = "authorization", access = JsonProperty.Access.WRITE_ONLY)
private SenderAuthorization authorization;
/*
* key value pairs to identify ARM permissions.
*/
@JsonProperty(value = "claims", access = JsonProperty.Access.WRITE_ONLY)
private Map<String, String> claims;
/*
* the email address of the user who has performed the operation, the UPN
* claim or SPN claim based on availability.
*/
@JsonProperty(value = "caller", access = JsonProperty.Access.WRITE_ONLY)
private String caller;
/*
* the description of the event.
*/
@JsonProperty(value = "description", access = JsonProperty.Access.WRITE_ONLY)
private String description;
/*
* the Id of this event as required by ARM for RBAC. It contains the
* EventDataID and a timestamp information.
*/
@JsonProperty(value = "id", access = JsonProperty.Access.WRITE_ONLY)
private String id;
/*
* the event data Id. This is a unique identifier for an event.
*/
@JsonProperty(value = "eventDataId", access = JsonProperty.Access.WRITE_ONLY)
private String eventDataId;
/*
* the correlation Id, usually a GUID in the string format. The correlation
* Id is shared among the events that belong to the same uber operation.
*/
@JsonProperty(value = "correlationId", access = JsonProperty.Access.WRITE_ONLY)
private String correlationId;
/*
* the event name. This value should not be confused with OperationName.
* For practical purposes, OperationName might be more appealing to end
* users.
*/
@JsonProperty(value = "eventName", access = JsonProperty.Access.WRITE_ONLY)
private LocalizableStringInner eventName;
/*
* the event category.
*/
@JsonProperty(value = "category", access = JsonProperty.Access.WRITE_ONLY)
private LocalizableStringInner category;
/*
* the HTTP request info. Usually includes the 'clientRequestId',
* 'clientIpAddress' (IP address of the user who initiated the event) and
* 'method' (HTTP method e.g. PUT).
*/
@JsonProperty(value = "httpRequest", access = JsonProperty.Access.WRITE_ONLY)
private HttpRequestInfo httpRequest;
/*
* the event level
*/
@JsonProperty(value = "level", access = JsonProperty.Access.WRITE_ONLY)
private EventLevel level;
/*
* the resource group name of the impacted resource.
*/
@JsonProperty(value = "resourceGroupName", access = JsonProperty.Access.WRITE_ONLY)
private String resourceGroupName;
/*
* the resource provider name of the impacted resource.
*/
@JsonProperty(value = "resourceProviderName", access = JsonProperty.Access.WRITE_ONLY)
private LocalizableStringInner resourceProviderName;
/*
* the resource uri that uniquely identifies the resource that caused this
* event.
*/
@JsonProperty(value = "resourceId", access = JsonProperty.Access.WRITE_ONLY)
private String resourceId;
/*
* the resource type
*/
@JsonProperty(value = "resourceType", access = JsonProperty.Access.WRITE_ONLY)
private LocalizableStringInner resourceType;
/*
* It is usually a GUID shared among the events corresponding to single
* operation. This value should not be confused with EventName.
*/
@JsonProperty(value = "operationId", access = JsonProperty.Access.WRITE_ONLY)
private String operationId;
/*
* the operation name.
*/
@JsonProperty(value = "operationName", access = JsonProperty.Access.WRITE_ONLY)
private LocalizableStringInner operationName;
/*
* the set of <Key, Value> pairs (usually a Dictionary<String, String>)
* that includes details about the event.
*/
@JsonProperty(value = "properties", access = JsonProperty.Access.WRITE_ONLY)
private Map<String, String> properties;
/*
* a string describing the status of the operation. Some typical values
* are: Started, In progress, Succeeded, Failed, Resolved.
*/
@JsonProperty(value = "status", access = JsonProperty.Access.WRITE_ONLY)
private LocalizableStringInner status;
/*
* the event sub status. Most of the time, when included, this captures the
* HTTP status code of the REST call. Common values are: OK (HTTP Status
* Code: 200), Created (HTTP Status Code: 201), Accepted (HTTP Status Code:
* 202), No Content (HTTP Status Code: 204), Bad Request(HTTP Status Code:
* 400), Not Found (HTTP Status Code: 404), Conflict (HTTP Status Code:
* 409), Internal Server Error (HTTP Status Code: 500), Service Unavailable
* (HTTP Status Code:503), Gateway Timeout (HTTP Status Code: 504)
*/
@JsonProperty(value = "subStatus", access = JsonProperty.Access.WRITE_ONLY)
private LocalizableStringInner subStatus;
/*
* the timestamp of when the event was generated by the Azure service
* processing the request corresponding the event. It in ISO 8601 format.
*/
@JsonProperty(value = "eventTimestamp", access = JsonProperty.Access.WRITE_ONLY)
private OffsetDateTime eventTimestamp;
/*
* the timestamp of when the event became available for querying via this
* API. It is in ISO 8601 format. This value should not be confused
* eventTimestamp. As there might be a delay between the occurrence time of
* the event, and the time that the event is submitted to the Azure logging
* infrastructure.
*/
@JsonProperty(value = "submissionTimestamp", access = JsonProperty.Access.WRITE_ONLY)
private OffsetDateTime submissionTimestamp;
/*
* the Azure subscription Id usually a GUID.
*/
@JsonProperty(value = "subscriptionId", access = JsonProperty.Access.WRITE_ONLY)
private String subscriptionId;
/*
* the Azure tenant Id
*/
@JsonProperty(value = "tenantId", access = JsonProperty.Access.WRITE_ONLY)
private String tenantId;
/**
* Get the authorization property: The sender authorization information.
*
* @return the authorization value.
*/
public SenderAuthorization authorization() {
return this.authorization;
}
/**
* Get the claims property: key value pairs to identify ARM permissions.
*
* @return the claims value.
*/
public Map<String, String> claims() {
return this.claims;
}
/**
* Get the caller property: the email address of the user who has performed the operation, the UPN claim or SPN
* claim based on availability.
*
* @return the caller value.
*/
public String caller() {
return this.caller;
}
/**
* Get the description property: the description of the event.
*
* @return the description value.
*/
public String description() {
return this.description;
}
/**
* Get the id property: the Id of this event as required by ARM for RBAC. It contains the EventDataID and a
* timestamp information.
*
* @return the id value.
*/
public String id() {
return this.id;
}
/**
* Get the eventDataId property: the event data Id. This is a unique identifier for an event.
*
* @return the eventDataId value.
*/
public String eventDataId() {
return this.eventDataId;
}
/**
* Get the correlationId property: the correlation Id, usually a GUID in the string format. The correlation Id is
* shared among the events that belong to the same uber operation.
*
* @return the correlationId value.
*/
public String correlationId() {
return this.correlationId;
}
/**
* Get the eventName property: the event name. This value should not be confused with OperationName. For practical
* purposes, OperationName might be more appealing to end users.
*
* @return the eventName value.
*/
public LocalizableStringInner eventName() {
return this.eventName;
}
/**
* Get the category property: the event category.
*
* @return the category value.
*/
public LocalizableStringInner category() {
return this.category;
}
/**
* Get the httpRequest property: the HTTP request info. Usually includes the 'clientRequestId', 'clientIpAddress'
* (IP address of the user who initiated the event) and 'method' (HTTP method e.g. PUT).
*
* @return the httpRequest value.
*/
public HttpRequestInfo httpRequest() {
return this.httpRequest;
}
/**
* Get the level property: the event level.
*
* @return the level value.
*/
public EventLevel level() {
return this.level;
}
/**
* Get the resourceGroupName property: the resource group name of the impacted resource.
*
* @return the resourceGroupName value.
*/
public String resourceGroupName() {
return this.resourceGroupName;
}
/**
* Get the resourceProviderName property: the resource provider name of the impacted resource.
*
* @return the resourceProviderName value.
*/
public LocalizableStringInner resourceProviderName() {
return this.resourceProviderName;
}
/**
* Get the resourceId property: the resource uri that uniquely identifies the resource that caused this event.
*
* @return the resourceId value.
*/
public String resourceId() {
return this.resourceId;
}
/**
* Get the resourceType property: the resource type.
*
* @return the resourceType value.
*/
public LocalizableStringInner resourceType() {
return this.resourceType;
}
/**
* Get the operationId property: It is usually a GUID shared among the events corresponding to single operation.
* This value should not be confused with EventName.
*
* @return the operationId value.
*/
public String operationId() {
return this.operationId;
}
/**
* Get the operationName property: the operation name.
*
* @return the operationName value.
*/
public LocalizableStringInner operationName() {
return this.operationName;
}
/**
* Get the properties property: the set of <Key, Value> pairs (usually a Dictionary<String, String>)
* that includes details about the event.
*
* @return the properties value.
*/
public Map<String, String> properties() {
return this.properties;
}
/**
* Get the status property: a string describing the status of the operation. Some typical values are: Started, In
* progress, Succeeded, Failed, Resolved.
*
* @return the status value.
*/
public LocalizableStringInner status() {
return this.status;
}
/**
* Get the subStatus property: the event sub status. Most of the time, when included, this captures the HTTP status
* code of the REST call. Common values are: OK (HTTP Status Code: 200), Created (HTTP Status Code: 201), Accepted
* (HTTP Status Code: 202), No Content (HTTP Status Code: 204), Bad Request(HTTP Status Code: 400), Not Found (HTTP
* Status Code: 404), Conflict (HTTP Status Code: 409), Internal Server Error (HTTP Status Code: 500), Service
* Unavailable (HTTP Status Code:503), Gateway Timeout (HTTP Status Code: 504).
*
* @return the subStatus value.
*/
public LocalizableStringInner subStatus() {
return this.subStatus;
}
/**
* Get the eventTimestamp property: the timestamp of when the event was generated by the Azure service processing
* the request corresponding the event. It in ISO 8601 format.
*
* @return the eventTimestamp value.
*/
public OffsetDateTime eventTimestamp() {
return this.eventTimestamp;
}
/**
* Get the submissionTimestamp property: the timestamp of when the event became available for querying via this API.
* It is in ISO 8601 format. This value should not be confused eventTimestamp. As there might be a delay between the
* occurrence time of the event, and the time that the event is submitted to the Azure logging infrastructure.
*
* @return the submissionTimestamp value.
*/
public OffsetDateTime submissionTimestamp() {
return this.submissionTimestamp;
}
/**
* Get the subscriptionId property: the Azure subscription Id usually a GUID.
*
* @return the subscriptionId value.
*/
public String subscriptionId() {
return this.subscriptionId;
}
/**
* Get the tenantId property: the Azure tenant Id.
*
* @return the tenantId value.
*/
public String tenantId() {
return this.tenantId;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (authorization() != null) {
authorization().validate();
}
if (eventName() != null) {
eventName().validate();
}
if (category() != null) {
category().validate();
}
if (httpRequest() != null) {
httpRequest().validate();
}
if (resourceProviderName() != null) {
resourceProviderName().validate();
}
if (resourceType() != null) {
resourceType().validate();
}
if (operationName() != null) {
operationName().validate();
}
if (status() != null) {
status().validate();
}
if (subStatus() != null) {
subStatus().validate();
}
}
}
| 32.286344
| 120
| 0.656024
|
d8a941880678634aa0cb869d138ebf5701ab12eb
| 1,779
|
/*
* Licensed to the Sakai Foundation (SF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The SF 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.sakaiproject.nakamura.api.proxy;
import org.apache.sling.api.SlingHttpServletResponse;
import java.io.IOException;
import java.util.Map;
/**
*
*/
public interface ProxyPostProcessor {
/**
*
*/
public static final String SAKAI_POSTPROCESSOR = "sakai:postprocessor";
/**
* @param templateParams
* The parameters used to fill out the template. These are supplied as request
* parameters.
* @param response
* The response that will be sent to the user.
* @param proxyResponse
* The response as it came back from the remote resource.
* @throws IOException
*/
void process(Map<String, Object> templateParams, SlingHttpServletResponse response,
ProxyResponse proxyResponse) throws IOException;
/**
* @return The name of this ProxyPostProcessor. Nodes that want this processor to be run
* should set the sakai:postprocessor property to this value.
*/
String getName();
}
| 32.345455
| 90
| 0.718381
|
49fe975175412dd6526df59c36b81f9cbe4be747
| 21,604
|
/*
* Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.carbon.registry.jcr.version;
import javax.jcr.*;
import javax.jcr.lock.Lock;
import javax.jcr.lock.LockException;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.nodetype.NoSuchNodeTypeException;
import javax.jcr.nodetype.NodeDefinition;
import javax.jcr.nodetype.NodeType;
import javax.jcr.version.ActivityViolationException;
import javax.jcr.version.Version;
import javax.jcr.version.VersionException;
import javax.jcr.version.VersionHistory;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Calendar;
public class RegistryVersion implements Version {
private String versionName = "";
private long createdTime = 0;
private VersionHistory vh;
private String fNodepath = "";
private Session session;
public RegistryVersion(String versionId, long createdTime, String nodepath, Session session) {
this.versionName = versionId;
this.createdTime = createdTime;
this.fNodepath = nodepath;
this.session = session;
}
public void setVersionHistory(VersionHistory vh) {
this.vh = vh;
}
public VersionHistory getContainingHistory() throws RepositoryException {
return vh;
}
public Calendar getCreated() throws RepositoryException {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(createdTime);
return cal;
}
public Version getLinearSuccessor() throws RepositoryException { //TODO Under Full Versioning
return null;
}
public Version[] getSuccessors() throws RepositoryException { //TODO Under Full Versioning
return new Version[0];
}
public Version getLinearPredecessor() throws RepositoryException { //TODO Under Full Versioning
return null;
}
public Version[] getPredecessors() throws RepositoryException { //TODO Under Full Versioning
return new Version[0];
}
public Node getFrozenNode() throws RepositoryException { //TODO Under Full Versioning
return (Node) session.getItem(fNodepath);
}
// TODO All following Node inherited methods will be apply under full versioning
public Node addNode(String s) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, RepositoryException {
return null;
}
public Node addNode(String s, String s1) throws ItemExistsException, PathNotFoundException, NoSuchNodeTypeException, LockException, VersionException, ConstraintViolationException, RepositoryException {
return null;
}
public void orderBefore(String s, String s1) throws UnsupportedRepositoryOperationException, VersionException, ConstraintViolationException, ItemNotFoundException, LockException, RepositoryException {
}
public Property setProperty(String s, Value value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Property setProperty(String s, Value value, int i) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Property setProperty(String s, Value[] values) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Property setProperty(String s, Value[] values, int i) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Property setProperty(String s, String[] strings) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Property setProperty(String s, String[] strings, int i) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Property setProperty(String s, String s1) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Property setProperty(String s, String s1, int i) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Property setProperty(String s, InputStream inputStream) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Property setProperty(String s, Binary binary) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Property setProperty(String s, boolean b) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Property setProperty(String s, double v) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Property setProperty(String s, BigDecimal bigDecimal) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Property setProperty(String s, long l) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Property setProperty(String s, Calendar calendar) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Property setProperty(String s, Node node) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Node getNode(String s) throws PathNotFoundException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public NodeIterator getNodes() throws RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public NodeIterator getNodes(String s) throws RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public NodeIterator getNodes(String[] strings) throws RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Property getProperty(String s) throws PathNotFoundException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public PropertyIterator getProperties() throws RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public PropertyIterator getProperties(String s) throws RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public PropertyIterator getProperties(String[] strings) throws RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Item getPrimaryItem() throws ItemNotFoundException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public String getUUID() throws UnsupportedRepositoryOperationException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public String getIdentifier() throws RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public int getIndex() throws RepositoryException {
return 0; //To change body of implemented methods use File | Settings | File Templates.
}
public PropertyIterator getReferences() throws RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public PropertyIterator getReferences(String s) throws RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public PropertyIterator getWeakReferences() throws RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public PropertyIterator getWeakReferences(String s) throws RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public boolean hasNode(String s) throws RepositoryException {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
public boolean hasProperty(String s) throws RepositoryException {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
public boolean hasNodes() throws RepositoryException {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
public boolean hasProperties() throws RepositoryException {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
public NodeType getPrimaryNodeType() throws RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public NodeType[] getMixinNodeTypes() throws RepositoryException {
return new NodeType[0]; //To change body of implemented methods use File | Settings | File Templates.
}
public boolean isNodeType(String s) throws RepositoryException {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
public void setPrimaryType(String s) throws NoSuchNodeTypeException, VersionException, ConstraintViolationException, LockException, RepositoryException {
//To change body of implemented methods use File | Settings | File Templates.
}
public void addMixin(String s) throws NoSuchNodeTypeException, VersionException, ConstraintViolationException, LockException, RepositoryException {
//To change body of implemented methods use File | Settings | File Templates.
}
public void removeMixin(String s) throws NoSuchNodeTypeException, VersionException, ConstraintViolationException, LockException, RepositoryException {
//To change body of implemented methods use File | Settings | File Templates.
}
public boolean canAddMixin(String s) throws NoSuchNodeTypeException, RepositoryException {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
public NodeDefinition getDefinition() throws RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Version checkin() throws VersionException, UnsupportedRepositoryOperationException, InvalidItemStateException, LockException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public void checkout() throws UnsupportedRepositoryOperationException, LockException, ActivityViolationException, RepositoryException {
//To change body of implemented methods use File | Settings | File Templates.
}
public void doneMerge(Version version) throws VersionException, InvalidItemStateException, UnsupportedRepositoryOperationException, RepositoryException {
//To change body of implemented methods use File | Settings | File Templates.
}
public void cancelMerge(Version version) throws VersionException, InvalidItemStateException, UnsupportedRepositoryOperationException, RepositoryException {
//To change body of implemented methods use File | Settings | File Templates.
}
public void update(String s) throws NoSuchWorkspaceException, AccessDeniedException, LockException, InvalidItemStateException, RepositoryException {
//To change body of implemented methods use File | Settings | File Templates.
}
public NodeIterator merge(String s, boolean b) throws NoSuchWorkspaceException, AccessDeniedException, MergeException, LockException, InvalidItemStateException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public String getCorrespondingNodePath(String s) throws ItemNotFoundException, NoSuchWorkspaceException, AccessDeniedException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public NodeIterator getSharedSet() throws RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public void removeSharedSet() throws VersionException, LockException, ConstraintViolationException, RepositoryException {
//To change body of implemented methods use File | Settings | File Templates.
}
public void removeShare() throws VersionException, LockException, ConstraintViolationException, RepositoryException {
//To change body of implemented methods use File | Settings | File Templates.
}
public boolean isCheckedOut() throws RepositoryException {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
public void restore(String s, boolean b) throws VersionException, ItemExistsException, UnsupportedRepositoryOperationException, LockException, InvalidItemStateException, RepositoryException {
//To change body of implemented methods use File | Settings | File Templates.
}
public void restore(Version version, boolean b) throws VersionException, ItemExistsException, InvalidItemStateException, UnsupportedRepositoryOperationException, LockException, RepositoryException {
//To change body of implemented methods use File | Settings | File Templates.
}
public void restore(Version version, String s, boolean b) throws PathNotFoundException, ItemExistsException, VersionException, ConstraintViolationException, UnsupportedRepositoryOperationException, LockException, InvalidItemStateException, RepositoryException {
//To change body of implemented methods use File | Settings | File Templates.
}
public void restoreByLabel(String s, boolean b) throws VersionException, ItemExistsException, UnsupportedRepositoryOperationException, LockException, InvalidItemStateException, RepositoryException {
//To change body of implemented methods use File | Settings | File Templates.
}
public VersionHistory getVersionHistory() throws UnsupportedRepositoryOperationException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Version getBaseVersion() throws UnsupportedRepositoryOperationException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Lock lock(boolean b, boolean b1) throws UnsupportedRepositoryOperationException, LockException, AccessDeniedException, InvalidItemStateException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Lock getLock() throws UnsupportedRepositoryOperationException, LockException, AccessDeniedException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public void unlock() throws UnsupportedRepositoryOperationException, LockException, AccessDeniedException, InvalidItemStateException, RepositoryException {
//To change body of implemented methods use File | Settings | File Templates.
}
public boolean holdsLock() throws RepositoryException {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
public boolean isLocked() throws RepositoryException {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
public void followLifecycleTransition(String s) throws UnsupportedRepositoryOperationException, InvalidLifecycleTransitionException, RepositoryException {
//To change body of implemented methods use File | Settings | File Templates.
}
public String[] getAllowedLifecycleTransistions() throws UnsupportedRepositoryOperationException, RepositoryException {
return new String[0]; //To change body of implemented methods use File | Settings | File Templates.
}
public String getPath() throws RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public String getName() throws RepositoryException {
return versionName;
}
public Item getAncestor(int i) throws ItemNotFoundException, AccessDeniedException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Node getParent() throws ItemNotFoundException, AccessDeniedException, RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public int getDepth() throws RepositoryException {
return 0; //To change body of implemented methods use File | Settings | File Templates.
}
public Session getSession() throws RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public boolean isNode() {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
public boolean isNew() {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
public boolean isModified() {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
public boolean isSame(Item item) throws RepositoryException {
return this.getName().equals(item.getName());
}
public void accept(ItemVisitor itemVisitor) throws RepositoryException {
//To change body of implemented methods use File | Settings | File Templates.
}
public void save() throws AccessDeniedException, ItemExistsException, ConstraintViolationException, InvalidItemStateException, ReferentialIntegrityException, VersionException, LockException, NoSuchNodeTypeException, RepositoryException {
//To change body of implemented methods use File | Settings | File Templates.
}
public void refresh(boolean b) throws InvalidItemStateException, RepositoryException {
//To change body of implemented methods use File | Settings | File Templates.
}
public void remove() throws VersionException, LockException, ConstraintViolationException, AccessDeniedException, RepositoryException {
//To change body of implemented methods use File | Settings | File Templates.
}
}
| 50.009259
| 265
| 0.751666
|
54baf6622c81ae17931325f13bddb2d564add494
| 464
|
package org.ivangrod.needlehack.infrastructure.post.api.rest.inbound.dto;
import org.ivangrod.needlehack.application.post.search.PostFound;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
public class SearchPostResponse extends ResponseEntity<Page<PostFound>> {
public SearchPostResponse(Page<PostFound> body, HttpStatus status) {
super(body, status);
}
}
| 33.142857
| 73
| 0.803879
|
a6a330c008184955f489345caf3191fa5c5051a6
| 941
|
package net.marshmallow.BetterRecipeBook.Mixins;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.marshmallow.BetterRecipeBook.BetterRecipeBook;
import net.minecraft.recipe.Recipe;
import net.minecraft.recipe.book.RecipeBook;
import net.minecraft.util.Identifier;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import java.util.Set;
@Mixin(RecipeBook.class)
public class DisableBounce {
@Final @Shadow
protected Set<Identifier> toBeDisplayed;
/**
* @author marshmallow
*/
@Overwrite
@Environment(EnvType.CLIENT)
public boolean shouldDisplay(Recipe<?> recipe) {
if (!BetterRecipeBook.config.newRecipes.enableBounce) {
return false;
} else {
return toBeDisplayed.contains(recipe.getId());
}
}
}
| 27.676471
| 63
| 0.735388
|
646151d5111e5e067d1937a8653637d27097f7a5
| 9,795
|
package us.koller.cameraroll.data;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.preference.PreferenceManager;
import java.util.Arrays;
import us.koller.cameraroll.R;
import us.koller.cameraroll.util.SortUtil;
public class Settings {
public static final int DEFAULT_COLUMN_COUNT = 4;
private static final String PREF_KEY_HIDDEN_FOLDERS = "HIDDEN_FOLDERS";
private String theme;
private boolean storageRetriever;
private int style;
private int styleColumnCount;
private int columnCount;
private int sort_albums_by;
private int sort_album_by;
private boolean hiddenFolders;
private boolean use8BitColor;
private boolean cameraShortcut;
private static Settings instance;
public static Settings getInstance(Context context) {
if (instance == null) {
instance = new Settings(context);
}
return instance;
}
private Settings(Context context) {
SharedPreferences sharedPreferences
= PreferenceManager.getDefaultSharedPreferences(context);
theme = sharedPreferences.getString(
context.getString(R.string.pref_key_theme),
context.getString(R.string.DARK_THEME_VALUE));
storageRetriever = sharedPreferences.getBoolean(
context.getString(R.string.pref_key_media_retriever),
false);
style = sharedPreferences.getInt(
context.getString(R.string.pref_key_style),
context.getResources().getInteger(R.integer.STYLE_PARALLAX_VALUE));
styleColumnCount = getDefaultStyleColumnCount(context, style);
columnCount = sharedPreferences.getInt(
context.getString(R.string.pref_key_column_count),
DEFAULT_COLUMN_COUNT);
sort_albums_by = sharedPreferences.getInt(
context.getString(R.string.pref_key_sort_albums),
SortUtil.BY_NAME);
sort_album_by = sharedPreferences.getInt(
context.getString(R.string.pref_key_sort_album),
SortUtil.BY_DATE);
hiddenFolders = sharedPreferences.getBoolean
(PREF_KEY_HIDDEN_FOLDERS, false);
use8BitColor = sharedPreferences.getBoolean(
context.getString(R.string.pref_key_8_bit_color),
false);
cameraShortcut = sharedPreferences.getBoolean(
context.getString(R.string.pref_key_camera_shortcut),
false);
}
/*Getter & Setter*/
public String getThemeValue() {
return theme;
}
//storing the theme as a string: easier with switchPreference
//using theme as integer in code: easier comparision
public int getTheme(Context context) {
String[] themeValues = context.getResources().getStringArray(R.array.theme_values);
int[] themes = context.getResources().getIntArray(R.array.themes);
int index = Arrays.asList(themeValues).indexOf(theme);
return themes[index];
}
public void setTheme(String theme) {
this.theme = theme;
}
public boolean useStorageRetriever() {
return storageRetriever;
}
public void useStorageRetriever(boolean storageRetriever) {
this.storageRetriever = storageRetriever;
}
public int getStyle() {
return style;
}
public void setStyle(int style) {
this.style = style;
}
public int getStyleColumnCount(Context context, boolean pick_photos) {
Resources res = context.getResources();
boolean landscape = res.getBoolean(R.bool.landscape);
if (pick_photos) {
int styleColumnCount = getDefaultStyleColumnCount(context,
res.getInteger(R.integer.STYLE_CARDS_VALUE));
return landscape ? styleColumnCount + 1 : styleColumnCount;
}
if (landscape &&
(getStyle() == res.getInteger(R.integer.STYLE_CARDS_VALUE) ||
getStyle() == res.getInteger(R.integer.STYLE_CARDS_2_VALUE))) {
return styleColumnCount + 1;
}
return styleColumnCount;
}
public int getStyleGridSpacing(Context context, boolean pick_photos) {
Resources res = context.getResources();
if (getStyle() == res.getInteger(R.integer.STYLE_CARDS_VALUE) || pick_photos) {
return (int) res.getDimension(R.dimen.cards_style_grid_spacing);
} else if (getStyle() == res.getInteger(R.integer.STYLE_CARDS_2_VALUE)) {
return (int) res.getDimension(R.dimen.album_grid_spacing);
}
return 0;
}
public void setStyleColumnCount(int styleColumnCount) {
this.styleColumnCount = styleColumnCount;
}
public int getColumnCount(Context context) {
if (columnCount == 0) {
columnCount = DEFAULT_COLUMN_COUNT;
}
boolean landscape = context.getResources().getBoolean(R.bool.landscape);
if (landscape) {
return columnCount + 1;
}
return columnCount;
}
public void setColumnCount(int columnCount) {
this.columnCount = columnCount;
}
public static int getDefaultStyleColumnCount(Context context, int style) {
Resources res = context.getResources();
if (style == res.getInteger(R.integer.STYLE_PARALLAX_VALUE)) {
return res.getInteger(R.integer.STYLE_PARALLAX_COLUMN_COUNT);
} else if (style == res.getInteger(R.integer.STYLE_CARDS_VALUE)) {
return res.getInteger(R.integer.STYLE_CARDS_COLUMN_COUNT);
} else if (style == res.getInteger(R.integer.STYLE_CARDS_2_VALUE)) {
return res.getInteger(R.integer.STYLE_CARDS_2_COLUMN_COUNT);
} else if (style == res.getInteger(R.integer.STYLE_NESTED_RECYCLER_VIEW_VALUE)) {
return res.getInteger(R.integer.STYLE_NESTED_RECYCLER_VIEW_COLUMN_COUNT);
}
return 1;
}
public int sortAlbumsBy() {
return sort_albums_by;
}
public void sortAlbumsBy(Context context, int sort_albums_by) {
this.sort_albums_by = sort_albums_by;
String key = context.getString(R.string.pref_key_sort_albums);
saveInt(context, key, sort_albums_by);
}
public int sortAlbumBy() {
return sort_album_by;
}
public void sortAlbumBy(Context context, int sort_album_by) {
this.sort_album_by = sort_album_by;
String key = context.getString(R.string.pref_key_sort_album);
saveInt(context, key, sort_album_by);
}
public boolean getHiddenFolders() {
return hiddenFolders;
}
public boolean setHiddenFolders(Context context, boolean hiddenFolders) {
this.hiddenFolders = hiddenFolders;
saveBoolean(context, PREF_KEY_HIDDEN_FOLDERS, hiddenFolders);
return hiddenFolders;
}
public boolean use8BitColor() {
return use8BitColor;
}
public void use8BitColor(boolean use8BitColor) {
this.use8BitColor = use8BitColor;
}
public boolean getCameraShortcut() {
return cameraShortcut;
}
public void setCameraShortcut(boolean cameraShortcut) {
this.cameraShortcut = cameraShortcut;
}
private static void saveInt(Context context, String key, int value) {
SharedPreferences sharedPreferences
= PreferenceManager.getDefaultSharedPreferences(context);
sharedPreferences
.edit()
.putInt(key, value)
.apply();
}
private static void saveBoolean(Context context, String key, boolean value) {
SharedPreferences sharedPreferences
= PreferenceManager.getDefaultSharedPreferences(context);
sharedPreferences
.edit()
.putBoolean(key, value)
.apply();
}
public static class Utils {
public static String getThemeName(Context context, String themeValue) {
int valuesRes = R.array.theme_values;
int namesRes = R.array.theme_names;
return getValueName(context, themeValue, valuesRes, namesRes);
}
public static String getStyleName(Context context, int styleValue) {
int valuesRes = R.array.style_values;
int namesRes = R.array.style_names;
return getValueName(context, styleValue, valuesRes, namesRes);
}
private static String getValueName(Context context, String value,
int valuesRes, int namesRes) {
String[] values = context.getResources().getStringArray(valuesRes);
String[] names = context.getResources().getStringArray(namesRes);
int index = -1;
for (int i = 0; i < values.length; i++) {
if (values[i].equals(value)) {
index = i;
break;
}
}
if (index >= 0) {
return names[index];
}
return "Error";
}
private static String getValueName(Context context, int value,
int valuesRes, int namesRes) {
int[] values = context.getResources().getIntArray(valuesRes);
String[] names = context.getResources().getStringArray(namesRes);
int index = -1;
for (int i = 0; i < values.length; i++) {
if (values[i] == value) {
index = i;
break;
}
}
if (index >= 0) {
return names[index];
}
return "Error";
}
}
}
| 33.20339
| 91
| 0.625625
|
33a5ed6be87b623a015c22d23966e24bb4573270
| 755
|
package com.example.zhengbotao.classassistant1.data.bean;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
/**
* Created by zhengbotao on 18-4-11.
*
* 用户父类,包括姓名,学号/工号,头像,密码 字段
*
* BmobUser 本身除BmobObject外,还包含
* username
* password 等属性,故这里不用重复声明
*/
public class Author extends BmobUser{
// 用户学号/工号
private String authorId;
// 用户头像
private BmobFile authorAvatar;
public String getAuthorId() {
return authorId;
}
public void setAuthorId(String authorId) {
this.authorId = authorId;
}
public BmobFile getAuthorAvatar() {
return authorAvatar;
}
public void setAuthorAvatar(BmobFile authorAvatar) {
this.authorAvatar = authorAvatar;
}
}
| 18.875
| 57
| 0.663576
|
ea6440c4d94ee599b661ddb8e42207eedbf556d0
| 635
|
package com.xnx3.template.bean;
import org.jsoup.nodes.Element;
/**
* 模板变量的筛选,将每个模板页面中都有的模板变量筛选出来
*/
public class TemplateVarFilter {
private String key; //查找的元素,即对element进行精简,去除空格等
private Element element; //元素本身
private double simSum; //相似度的和
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public double getSimSum() {
return simSum;
}
public void setSimSum(double simSum) {
this.simSum = simSum;
}
public Element getElement() {
return element;
}
public void setElement(Element element) {
this.element = element;
}
}
| 18.142857
| 50
| 0.667717
|
4f0c55bc582d8c5ecd1374c5caf6548951b1a609
| 3,163
|
/*
* 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
*
* https://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.ivyde.internal.eclipse.ui.console;
import java.util.Collections;
import java.util.List;
import org.apache.ivy.util.Message;
import org.apache.ivy.util.MessageLogger;
import org.apache.ivyde.internal.eclipse.IvyPlugin;
public class IvyDEMessageLogger implements MessageLogger {
private final IvyConsole console;
private int logLevel;
public IvyDEMessageLogger(IvyConsole console) {
this.console = console;
logLevel = IvyPlugin.getPreferenceStoreHelper().getIvyConsoleIvyDELogLevel();
}
public void setLogLevel(int logLevel) {
this.logLevel = logLevel;
IvyPlugin.getPreferenceStoreHelper().setIvyConsoleIvyDELogLevel(logLevel);
}
public int getLogLevel() {
return logLevel;
}
public void log(String msg, int level) {
if (level <= logLevel) {
console.doAppendLine(level, "[IvyDE] " + msg);
}
}
public void rawlog(String msg, int level) {
log(msg, level);
}
public void debug(String msg) {
log(msg, Message.MSG_DEBUG);
}
public void verbose(String msg) {
log(msg, Message.MSG_VERBOSE);
}
public void deprecated(String msg) {
log("DEPRECATED: " + msg, Message.MSG_WARN);
}
public void info(String msg) {
log(msg, Message.MSG_INFO);
}
public void rawinfo(String msg) {
rawlog(msg, Message.MSG_INFO);
}
public void warn(String msg) {
log(msg, Message.MSG_WARN);
}
public void error(String msg) {
log(msg, Message.MSG_ERR);
}
public void sumupProblems() {
// we don't buffer anything, nothing to sumup
}
public void clearProblems() {
// do nothing
}
public List<String> getProblems() {
return Collections.emptyList();
}
public List<String> getErrors() {
return Collections.emptyList();
}
public List<String> getWarns() {
return Collections.emptyList();
}
public void progress() {
// do nothing
}
public void endProgress() {
// do nothing
}
public void endProgress(String msg) {
// do nothing
}
public boolean isShowProgress() {
return false;
}
public void setShowProgress(boolean progress) {
// do nothing
}
}
| 25.103175
| 85
| 0.653494
|
1150efd7a093a966de40a459cdece70df7b9e734
| 7,345
|
/*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2017 The ZAP Development Team
*
* 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.zaproxy.zap.extension.selenium;
import java.util.List;
import javax.swing.AbstractListModel;
import javax.swing.ComboBoxModel;
import org.apache.commons.lang.Validate;
/**
* A {@code ComboBoxModel} of {@link ProvidedBrowserUI}s.
*
* @since 1.1.0
*/
public class ProvidedBrowsersComboBoxModel extends AbstractListModel<ProvidedBrowserUI>
implements ComboBoxModel<ProvidedBrowserUI> {
private static final long serialVersionUID = -2353742370704132293L;
/**
* The {@code ProvidedBrowserUI}s contained in this model.
*/
private final List<ProvidedBrowserUI> browsers;
/**
* The currently selected browser, {@code null} if no browser is selected.
*/
private ProvidedBrowserUI selectedBrowser;
private boolean includeHeadless = true;
private boolean includeUnconfigured = true;
/**
* Constructs a {@code BrowsersComboBoxModel} with the given {@code browsers}.
* <p>
* The selected item will be set to the first browser of the given list of {@code browsers}.
*
* @param browsers the browsers that will have this combo box model
* @throws IllegalArgumentException if the given {@code List} of {@code browsers} is {@code null} or empty.
*/
public ProvidedBrowsersComboBoxModel(List<ProvidedBrowserUI> browsers) {
Validate.notEmpty(browsers);
this.browsers = browsers;
this.selectedBrowser = this.browsers.get(0);
}
/**
* Returns whether headless browsers should be included in the model
* @return true if headless browsers should be included in the model
*/
public boolean isIncludeHeadless() {
return includeHeadless;
}
/**
* Sets whether headless browsers should be included in the model
* @param includeHeadless true if headless browsers should be included in the model
*/
public void setIncludeHeadless(boolean includeHeadless) {
this.includeHeadless = includeHeadless;
configsChanged();
}
/**
* Returns whether unconfigured browsers should be included in the model
* @return true if unconfigured browsers should be included in the model
*/
public boolean isIncludeUnconfigured() {
return includeUnconfigured;
}
/**
* Sets whether unconfigured browsers should be included in the model
* @param includeHeadless true if unconfigured browsers should be included in the model
*/
public void setIncludeUnconfigured(boolean includeUnconfigured) {
this.includeUnconfigured = includeUnconfigured;
configsChanged();
}
private void configsChanged() {
fireContentsChanged(this, -1, -1);
if (! this.incBrowser(this.getSelectedItem())) {
// The selected item is no longer valid
this.setSelectedItem(this.getElementAt(0));
}
}
@Override
public ProvidedBrowserUI getSelectedItem() {
return selectedBrowser;
}
/**
* Convenience method that sets the selected browser using the browser ID.
* <p>
* No changes are done to the selected item if the browser with the given ID is not contained in this model.
*
* @param providerBrowserId the id of the browser, {@code null} to clear the selection
* @see #setSelectedBrowser(ProvidedBrowser)
*/
public void setSelectedBrowser(String providerBrowserId) {
if (providerBrowserId == null) {
setSelectedBrowserImpl(null);
return;
}
for (ProvidedBrowserUI browserUI : browsers) {
if (providerBrowserId.equals(browserUI.getBrowser().getId())) {
setSelectedBrowserImpl(browserUI);
break;
}
}
}
/**
* Convenience method that sets the selected item using the given {@code browser}.
* <p>
* No changes are done to the selected item if the given browser is not contained in this model.
*
* @param browser the browser, {@code null} to clear the selection
* @see #setSelectedItem(Object)
*/
public void setSelectedBrowser(ProvidedBrowser browser) {
if (browser == null) {
setSelectedBrowserImpl(null);
return;
}
for (ProvidedBrowserUI browserUI : browsers) {
if (browser.equals(browserUI.getBrowser())) {
setSelectedBrowserImpl(browserUI);
break;
}
}
}
/**
* Sets the given {@code item} as the selected item. Might be {@code null} to clear the selection.
* <p>
* No changes are done to the selected item if the given {@code item} is not contained in this model.
*
* @throws IllegalArgumentException if {@code item} is not a {@code ProvidedBrowserUI} when non-{@code null}.
*/
@Override
public void setSelectedItem(Object item) {
if (item != null && !(item instanceof ProvidedBrowserUI)) {
throw new IllegalArgumentException("Parameter item must be of type ProvidedBrowserUI.");
}
ProvidedBrowserUI browser = (ProvidedBrowserUI) item;
if (browser != null && !browsers.contains(browser)) {
return;
}
setSelectedBrowserImpl(browser);
}
private void setSelectedBrowserImpl(ProvidedBrowserUI browser) {
if ((selectedBrowser != null && !selectedBrowser.equals(browser)) || selectedBrowser == null && browser != null) {
if (this.incBrowser(browser)) {
selectedBrowser = browser;
fireContentsChanged(this, -1, -1);
}
}
}
private boolean incBrowser(ProvidedBrowserUI browser) {
if (browser == null) {
// Special case - null is used to indicate no selected item
return true;
}
return (this.includeUnconfigured || browser.getBrowser().isConfigured()) &&
(this.isIncludeHeadless() || ! browser.getBrowser().isHeadless());
}
@Override
public int getSize() {
int size = 0;
for (ProvidedBrowserUI browser : browsers) {
if (incBrowser(browser)) {
size ++;
}
}
return size;
}
@Override
public ProvidedBrowserUI getElementAt(int index) {
int idx = -1;
for (ProvidedBrowserUI browser : browsers) {
if (incBrowser(browser)) {
idx ++;
if (idx == index) {
return browser;
}
}
}
return null;
}
}
| 32.93722
| 122
| 0.635671
|
c7568aeadad5d05701b2cae59669918a5707b265
| 2,538
|
package frc.robot.commands.wrist;
import java.util.ArrayList;
import com.ctre.phoenix.motorcontrol.ControlMode;
import edu.wpi.first.wpilibj2.command.CommandBase;
import frc.robot.Robot;
import frc.robot.subsystems.Arm;
import frc.robot.subsystems.Arm.ArmDirection;
import frc.robot.subsystems.Wrist;
import frc.robot.subsystems.Wrist.WristDirection;
/**
* Sets the wrist along the path that allows it to hit the limit switch at the
* front.
*
* @author Angela Jia
* @since 2/8/19
*/
public class ZeroWrist extends CommandBase {
private static final double ZERO_SPEED = 0.21;
private static final int CURRENT_SPIKE = 7;
private static final double TIMEOUT = 5000;
private ArrayList<Double> currentVals;
private int VALUES_TO_SAMPLE = 10;
private int startTime = 0;
public ZeroWrist() {
addRequirements(Wrist.getInstance());
currentVals = new ArrayList<Double>();
}
public void initialize() {
startTime = Robot.getTime();
Wrist.getInstance().getMasterTalon().configReverseSoftLimitEnable(false);
Arm.getInstance().setState(ArmDirection.DOWN.getState());
// Wrist.getInstance().getMasterTalon().configSelectedFeedbackSensor(FeedbackDevice.CTRE_MagEncoder_Absolute);
Robot.log("ZeroWrist initialized.");
}
@Override
public void execute() {
Wrist.getInstance().setWristPercentOutput(ZERO_SPEED, WristDirection.TO_FRONT);
}
/**
* @return true if wrist has hit hard limit on front side
*/
@Override
public boolean isFinished() {
if (Robot.getTime() - startTime > TIMEOUT) {
return true;
}
if ((Robot.getTime() - startTime) > Wrist.PEAK_TIME) {
currentVals.add(Wrist.getInstance().getMasterTalon().getOutputCurrent());
if (currentVals.size() >= VALUES_TO_SAMPLE) {
currentVals.remove(0);
boolean isAllValid = true;
for (double currentVal : currentVals) {
isAllValid = isAllValid && currentVal > CURRENT_SPIKE;
}
return isAllValid;
}
}
return false;
}
public void end(boolean interrupted) {
Wrist.getInstance().setWrist(ControlMode.Disabled, 0);
Wrist.getInstance().getMasterTalon().setSelectedSensorPosition(0);
Wrist.getInstance().getMasterTalon().configReverseSoftLimitEnable(true);
((MoveWristManual) Wrist.getInstance().getDefaultCommand()).disableClosedLoop();
Robot.log("ZeroWrist ended.");
System.out.println("command over");
}
}
| 31.725
| 116
| 0.686367
|
6cff118e94be6d9630591f056df635f53b645490
| 1,014
|
package com.shareworx.ezfm.baseinfo.userstation.vo;
/**
* 人员与岗位的查询条件VO
*
* @author jin.li
*
*/
public class UserStationQueryVo {
private String pk_station;
private String flag;
private int start;
private int limit;
private String user_name;
private String stan_code;
public String getPk_station() {
return pk_station;
}
public void setPk_station(String pk_station) {
this.pk_station = pk_station;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getStan_code() {
return stan_code;
}
public void setStan_code(String stan_code) {
this.stan_code = stan_code;
}
}
| 15.6
| 51
| 0.704142
|
b79a3c5af75d795b6ac7bccccbea0fb09597855d
| 1,266
|
package frc.robot.commands.MultiSubsystemCommands;
import edu.wpi.first.wpilibj2.command.InstantCommand;
import edu.wpi.first.wpilibj2.command.ParallelCommandGroup;
import edu.wpi.first.wpilibj2.command.SequentialCommandGroup;
import frc.robot.Constants;
import frc.robot.commands.ConveyerCommands.MoveConveyor;
import frc.robot.commands.ShooterCommands.ResetShooter;
import frc.robot.subsystems.Conveyor;
import frc.robot.subsystems.Shooter;
public class EjectTopCargo extends SequentialCommandGroup {
private final Conveyor conveyor;
private final Shooter shooter;
public EjectTopCargo(Shooter shooter, Conveyor conveyor) {
this.conveyor = conveyor;
this.shooter = shooter;
addRequirements(conveyor, shooter);
addCommands(
new ParallelCommandGroup(
new InstantCommand(() -> shooter.setVelocity(.3)),
new InstantCommand(() -> shooter.hoodToDegree(70))),
new MoveConveyor(conveyor, Constants.ConveyorConstants.SHOOT_CONVEYOR_STEP),
new ResetShooter(shooter));
}
@Override
public void end(boolean interrupted) {
shooter.setVelocity(0);
shooter.hoodToPos(0);
super.end(false);
}
}
| 33.315789
| 92
| 0.704581
|
71962950601c0e062b901891511bb5ad9f965420
| 1,776
|
package com.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.adapter.MyListAdapter;
import com.example.zh_demo.R;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by mycomputer on 2017/6/30.
* 热门推荐
*/
public class recommend_fragment extends Fragment {
private static final String TAG = "TAG";
@BindView(R.id.recyclerView)
RecyclerView rc;
private View view;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
if (view == null) {
Log.i(TAG, "onCreateView:热门推荐 ");
view = inflater.inflate(R.layout.recommend_fragment, null);
ButterKnife.bind(this, view);
ArrayList<String> list = new ArrayList<>();
for (int i = 'A'; i <= 'Z'; i++) {
list.add("" + (char) i);
}
MyListAdapter adapter = new MyListAdapter(list);
rc.setAdapter(adapter);
StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
// LinearLayoutManager manager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
rc.setLayoutManager(manager);
}
return view;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy: 热门推荐");
}
}
| 31.157895
| 123
| 0.68018
|
95d515d9c10a0c87fe6d87641163cc5902760218
| 2,076
|
package pwr.newEducation.domain.learningEffect;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.stream.Collectors;
@ApplicationScoped
public class SubjectLearningEffectDTOMapper {
@Inject
LearningEffectDTOMapper learningEffectDTOMapper;
@Inject
KnowledgeVerificationFormDTOMapper knowledgeVerificationFormDTOMapper;
@Inject
LearningEffectRangeDTOMapper learningEffectRangeDTOMapper;
public SubjectLearningEffectEntity toEntity(SubjectLearningEffectDTO subjectLearningEffectDTO) {
return SubjectLearningEffectEntity.builder(subjectLearningEffectDTO.getIdentifier(),
subjectLearningEffectDTO.getContent(),
subjectLearningEffectDTO.getLearningEffects().stream()
.map(learningEffectDTOMapper::toEntity).collect(Collectors.toSet()),
subjectLearningEffectDTO.getKnowledgeVerificationForms().stream()
.map(knowledgeVerificationFormDTOMapper::toEntity).collect(Collectors.toSet()),
subjectLearningEffectDTO.getLearningEffectRanges().stream()
.map(learningEffectRangeDTOMapper::toEntity).collect(Collectors.toSet()))
.build();
}
public SubjectLearningEffectDTO toDTO(SubjectLearningEffectEntity subjectLearningEffectEntity) {
return SubjectLearningEffectDTO.builder(subjectLearningEffectEntity.getIdentifier(),
subjectLearningEffectEntity.getContent(),
subjectLearningEffectEntity.getLearningEffects().stream()
.map(learningEffectDTOMapper::toDTO).collect(Collectors.toSet()),
subjectLearningEffectEntity.getKnowledgeVerificationForms().stream()
.map(knowledgeVerificationFormDTOMapper::toDTO).collect(Collectors.toSet()),
subjectLearningEffectEntity.getLearningEffectRanges().stream()
.map(learningEffectRangeDTOMapper::toDTO).collect(Collectors.toSet()))
.build();
}
}
| 49.428571
| 103
| 0.716281
|
6f6e36c5ff9122e599eab1f4d9724df5eaf5f28c
| 1,018
|
package com.feilong.gateway.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
/**
* @author FeiLong
* @version 1.8
* @date 2020/11/17 17:17
* 統一网关的跨域配置类
*/
@Configuration
@SuppressWarnings("ALL")
public class GateWayCorsConfiguration {
@Bean
public CorsWebFilter getCorsWebFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration configuration = new CorsConfiguration();
configuration.addAllowedHeader("*");
configuration.addAllowedMethod("*");
configuration.addAllowedOrigin("*");
configuration.setAllowCredentials(true);
source.registerCorsConfiguration("/**", configuration);
return new CorsWebFilter(source);
}
}
| 31.8125
| 87
| 0.755403
|
25391d53c8e96078375ed746ea6a71d74e22fba5
| 1,142
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package talitakumi.servicios;
import talitakumi.framework.*;
import talitakumi.model.core.Personas;
/**
*
* @author rupertus
*/
public class ConvertPersona implements Converter {
@Override
public DataParameter fromObject(Object p) {
DataParameter dp = new DataParameter();
Personas o = (Personas) p;
dp.set("id", o.getId());
dp.set("apellidos", o.getApellidos());
dp.set("ciudad", o.getCiudad());
dp.set("nombres", o.getNombres());
dp.set("fechanacimiento", o.getFechanacimiento());
dp.set("documento", o.getDocumento());
dp.set("telefono", o.getTelefono());
dp.set("sexo", o.getSexo());
dp.set("email", o.getEmail());
dp.set("domicilio", o.getDomicilio());
dp.set("movil", o.getMovil());
dp.set("foto", o.getFoto());
dp.set("telefono", o.getTelefono());
return(dp);
}
@Override
public Personas fromDP(DataParameter dp) {
Personas p = null;
return(p);
}
}
| 21.54717
| 58
| 0.590193
|
9fb25c20a8228c330053ef84262f154707be3f84
| 476
|
package com.hzfc.management.jsbsb.modules.testOnlineTaxiJiJia.constatnt;
import lombok.Getter;
/**
* @author yueyi2019
*/
@Getter
public enum BusinessInterfaceStatus implements CodeEnum {
/**
* 操作成功
*/
SUCCESS(0, "success"),
/**
* 操作失败
*/
FAIL(1, "fail");
private final int code;
private final String value;
BusinessInterfaceStatus(int code, String value) {
this.code = code;
this.value = value;
}
}
| 16.413793
| 72
| 0.619748
|
40dec98a3ffe5208d632c4cef7c6c1bc45b38155
| 8,409
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* 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.redhat.acceptance.steps;
import com.google.common.collect.Lists;
import com.redhat.acceptance.steps.Helper.Pages;
import com.redhat.acceptance.utils.MapBuilder;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import cucumber.api.java.en_tx.Givenyall;
import cucumber.api.java.en_tx.Whenyall;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import static com.redhat.acceptance.steps.Helper.Pages.CUSTOMERS;
public class CustomerSteps {
private static ResourceBundle rb = ResourceBundle.getBundle("acceptance");
private static final Logger log = LoggerFactory.getLogger(CustomerSteps.class);
protected static Helper helper;
private static WebDriver browser = null;
private WebDriver getBrowser() {
return browser;
}
private static boolean initialised = false;
@Before
public void beforeAll() {
helper = Helper.get();
browser = helper.getBrowser();
}
@Given("^we login:$")
public void login(List<Map<String, String>> table) throws Throwable {
helper.cleanup();
if (!helper.isLoggedIn()) {
helper.login(table.get(0).get("Username"), table.get(0).get("Password"));
helper.navigateTo(Pages.CUSTOMERS);
}
}
@Givenyall("^navigate to the \"(.*?)\" page$")
public void navigate_to_the_page(String pageName) throws Throwable {
helper.navigateTo(Pages.valueOf(pageName.toUpperCase()));
}
@When("^click the \"(.*?)\" button$")
public void click_the_button(String buttonText) throws Throwable {
helper.clickButton(buttonText);
}
@Whenyall("^enter the following into the \"(.*?)\" dialog:$")
public void we_enter_the_following_into_the_dialog(String dialogTitle, List<Map<String, String>> table) throws Throwable {
helper.enterDetailsIntoTheDialog(dialogTitle, table);
// Wait.For("dialog is not visible: "+dialogTitle, 5, new ToHappen(){@Override public boolean hasHappened(){
// return getBrowser().findElement(By.className("modal-title")).isDisplayed();
// }});
//
// if (!dialogTitle.equals(getBrowser().findElement(By.className("modal-title")).getText())){
// throw new RuntimeException("unable to find dialog with name: "+dialogTitle);
// }
//
// final String prefix;
// if (dialogTitle.toLowerCase().contains("customer")){
// prefix="Customer";
// }else
// prefix="";
//
// for(Map<String,String> row:table){
// for(Entry<String, String> e:row.entrySet()){
// Wait.For(5, new ToHappen(){@Override public boolean hasHappened(){
// WebElement element=getBrowser().findElement(By.id(prefix+e.getKey()));
// return element.isDisplayed() && element.isEnabled();
// }});
//
// WebElement element=getBrowser().findElement(By.id(prefix+e.getKey()));
// if (element.getTagName().toLowerCase().equals("select")){
// new Select(element).selectByValue(e.getValue());
// }else{
// element.sendKeys(e.getValue());
// }
//
// }
// }
}
@Then("^customers exist with the following details:$")
public void customers_exist_with_the_following_details(List<Map<String, String>> table) throws Throwable {
// check that the list is exactly what it listed, not too many, not too few
// this rows logic doesnt seem to always return the correct number of rows in the table
List<WebElement> rows = getBrowser().findElements(By.xpath("//*[@id=\"example\"]/tbody/tr"));
int rowSize = table.size(); //resorting to using the expected size since xpath of the table/tr with the selenium driver appears to be inaccurate
try {
Thread.sleep(1000);
} catch (Exception ignore) {
}
List<Map<String, String>> expectedTable = Lists.newArrayList(table.toArray(new Map[table.size()]));
List<Map<String, String>> foundTable = new ArrayList<>();
// System.out.println("Datatable.size() = "+rows.size());
for (int i = 0; i <= rowSize; i++) {
try {
// System.out.println("Datatable("+(i+1)+") ... about to check");
String name = getBrowser().findElement(By.xpath("//*[@id=\"example\"]/tbody/tr[" + (i + 1) + "]/td[2]/a")).getText();
// System.out.println("Datatable("+(i+1)+") = "+name);
String description = getBrowser().findElement(By.xpath("//*[@id=\"example\"]/tbody/tr[" + (i + 1) + "]/td[3]")).getText();
String vertical = getBrowser().findElement(By.xpath("//*[@id=\"example\"]/tbody/tr[" + (i + 1) + "]/td[4]")).getText();
String assessor = getBrowser().findElement(By.xpath("//*[@id=\"example\"]/tbody/tr[" + (i + 1) + "]/td[5]")).getText();
foundTable.add(new MapBuilder<String, String>()
.put("Name", name)
.put("Description", description)
.put("Vertical", vertical)
.put("Assessor", assessor)
.build());
} catch (WebDriverException ignore) {
break; // assume it's read too many rows
}
}
if (expectedTable.size() != foundTable.size()) {
System.out.println("gonna fail!");
}
Assert.assertEquals("Expected and actual data size is wrong", expectedTable.size(), foundTable.size());
int protectionMax = expectedTable.size() + 1;
int i = 0;
while (expectedTable.size() > 0) {
i += 1;
if (i >= protectionMax) break;
String expectedName = expectedTable.get(0).get("Name");
String expectedDescription = expectedTable.get(0).get("Description");
String expectedVertical = expectedTable.get(0).get("Vertical");
String expectedAssessor = expectedTable.get(0).get("Assessor");
String expected = expectedName + expectedDescription + expectedVertical + expectedAssessor;
for (Map<String, String> e : foundTable) {
String actual = e.get("Name") + e.get("Description") + e.get("Vertical") + e.get("Assessor");
if (expected.equals(actual)) {
expectedTable.remove(0);
break;
}
}
}
Assert.assertEquals("There are still customers in the expected list that weren't found", 0, expectedTable.size());
}
@Given("^we delete all customers$")
public void cleanup() throws Throwable {
helper.cleanup();
}
@Then("^delete the customer:$")
public void delete_the_customer(List<Map<String, String>> table) throws Throwable {
for (Map<String, String> row : table) {
throw new RuntimeException("NOT IMPLEMENTED YET");
}
}
@Givenyall("^create the following customers:$")
public void createCustomers(List<Map<String, String>> table) throws Throwable {
helper.navigateTo(CUSTOMERS);
for (Map<String, String> row : table) {
helper.clickButton("Add Customer");
we_enter_the_following_into_the_dialog("New Customer", Lists.newArrayList(row));
helper.clickButton("Create");
// helper.waitForPage(CUSTOMERS, 5);
}
}
}
| 40.820388
| 152
| 0.63658
|
6b6a6c2a72129b50f3e37221c7b96a554fba93c5
| 52,422
|
/*
* 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.accumulo.core.clientImpl;
import static org.easymock.EasyMock.replay;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.accumulo.core.clientImpl.TabletLocator.TabletLocation;
import org.apache.accumulo.core.clientImpl.TabletLocator.TabletLocations;
import org.apache.accumulo.core.clientImpl.TabletLocator.TabletServerMutations;
import org.apache.accumulo.core.clientImpl.TabletLocatorImpl.TabletLocationObtainer;
import org.apache.accumulo.core.clientImpl.TabletLocatorImpl.TabletServerLockChecker;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.PartialKey;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.TableId;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.dataImpl.KeyExtent;
import org.apache.accumulo.core.metadata.MetadataLocationObtainer;
import org.apache.accumulo.core.metadata.MetadataTable;
import org.apache.accumulo.core.metadata.RootTable;
import org.apache.accumulo.core.metadata.schema.MetadataSchema.TabletsSection;
import org.apache.hadoop.io.Text;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
public class TabletLocatorImplTest {
private static final KeyExtent RTE = RootTable.EXTENT;
private static final KeyExtent MTE = new KeyExtent(MetadataTable.ID, null, RTE.getEndRow());
static KeyExtent nke(String t, String er, String per) {
return new KeyExtent(TableId.of(t), er == null ? null : new Text(er),
per == null ? null : new Text(per));
}
static Range nr(String k1, boolean si, String k2, boolean ei) {
return new Range(k1 == null ? null : new Text(k1), si, k2 == null ? null : new Text(k2), ei);
}
static Range nr(String k1, String k2) {
return new Range(k1 == null ? null : new Text(k1), k2 == null ? null : new Text(k2));
}
static List<Range> nrl(Range... ranges) {
return Arrays.asList(ranges);
}
static Object[] nol(Object... objs) {
return objs;
}
@SuppressWarnings("unchecked")
static Map<String,Map<KeyExtent,List<Range>>> createExpectedBinnings(Object... data) {
Map<String,Map<KeyExtent,List<Range>>> expBinnedRanges = new HashMap<>();
for (int i = 0; i < data.length; i += 2) {
String loc = (String) data[i];
Object[] binData = (Object[]) data[i + 1];
HashMap<KeyExtent,List<Range>> binnedKE = new HashMap<>();
expBinnedRanges.put(loc, binnedKE);
for (int j = 0; j < binData.length; j += 2) {
KeyExtent ke = (KeyExtent) binData[j];
List<Range> ranges = (List<Range>) binData[j + 1];
binnedKE.put(ke, ranges);
}
}
return expBinnedRanges;
}
static TreeMap<KeyExtent,TabletLocation> createMetaCacheKE(Object... data) {
TreeMap<KeyExtent,TabletLocation> mcke = new TreeMap<>();
for (int i = 0; i < data.length; i += 2) {
KeyExtent ke = (KeyExtent) data[i];
String loc = (String) data[i + 1];
mcke.put(ke, new TabletLocation(ke, loc, "1"));
}
return mcke;
}
static TreeMap<Text,TabletLocation> createMetaCache(Object... data) {
TreeMap<KeyExtent,TabletLocation> mcke = createMetaCacheKE(data);
TreeMap<Text,TabletLocation> mc = new TreeMap<>(TabletLocatorImpl.END_ROW_COMPARATOR);
for (Entry<KeyExtent,TabletLocation> entry : mcke.entrySet()) {
if (entry.getKey().getEndRow() == null)
mc.put(TabletLocatorImpl.MAX_TEXT, entry.getValue());
else
mc.put(entry.getKey().getEndRow(), entry.getValue());
}
return mc;
}
static TabletLocatorImpl createLocators(TServers tservers, String rootTabLoc, String metaTabLoc,
String table, TabletServerLockChecker tslc, Object... data) {
TreeMap<KeyExtent,TabletLocation> mcke = createMetaCacheKE(data);
TestTabletLocationObtainer ttlo = new TestTabletLocationObtainer(tservers);
RootTabletLocator rtl = new TestRootTabletLocator();
TabletLocatorImpl rootTabletCache =
new TabletLocatorImpl(MetadataTable.ID, rtl, ttlo, new YesLockChecker());
TabletLocatorImpl tab1TabletCache =
new TabletLocatorImpl(TableId.of(table), rootTabletCache, ttlo, tslc);
setLocation(tservers, rootTabLoc, RTE, MTE, metaTabLoc);
for (Entry<KeyExtent,TabletLocation> entry : mcke.entrySet()) {
setLocation(tservers, metaTabLoc, MTE, entry.getKey(), entry.getValue().tablet_location);
}
return tab1TabletCache;
}
static TabletLocatorImpl createLocators(TServers tservers, String rootTabLoc, String metaTabLoc,
String table, Object... data) {
return createLocators(tservers, rootTabLoc, metaTabLoc, table, new YesLockChecker(), data);
}
static TabletLocatorImpl createLocators(String table, Object... data) {
TServers tservers = new TServers();
return createLocators(tservers, "tserver1", "tserver2", table, data);
}
private ClientContext context;
@Before
public void setUp() {
context = EasyMock.createMock(ClientContext.class);
EasyMock.expect(context.getRootTabletLocation()).andReturn("tserver1").anyTimes();
EasyMock.expect(context.getInstanceID()).andReturn("instance1").anyTimes();
replay(context);
}
private void runTest(List<Range> ranges, TabletLocatorImpl tab1TabletCache,
Map<String,Map<KeyExtent,List<Range>>> expected) throws Exception {
List<Range> failures = Collections.emptyList();
runTest(ranges, tab1TabletCache, expected, failures);
}
private void runTest(List<Range> ranges, TabletLocatorImpl tab1TabletCache,
Map<String,Map<KeyExtent,List<Range>>> expected, List<Range> efailures) throws Exception {
Map<String,Map<KeyExtent,List<Range>>> binnedRanges = new HashMap<>();
List<Range> f = tab1TabletCache.binRanges(context, ranges, binnedRanges);
assertEquals(expected, binnedRanges);
HashSet<Range> f1 = new HashSet<>(f);
HashSet<Range> f2 = new HashSet<>(efailures);
assertEquals(f2, f1);
}
static Set<KeyExtent> nkes(KeyExtent... extents) {
HashSet<KeyExtent> kes = new HashSet<>();
Collections.addAll(kes, extents);
return kes;
}
static void runTest(TreeMap<Text,TabletLocation> mc, KeyExtent remove, Set<KeyExtent> expected) {
// copy so same metaCache can be used for multiple test
mc = new TreeMap<>(mc);
TabletLocatorImpl.removeOverlapping(mc, remove);
HashSet<KeyExtent> eic = new HashSet<>();
for (TabletLocation tl : mc.values()) {
eic.add(tl.tablet_extent);
}
assertEquals(expected, eic);
}
static Mutation nm(String row, String... data) {
Mutation mut = new Mutation(new Text(row));
for (String element : data) {
String[] cvp = element.split("=");
String[] cols = cvp[0].split(":");
mut.put(cols[0], cols[1], cvp[1]);
}
return mut;
}
static List<Mutation> nml(Mutation... ma) {
return Arrays.asList(ma);
}
private void runTest(TabletLocatorImpl metaCache, List<Mutation> ml,
Map<String,Map<KeyExtent,List<String>>> emb, String... efailures) throws Exception {
Map<String,TabletServerMutations<Mutation>> binnedMutations = new HashMap<>();
List<Mutation> afailures = new ArrayList<>();
metaCache.binMutations(context, ml, binnedMutations, afailures);
verify(emb, binnedMutations);
ArrayList<String> afs = new ArrayList<>();
ArrayList<String> efs = new ArrayList<>(Arrays.asList(efailures));
for (Mutation mutation : afailures) {
afs.add(new String(mutation.getRow()));
}
Collections.sort(afs);
Collections.sort(efs);
assertEquals(efs, afs);
}
private void verify(Map<String,Map<KeyExtent,List<String>>> expected,
Map<String,TabletServerMutations<Mutation>> actual) {
assertEquals(expected.keySet(), actual.keySet());
for (String server : actual.keySet()) {
TabletServerMutations<Mutation> atb = actual.get(server);
Map<KeyExtent,List<String>> etb = expected.get(server);
assertEquals(etb.keySet(), atb.getMutations().keySet());
for (KeyExtent ke : etb.keySet()) {
ArrayList<String> eRows = new ArrayList<>(etb.get(ke));
ArrayList<String> aRows = new ArrayList<>();
for (Mutation m : atb.getMutations().get(ke)) {
aRows.add(new String(m.getRow()));
}
Collections.sort(eRows);
Collections.sort(aRows);
assertEquals(eRows, aRows);
}
}
}
static Map<String,Map<KeyExtent,List<String>>> cemb(Object[]... ols) {
Map<String,Map<KeyExtent,List<String>>> emb = new HashMap<>();
for (Object[] ol : ols) {
String row = (String) ol[0];
String server = (String) ol[1];
KeyExtent ke = (KeyExtent) ol[2];
emb.computeIfAbsent(server, k -> new HashMap<>()).computeIfAbsent(ke, k -> new ArrayList<>())
.add(row);
}
return emb;
}
@Test
public void testRemoveOverlapping1() {
TreeMap<Text,TabletLocation> mc = createMetaCache(nke("0", null, null), "l1");
runTest(mc, nke("0", "a", null), nkes());
runTest(mc, nke("0", null, null), nkes());
runTest(mc, nke("0", null, "a"), nkes());
mc = createMetaCache(nke("0", "g", null), "l1", nke("0", "r", "g"), "l1", nke("0", null, "r"),
"l1");
runTest(mc, nke("0", null, null), nkes());
runTest(mc, nke("0", "a", null), nkes(nke("0", "r", "g"), nke("0", null, "r")));
runTest(mc, nke("0", "g", null), nkes(nke("0", "r", "g"), nke("0", null, "r")));
runTest(mc, nke("0", "h", null), nkes(nke("0", null, "r")));
runTest(mc, nke("0", "r", null), nkes(nke("0", null, "r")));
runTest(mc, nke("0", "s", null), nkes());
runTest(mc, nke("0", "b", "a"), nkes(nke("0", "r", "g"), nke("0", null, "r")));
runTest(mc, nke("0", "g", "a"), nkes(nke("0", "r", "g"), nke("0", null, "r")));
runTest(mc, nke("0", "h", "a"), nkes(nke("0", null, "r")));
runTest(mc, nke("0", "r", "a"), nkes(nke("0", null, "r")));
runTest(mc, nke("0", "s", "a"), nkes());
runTest(mc, nke("0", "h", "g"), nkes(nke("0", "g", null), nke("0", null, "r")));
runTest(mc, nke("0", "r", "g"), nkes(nke("0", "g", null), nke("0", null, "r")));
runTest(mc, nke("0", "s", "g"), nkes(nke("0", "g", null)));
runTest(mc, nke("0", "i", "h"), nkes(nke("0", "g", null), nke("0", null, "r")));
runTest(mc, nke("0", "r", "h"), nkes(nke("0", "g", null), nke("0", null, "r")));
runTest(mc, nke("0", "s", "h"), nkes(nke("0", "g", null)));
runTest(mc, nke("0", "z", "f"), nkes());
runTest(mc, nke("0", "z", "g"), nkes(nke("0", "g", null)));
runTest(mc, nke("0", "z", "q"), nkes(nke("0", "g", null)));
runTest(mc, nke("0", "z", "r"), nkes(nke("0", "g", null), nke("0", "r", "g")));
runTest(mc, nke("0", "z", "s"), nkes(nke("0", "g", null), nke("0", "r", "g")));
runTest(mc, nke("0", null, "f"), nkes());
runTest(mc, nke("0", null, "g"), nkes(nke("0", "g", null)));
runTest(mc, nke("0", null, "q"), nkes(nke("0", "g", null)));
runTest(mc, nke("0", null, "r"), nkes(nke("0", "g", null), nke("0", "r", "g")));
runTest(mc, nke("0", null, "s"), nkes(nke("0", "g", null), nke("0", "r", "g")));
}
@Test
public void testRemoveOverlapping2() {
// test removes when cache does not contain all tablets in a table
TreeMap<Text,TabletLocation> mc =
createMetaCache(nke("0", "r", "g"), "l1", nke("0", null, "r"), "l1");
runTest(mc, nke("0", "a", null), nkes(nke("0", "r", "g"), nke("0", null, "r")));
runTest(mc, nke("0", "g", null), nkes(nke("0", "r", "g"), nke("0", null, "r")));
runTest(mc, nke("0", "h", null), nkes(nke("0", null, "r")));
runTest(mc, nke("0", "r", null), nkes(nke("0", null, "r")));
runTest(mc, nke("0", "s", null), nkes());
runTest(mc, nke("0", "b", "a"), nkes(nke("0", "r", "g"), nke("0", null, "r")));
runTest(mc, nke("0", "g", "a"), nkes(nke("0", "r", "g"), nke("0", null, "r")));
runTest(mc, nke("0", "h", "a"), nkes(nke("0", null, "r")));
runTest(mc, nke("0", "r", "a"), nkes(nke("0", null, "r")));
runTest(mc, nke("0", "s", "a"), nkes());
runTest(mc, nke("0", "h", "g"), nkes(nke("0", null, "r")));
mc = createMetaCache(nke("0", "g", null), "l1", nke("0", null, "r"), "l1");
runTest(mc, nke("0", "h", "g"), nkes(nke("0", "g", null), nke("0", null, "r")));
runTest(mc, nke("0", "h", "a"), nkes(nke("0", null, "r")));
runTest(mc, nke("0", "s", "g"), nkes(nke("0", "g", null)));
runTest(mc, nke("0", "s", "a"), nkes());
mc = createMetaCache(nke("0", "g", null), "l1", nke("0", "r", "g"), "l1");
runTest(mc, nke("0", "z", "f"), nkes());
runTest(mc, nke("0", "z", "g"), nkes(nke("0", "g", null)));
runTest(mc, nke("0", "z", "q"), nkes(nke("0", "g", null)));
runTest(mc, nke("0", "z", "r"), nkes(nke("0", "g", null), nke("0", "r", "g")));
runTest(mc, nke("0", "z", "s"), nkes(nke("0", "g", null), nke("0", "r", "g")));
runTest(mc, nke("0", null, "f"), nkes());
runTest(mc, nke("0", null, "g"), nkes(nke("0", "g", null)));
runTest(mc, nke("0", null, "q"), nkes(nke("0", "g", null)));
runTest(mc, nke("0", null, "r"), nkes(nke("0", "g", null), nke("0", "r", "g")));
runTest(mc, nke("0", null, "s"), nkes(nke("0", "g", null), nke("0", "r", "g")));
}
static class TServers {
private final Map<String,Map<KeyExtent,SortedMap<Key,Value>>> tservers = new HashMap<>();
}
static class TestTabletLocationObtainer implements TabletLocationObtainer {
private final Map<String,Map<KeyExtent,SortedMap<Key,Value>>> tservers;
TestTabletLocationObtainer(TServers tservers) {
this.tservers = tservers.tservers;
}
@Override
public TabletLocations lookupTablet(ClientContext context, TabletLocation src, Text row,
Text stopRow, TabletLocator parent) {
// System.out.println("lookupTablet("+src+","+row+","+stopRow+","+ parent+")");
// System.out.println(tservers);
Map<KeyExtent,SortedMap<Key,Value>> tablets = tservers.get(src.tablet_location);
if (tablets == null) {
parent.invalidateCache(context, src.tablet_location);
return null;
}
SortedMap<Key,Value> tabletData = tablets.get(src.tablet_extent);
if (tabletData == null) {
parent.invalidateCache(src.tablet_extent);
return null;
}
// the following clip is done on a tablet, do it here to see if it throws exceptions
src.tablet_extent.toDataRange().clip(new Range(row, true, stopRow, true));
Key startKey = new Key(row);
Key stopKey = new Key(stopRow).followingKey(PartialKey.ROW);
SortedMap<Key,Value> results = tabletData.tailMap(startKey).headMap(stopKey);
return MetadataLocationObtainer.getMetadataLocationEntries(results);
}
@Override
public List<TabletLocation> lookupTablets(ClientContext context, String tserver,
Map<KeyExtent,List<Range>> map, TabletLocator parent) {
ArrayList<TabletLocation> list = new ArrayList<>();
Map<KeyExtent,SortedMap<Key,Value>> tablets = tservers.get(tserver);
if (tablets == null) {
parent.invalidateCache(context, tserver);
return list;
}
TreeMap<Key,Value> results = new TreeMap<>();
Set<Entry<KeyExtent,List<Range>>> es = map.entrySet();
List<KeyExtent> failures = new ArrayList<>();
for (Entry<KeyExtent,List<Range>> entry : es) {
SortedMap<Key,Value> tabletData = tablets.get(entry.getKey());
if (tabletData == null) {
failures.add(entry.getKey());
continue;
}
List<Range> ranges = entry.getValue();
for (Range range : ranges) {
SortedMap<Key,Value> tm;
if (range.getStartKey() == null)
tm = tabletData;
else
tm = tabletData.tailMap(range.getStartKey());
for (Entry<Key,Value> de : tm.entrySet()) {
if (range.afterEndKey(de.getKey())) {
break;
}
if (range.contains(de.getKey())) {
results.put(de.getKey(), de.getValue());
}
}
}
}
if (!failures.isEmpty())
parent.invalidateCache(failures);
return MetadataLocationObtainer.getMetadataLocationEntries(results).getLocations();
}
}
static class YesLockChecker implements TabletServerLockChecker {
@Override
public boolean isLockHeld(String tserver, String session) {
return true;
}
@Override
public void invalidateCache(String server) {}
}
static class TestRootTabletLocator extends RootTabletLocator {
TestRootTabletLocator() {
super(new YesLockChecker());
}
@Override
protected TabletLocation getRootTabletLocation(ClientContext context) {
return new TabletLocation(RootTable.EXTENT, context.getRootTabletLocation(), "1");
}
@Override
public void invalidateCache(ClientContext context, String server) {}
}
static void createEmptyTablet(TServers tservers, String server, KeyExtent tablet) {
Map<KeyExtent,SortedMap<Key,Value>> tablets =
tservers.tservers.computeIfAbsent(server, k -> new HashMap<>());
SortedMap<Key,Value> tabletData = tablets.get(tablet);
if (tabletData == null) {
tabletData = new TreeMap<>();
tablets.put(tablet, tabletData);
} else if (!tabletData.isEmpty()) {
throw new RuntimeException("Asked for empty tablet, but non empty tablet exists");
}
}
static void clearLocation(TServers tservers, String server, KeyExtent tablet, KeyExtent ke,
String instance) {
Map<KeyExtent,SortedMap<Key,Value>> tablets = tservers.tservers.get(server);
if (tablets == null) {
return;
}
SortedMap<Key,Value> tabletData = tablets.get(tablet);
if (tabletData == null) {
return;
}
Text mr = ke.getMetadataEntry();
Key lk = new Key(mr, TabletsSection.CurrentLocationColumnFamily.NAME, new Text(instance));
tabletData.remove(lk);
}
static void setLocation(TServers tservers, String server, KeyExtent tablet, KeyExtent ke,
String location, String instance) {
Map<KeyExtent,SortedMap<Key,Value>> tablets =
tservers.tservers.computeIfAbsent(server, k -> new HashMap<>());
SortedMap<Key,Value> tabletData = tablets.computeIfAbsent(tablet, k -> new TreeMap<>());
Text mr = ke.getMetadataEntry();
Value per = KeyExtent.encodePrevEndRow(ke.getPrevEndRow());
if (location != null) {
if (instance == null)
instance = "";
Key lk = new Key(mr, TabletsSection.CurrentLocationColumnFamily.NAME, new Text(instance));
tabletData.put(lk, new Value(location));
}
Key pk = new Key(mr, TabletsSection.TabletColumnFamily.PREV_ROW_COLUMN.getColumnFamily(),
TabletsSection.TabletColumnFamily.PREV_ROW_COLUMN.getColumnQualifier());
tabletData.put(pk, per);
}
static void setLocation(TServers tservers, String server, KeyExtent tablet, KeyExtent ke,
String location) {
setLocation(tservers, server, tablet, ke, location, "");
}
static void deleteServer(TServers tservers, String server) {
tservers.tservers.remove(server);
}
private void locateTabletTest(TabletLocatorImpl cache, String row, boolean skipRow,
KeyExtent expected, String server) throws Exception {
TabletLocation tl = cache.locateTablet(context, new Text(row), skipRow, false);
if (expected == null) {
if (tl != null)
System.out.println("tl = " + tl);
assertNull(tl);
} else {
assertNotNull(tl);
assertEquals(server, tl.tablet_location);
assertEquals(expected, tl.tablet_extent);
}
}
private void locateTabletTest(TabletLocatorImpl cache, String row, KeyExtent expected,
String server) throws Exception {
locateTabletTest(cache, row, false, expected, server);
}
@Test
public void test1() throws Exception {
TServers tservers = new TServers();
TestTabletLocationObtainer ttlo = new TestTabletLocationObtainer(tservers);
RootTabletLocator rtl = new TestRootTabletLocator();
TabletLocatorImpl rootTabletCache =
new TabletLocatorImpl(MetadataTable.ID, rtl, ttlo, new YesLockChecker());
TabletLocatorImpl tab1TabletCache =
new TabletLocatorImpl(TableId.of("tab1"), rootTabletCache, ttlo, new YesLockChecker());
locateTabletTest(tab1TabletCache, "r1", null, null);
KeyExtent tab1e = nke("tab1", null, null);
setLocation(tservers, "tserver1", RTE, MTE, "tserver2");
setLocation(tservers, "tserver2", MTE, tab1e, "tserver3");
locateTabletTest(tab1TabletCache, "r1", tab1e, "tserver3");
locateTabletTest(tab1TabletCache, "r2", tab1e, "tserver3");
// simulate a split
KeyExtent tab1e1 = nke("tab1", "g", null);
KeyExtent tab1e2 = nke("tab1", null, "g");
setLocation(tservers, "tserver2", MTE, tab1e1, "tserver4");
setLocation(tservers, "tserver2", MTE, tab1e2, "tserver5");
locateTabletTest(tab1TabletCache, "r1", tab1e, "tserver3");
tab1TabletCache.invalidateCache(tab1e);
locateTabletTest(tab1TabletCache, "r1", tab1e2, "tserver5");
locateTabletTest(tab1TabletCache, "a", tab1e1, "tserver4");
locateTabletTest(tab1TabletCache, "a", true, tab1e1, "tserver4");
locateTabletTest(tab1TabletCache, "g", tab1e1, "tserver4");
locateTabletTest(tab1TabletCache, "g", true, tab1e2, "tserver5");
// simulate a partial split
KeyExtent tab1e22 = nke("tab1", null, "m");
setLocation(tservers, "tserver2", MTE, tab1e22, "tserver6");
locateTabletTest(tab1TabletCache, "r1", tab1e2, "tserver5");
tab1TabletCache.invalidateCache(tab1e2);
locateTabletTest(tab1TabletCache, "r1", tab1e22, "tserver6");
locateTabletTest(tab1TabletCache, "h", null, null);
locateTabletTest(tab1TabletCache, "a", tab1e1, "tserver4");
KeyExtent tab1e21 = nke("tab1", "m", "g");
setLocation(tservers, "tserver2", MTE, tab1e21, "tserver7");
locateTabletTest(tab1TabletCache, "r1", tab1e22, "tserver6");
locateTabletTest(tab1TabletCache, "h", tab1e21, "tserver7");
locateTabletTest(tab1TabletCache, "a", tab1e1, "tserver4");
// simulate a migration
setLocation(tservers, "tserver2", MTE, tab1e21, "tserver8");
tab1TabletCache.invalidateCache(tab1e21);
locateTabletTest(tab1TabletCache, "r1", tab1e22, "tserver6");
locateTabletTest(tab1TabletCache, "h", tab1e21, "tserver8");
locateTabletTest(tab1TabletCache, "a", tab1e1, "tserver4");
// simulate a server failure
setLocation(tservers, "tserver2", MTE, tab1e21, "tserver9");
tab1TabletCache.invalidateCache(context, "tserver8");
locateTabletTest(tab1TabletCache, "r1", tab1e22, "tserver6");
locateTabletTest(tab1TabletCache, "h", tab1e21, "tserver9");
locateTabletTest(tab1TabletCache, "a", tab1e1, "tserver4");
// simulate all servers failing
deleteServer(tservers, "tserver1");
deleteServer(tservers, "tserver2");
tab1TabletCache.invalidateCache(context, "tserver4");
tab1TabletCache.invalidateCache(context, "tserver6");
tab1TabletCache.invalidateCache(context, "tserver9");
locateTabletTest(tab1TabletCache, "r1", null, null);
locateTabletTest(tab1TabletCache, "h", null, null);
locateTabletTest(tab1TabletCache, "a", null, null);
EasyMock.verify(context);
context = EasyMock.createMock(ClientContext.class);
EasyMock.expect(context.getInstanceID()).andReturn("instance1").anyTimes();
EasyMock.expect(context.getRootTabletLocation()).andReturn("tserver4").anyTimes();
replay(context);
setLocation(tservers, "tserver4", RTE, MTE, "tserver5");
setLocation(tservers, "tserver5", MTE, tab1e1, "tserver1");
setLocation(tservers, "tserver5", MTE, tab1e21, "tserver2");
setLocation(tservers, "tserver5", MTE, tab1e22, "tserver3");
locateTabletTest(tab1TabletCache, "a", tab1e1, "tserver1");
locateTabletTest(tab1TabletCache, "h", tab1e21, "tserver2");
locateTabletTest(tab1TabletCache, "r", tab1e22, "tserver3");
// simulate the metadata table splitting
KeyExtent mte1 = new KeyExtent(MetadataTable.ID, tab1e21.getMetadataEntry(), RTE.getEndRow());
KeyExtent mte2 = new KeyExtent(MetadataTable.ID, null, tab1e21.getMetadataEntry());
setLocation(tservers, "tserver4", RTE, mte1, "tserver5");
setLocation(tservers, "tserver4", RTE, mte2, "tserver6");
deleteServer(tservers, "tserver5");
setLocation(tservers, "tserver5", mte1, tab1e1, "tserver7");
setLocation(tservers, "tserver5", mte1, tab1e21, "tserver8");
setLocation(tservers, "tserver6", mte2, tab1e22, "tserver9");
tab1TabletCache.invalidateCache(tab1e1);
tab1TabletCache.invalidateCache(tab1e21);
tab1TabletCache.invalidateCache(tab1e22);
locateTabletTest(tab1TabletCache, "a", tab1e1, "tserver7");
locateTabletTest(tab1TabletCache, "h", tab1e21, "tserver8");
locateTabletTest(tab1TabletCache, "r", tab1e22, "tserver9");
// simulate metadata and regular server down and the reassigned
deleteServer(tservers, "tserver5");
tab1TabletCache.invalidateCache(context, "tserver7");
locateTabletTest(tab1TabletCache, "a", null, null);
locateTabletTest(tab1TabletCache, "h", tab1e21, "tserver8");
locateTabletTest(tab1TabletCache, "r", tab1e22, "tserver9");
setLocation(tservers, "tserver4", RTE, mte1, "tserver10");
setLocation(tservers, "tserver10", mte1, tab1e1, "tserver7");
setLocation(tservers, "tserver10", mte1, tab1e21, "tserver8");
locateTabletTest(tab1TabletCache, "a", tab1e1, "tserver7");
locateTabletTest(tab1TabletCache, "h", tab1e21, "tserver8");
locateTabletTest(tab1TabletCache, "r", tab1e22, "tserver9");
tab1TabletCache.invalidateCache(context, "tserver7");
setLocation(tservers, "tserver10", mte1, tab1e1, "tserver2");
locateTabletTest(tab1TabletCache, "a", tab1e1, "tserver2");
locateTabletTest(tab1TabletCache, "h", tab1e21, "tserver8");
locateTabletTest(tab1TabletCache, "r", tab1e22, "tserver9");
// simulate a hole in the metadata, caused by a partial split
KeyExtent mte11 = new KeyExtent(MetadataTable.ID, tab1e1.getMetadataEntry(), RTE.getEndRow());
KeyExtent mte12 =
new KeyExtent(MetadataTable.ID, tab1e21.getMetadataEntry(), tab1e1.getMetadataEntry());
deleteServer(tservers, "tserver10");
setLocation(tservers, "tserver4", RTE, mte12, "tserver10");
setLocation(tservers, "tserver10", mte12, tab1e21, "tserver12");
// at this point should be no table1 metadata
tab1TabletCache.invalidateCache(tab1e1);
tab1TabletCache.invalidateCache(tab1e21);
locateTabletTest(tab1TabletCache, "a", null, null);
locateTabletTest(tab1TabletCache, "h", tab1e21, "tserver12");
locateTabletTest(tab1TabletCache, "r", tab1e22, "tserver9");
setLocation(tservers, "tserver4", RTE, mte11, "tserver5");
setLocation(tservers, "tserver5", mte11, tab1e1, "tserver13");
locateTabletTest(tab1TabletCache, "a", tab1e1, "tserver13");
locateTabletTest(tab1TabletCache, "h", tab1e21, "tserver12");
locateTabletTest(tab1TabletCache, "r", tab1e22, "tserver9");
}
@Test
public void test2() throws Exception {
TServers tservers = new TServers();
TabletLocatorImpl metaCache = createLocators(tservers, "tserver1", "tserver2", "foo");
KeyExtent ke1 = nke("foo", "m", null);
KeyExtent ke2 = nke("foo", null, "m");
setLocation(tservers, "tserver2", MTE, ke1, null);
setLocation(tservers, "tserver2", MTE, ke2, "L1");
locateTabletTest(metaCache, "a", null, null);
locateTabletTest(metaCache, "r", ke2, "L1");
setLocation(tservers, "tserver2", MTE, ke1, "L2");
locateTabletTest(metaCache, "a", ke1, "L2");
locateTabletTest(metaCache, "r", ke2, "L1");
}
@Test
public void testBinRanges1() throws Exception {
TabletLocatorImpl metaCache = createLocators("foo", nke("foo", null, null), "l1");
List<Range> ranges = nrl(nr(null, null));
Map<String,Map<KeyExtent,List<Range>>> expected =
createExpectedBinnings("l1", nol(nke("foo", null, null), nrl(nr(null, null)))
);
runTest(ranges, metaCache, expected);
ranges = nrl(nr("a", null));
expected = createExpectedBinnings("l1", nol(nke("foo", null, null), nrl(nr("a", null)))
);
runTest(ranges, metaCache, expected);
ranges = nrl(nr(null, "b"));
expected = createExpectedBinnings("l1", nol(nke("foo", null, null), nrl(nr(null, "b")))
);
runTest(ranges, metaCache, expected);
}
@Test
public void testBinRanges2() throws Exception {
List<Range> ranges = nrl(nr(null, null));
TabletLocatorImpl metaCache =
createLocators("foo", nke("foo", "g", null), "l1", nke("foo", null, "g"), "l2");
Map<String,Map<KeyExtent,List<Range>>> expected =
createExpectedBinnings("l1", nol(nke("foo", "g", null), nrl(nr(null, null))), "l2",
nol(nke("foo", null, "g"), nrl(nr(null, null)))
);
runTest(ranges, metaCache, expected);
}
@Test
public void testBinRanges3() throws Exception {
// test with three tablets and a range that covers the whole table
List<Range> ranges = nrl(nr(null, null));
TabletLocatorImpl metaCache = createLocators("foo", nke("foo", "g", null), "l1",
nke("foo", "m", "g"), "l2", nke("foo", null, "m"), "l2");
Map<String,Map<KeyExtent,List<Range>>> expected = createExpectedBinnings("l1",
nol(nke("foo", "g", null), nrl(nr(null, null))), "l2",
nol(nke("foo", "m", "g"), nrl(nr(null, null)), nke("foo", null, "m"), nrl(nr(null, null)))
);
runTest(ranges, metaCache, expected);
// test with three tablets where one range falls within the first tablet and last two ranges
// fall within the last tablet
ranges = nrl(nr(null, "c"), nr("s", "y"), nr("z", null));
expected = createExpectedBinnings("l1", nol(nke("foo", "g", null), nrl(nr(null, "c"))), "l2",
nol(nke("foo", null, "m"), nrl(nr("s", "y"), nr("z", null)))
);
runTest(ranges, metaCache, expected);
// test is same as above, but has an additional range that spans the first two tablets
ranges = nrl(nr(null, "c"), nr("f", "i"), nr("s", "y"), nr("z", null));
expected =
createExpectedBinnings("l1", nol(nke("foo", "g", null), nrl(nr(null, "c"), nr("f", "i"))),
"l2", nol(nke("foo", "m", "g"), nrl(nr("f", "i")), nke("foo", null, "m"),
nrl(nr("s", "y"), nr("z", null)))
);
runTest(ranges, metaCache, expected);
// test where start of range is not inclusive and same as tablet endRow
ranges = nrl(nr("g", false, "m", true));
expected =
createExpectedBinnings("l2", nol(nke("foo", "m", "g"), nrl(nr("g", false, "m", true)))
);
runTest(ranges, metaCache, expected);
// test where start of range is inclusive and same as tablet endRow
ranges = nrl(nr("g", true, "m", true));
expected =
createExpectedBinnings("l1", nol(nke("foo", "g", null), nrl(nr("g", true, "m", true))),
"l2", nol(nke("foo", "m", "g"), nrl(nr("g", true, "m", true)))
);
runTest(ranges, metaCache, expected);
ranges = nrl(nr("g", true, "m", false));
expected =
createExpectedBinnings("l1", nol(nke("foo", "g", null), nrl(nr("g", true, "m", false))),
"l2", nol(nke("foo", "m", "g"), nrl(nr("g", true, "m", false)))
);
runTest(ranges, metaCache, expected);
ranges = nrl(nr("g", false, "m", false));
expected =
createExpectedBinnings("l2", nol(nke("foo", "m", "g"), nrl(nr("g", false, "m", false)))
);
runTest(ranges, metaCache, expected);
}
@Test
public void testBinRanges4() throws Exception {
List<Range> ranges = nrl(new Range(new Text("1")));
TabletLocatorImpl metaCache =
createLocators("foo", nke("foo", "0", null), "l1", nke("foo", "1", "0"), "l2",
nke("foo", "2", "1"), "l3", nke("foo", "3", "2"), "l4", nke("foo", null, "3"), "l5");
Map<String,Map<KeyExtent,List<Range>>> expected =
createExpectedBinnings("l2", nol(nke("foo", "1", "0"), nrl(new Range(new Text("1"))))
);
runTest(ranges, metaCache, expected);
Key rowColKey = new Key(new Text("3"), new Text("cf1"), new Text("cq1"));
Range range =
new Range(rowColKey, true, new Key(new Text("3")).followingKey(PartialKey.ROW), false);
ranges = nrl(range);
Map<String,Map<KeyExtent,List<Range>>> expected4 =
createExpectedBinnings("l4", nol(nke("foo", "3", "2"), nrl(range))
);
runTest(ranges, metaCache, expected4, nrl());
range = new Range(rowColKey, true, new Key(new Text("3")).followingKey(PartialKey.ROW), true);
ranges = nrl(range);
Map<String,Map<KeyExtent,List<Range>>> expected5 = createExpectedBinnings("l4",
nol(nke("foo", "3", "2"), nrl(range)), "l5", nol(nke("foo", null, "3"), nrl(range))
);
runTest(ranges, metaCache, expected5, nrl());
range = new Range(new Text("2"), false, new Text("3"), false);
ranges = nrl(range);
Map<String,Map<KeyExtent,List<Range>>> expected6 =
createExpectedBinnings("l4", nol(nke("foo", "3", "2"), nrl(range))
);
runTest(ranges, metaCache, expected6, nrl());
range = new Range(new Text("2"), true, new Text("3"), false);
ranges = nrl(range);
Map<String,Map<KeyExtent,List<Range>>> expected7 = createExpectedBinnings("l3",
nol(nke("foo", "2", "1"), nrl(range)), "l4", nol(nke("foo", "3", "2"), nrl(range))
);
runTest(ranges, metaCache, expected7, nrl());
range = new Range(new Text("2"), false, new Text("3"), true);
ranges = nrl(range);
Map<String,Map<KeyExtent,List<Range>>> expected8 =
createExpectedBinnings("l4", nol(nke("foo", "3", "2"), nrl(range))
);
runTest(ranges, metaCache, expected8, nrl());
range = new Range(new Text("2"), true, new Text("3"), true);
ranges = nrl(range);
Map<String,Map<KeyExtent,List<Range>>> expected9 = createExpectedBinnings("l3",
nol(nke("foo", "2", "1"), nrl(range)), "l4", nol(nke("foo", "3", "2"), nrl(range))
);
runTest(ranges, metaCache, expected9, nrl());
}
@Test
public void testBinRanges5() throws Exception {
// Test binning when there is a hole in the metadata
List<Range> ranges = nrl(new Range(new Text("1")));
TabletLocatorImpl metaCache = createLocators("foo", nke("foo", "0", null), "l1",
nke("foo", "1", "0"), "l2", nke("foo", "3", "2"), "l4", nke("foo", null, "3"), "l5");
Map<String,Map<KeyExtent,List<Range>>> expected1 =
createExpectedBinnings("l2", nol(nke("foo", "1", "0"), nrl(new Range(new Text("1"))))
);
runTest(ranges, metaCache, expected1);
ranges = nrl(new Range(new Text("2")), new Range(new Text("11")));
Map<String,Map<KeyExtent,List<Range>>> expected2 = createExpectedBinnings();
runTest(ranges, metaCache, expected2, ranges);
ranges = nrl(new Range(new Text("1")), new Range(new Text("2")));
runTest(ranges, metaCache, expected1, nrl(new Range(new Text("2"))));
ranges = nrl(nr("0", "2"), nr("3", "4"));
Map<String,Map<KeyExtent,List<Range>>> expected3 =
createExpectedBinnings("l4", nol(nke("foo", "3", "2"), nrl(nr("3", "4"))), "l5",
nol(nke("foo", null, "3"), nrl(nr("3", "4")))
);
runTest(ranges, metaCache, expected3, nrl(nr("0", "2")));
ranges =
nrl(nr("0", "1"), nr("0", "11"), nr("1", "2"), nr("0", "4"), nr("2", "4"), nr("21", "4"));
Map<String,Map<KeyExtent,List<Range>>> expected4 =
createExpectedBinnings("l1", nol(nke("foo", "0", null), nrl(nr("0", "1"))), "l2",
nol(nke("foo", "1", "0"), nrl(nr("0", "1"))), "l4",
nol(nke("foo", "3", "2"), nrl(nr("21", "4"))), "l5",
nol(nke("foo", null, "3"), nrl(nr("21", "4")))
);
runTest(ranges, metaCache, expected4,
nrl(nr("0", "11"), nr("1", "2"), nr("0", "4"), nr("2", "4")));
}
@Test
public void testBinMutations1() throws Exception {
// one tablet table
KeyExtent ke1 = nke("foo", null, null);
TabletLocatorImpl metaCache = createLocators("foo", ke1, "l1");
List<Mutation> ml =
nml(nm("a", "cf1:cq1=v1", "cf1:cq2=v2"), nm("c", "cf1:cq1=v3", "cf1:cq2=v4"));
Map<String,Map<KeyExtent,List<String>>> emb = cemb(nol("a", "l1", ke1), nol("c", "l1", ke1));
runTest(metaCache, ml, emb);
ml = nml(nm("a", "cf1:cq1=v1", "cf1:cq2=v2"));
emb = cemb(nol("a", "l1", ke1));
runTest(metaCache, ml, emb);
ml = nml(nm("a", "cf1:cq1=v1", "cf1:cq2=v2"), nm("a", "cf1:cq3=v3"));
emb = cemb(nol("a", "l1", ke1), nol("a", "l1", ke1));
runTest(metaCache, ml, emb);
}
@Test
public void testBinMutations2() throws Exception {
// no tablets for table
TabletLocatorImpl metaCache = createLocators("foo");
List<Mutation> ml =
nml(nm("a", "cf1:cq1=v1", "cf1:cq2=v2"), nm("c", "cf1:cq1=v3", "cf1:cq2=v4"));
Map<String,Map<KeyExtent,List<String>>> emb = cemb();
runTest(metaCache, ml, emb, "a", "c");
}
@Test
public void testBinMutations3() throws Exception {
// three tablet table
KeyExtent ke1 = nke("foo", "h", null);
KeyExtent ke2 = nke("foo", "t", "h");
KeyExtent ke3 = nke("foo", null, "t");
TabletLocatorImpl metaCache = createLocators("foo", ke1, "l1", ke2, "l2", ke3, "l3");
List<Mutation> ml =
nml(nm("a", "cf1:cq1=v1", "cf1:cq2=v2"), nm("i", "cf1:cq1=v3", "cf1:cq2=v4"));
Map<String,Map<KeyExtent,List<String>>> emb = cemb(nol("a", "l1", ke1), nol("i", "l2", ke2));
runTest(metaCache, ml, emb);
ml = nml(nm("a", "cf1:cq1=v1", "cf1:cq2=v2"));
emb = cemb(nol("a", "l1", ke1));
runTest(metaCache, ml, emb);
ml = nml(nm("a", "cf1:cq1=v1", "cf1:cq2=v2"), nm("a", "cf1:cq3=v3"));
emb = cemb(nol("a", "l1", ke1), nol("a", "l1", ke1));
runTest(metaCache, ml, emb);
ml = nml(nm("a", "cf1:cq1=v1", "cf1:cq2=v2"), nm("w", "cf1:cq3=v3"));
emb = cemb(nol("a", "l1", ke1), nol("w", "l3", ke3));
runTest(metaCache, ml, emb);
ml = nml(nm("a", "cf1:cq1=v1", "cf1:cq2=v2"), nm("w", "cf1:cq3=v3"), nm("z", "cf1:cq4=v4"));
emb = cemb(nol("a", "l1", ke1), nol("w", "l3", ke3), nol("z", "l3", ke3));
runTest(metaCache, ml, emb);
ml = nml(nm("h", "cf1:cq1=v1", "cf1:cq2=v2"), nm("t", "cf1:cq1=v1", "cf1:cq2=v2"));
emb = cemb(nol("h", "l1", ke1), nol("t", "l2", ke2));
runTest(metaCache, ml, emb);
}
@Test
public void testBinMutations4() throws Exception {
// three table with hole
KeyExtent ke1 = nke("foo", "h", null);
KeyExtent ke3 = nke("foo", null, "t");
TabletLocatorImpl metaCache = createLocators("foo", ke1, "l1", ke3, "l3");
List<Mutation> ml =
nml(nm("a", "cf1:cq1=v1", "cf1:cq2=v2"), nm("i", "cf1:cq1=v3", "cf1:cq2=v4"));
Map<String,Map<KeyExtent,List<String>>> emb = cemb(nol("a", "l1", ke1));
runTest(metaCache, ml, emb, "i");
ml = nml(nm("a", "cf1:cq1=v1", "cf1:cq2=v2"));
emb = cemb(nol("a", "l1", ke1));
runTest(metaCache, ml, emb);
ml = nml(nm("a", "cf1:cq1=v1", "cf1:cq2=v2"), nm("a", "cf1:cq3=v3"));
emb = cemb(nol("a", "l1", ke1), nol("a", "l1", ke1));
runTest(metaCache, ml, emb);
ml = nml(nm("a", "cf1:cq1=v1", "cf1:cq2=v2"), nm("w", "cf1:cq3=v3"));
emb = cemb(nol("a", "l1", ke1), nol("w", "l3", ke3));
runTest(metaCache, ml, emb);
ml = nml(nm("a", "cf1:cq1=v1", "cf1:cq2=v2"), nm("w", "cf1:cq3=v3"), nm("z", "cf1:cq4=v4"));
emb = cemb(nol("a", "l1", ke1), nol("w", "l3", ke3), nol("z", "l3", ke3));
runTest(metaCache, ml, emb);
ml = nml(nm("a", "cf1:cq1=v1", "cf1:cq2=v2"), nm("w", "cf1:cq3=v3"), nm("z", "cf1:cq4=v4"),
nm("t", "cf1:cq5=v5"));
emb = cemb(nol("a", "l1", ke1), nol("w", "l3", ke3), nol("z", "l3", ke3));
runTest(metaCache, ml, emb, "t");
}
@Test
public void testBinSplit() throws Exception {
// try binning mutations and ranges when a tablet splits
for (int i = 0; i < 3; i++) {
// when i == 0 only test binning mutations
// when i == 1 only test binning ranges
// when i == 2 test both
KeyExtent ke1 = nke("foo", null, null);
TServers tservers = new TServers();
TabletLocatorImpl metaCache =
createLocators(tservers, "tserver1", "tserver2", "foo", ke1, "l1");
List<Mutation> ml = nml(nm("a", "cf1:cq1=v1", "cf1:cq2=v2"),
nm("m", "cf1:cq1=v3", "cf1:cq2=v4"), nm("z", "cf1:cq1=v5"));
Map<String,Map<KeyExtent,List<String>>> emb =
cemb(nol("a", "l1", ke1), nol("m", "l1", ke1), nol("z", "l1", ke1));
if (i == 0 || i == 2)
runTest(metaCache, ml, emb);
List<Range> ranges =
nrl(new Range(new Text("a")), new Range(new Text("m")), new Range(new Text("z")));
Map<String,Map<KeyExtent,List<Range>>> expected1 =
createExpectedBinnings("l1", nol(nke("foo", null, null), ranges)
);
if (i == 1 || i == 2)
runTest(ranges, metaCache, expected1);
KeyExtent ke11 = nke("foo", "n", null);
KeyExtent ke12 = nke("foo", null, "n");
setLocation(tservers, "tserver2", MTE, ke12, "l2");
metaCache.invalidateCache(ke1);
emb = cemb(nol("z", "l2", ke12));
if (i == 0 || i == 2)
runTest(metaCache, ml, emb, "a", "m");
Map<String,Map<KeyExtent,List<Range>>> expected2 =
createExpectedBinnings("l2", nol(nke("foo", null, "n"), nrl(new Range(new Text("z"))))
);
if (i == 1 || i == 2)
runTest(ranges, metaCache, expected2,
nrl(new Range(new Text("a")), new Range(new Text("m"))));
setLocation(tservers, "tserver2", MTE, ke11, "l3");
emb = cemb(nol("a", "l3", ke11), nol("m", "l3", ke11), nol("z", "l2", ke12));
if (i == 0 || i == 2)
runTest(metaCache, ml, emb);
Map<String,
Map<KeyExtent,List<Range>>> expected3 = createExpectedBinnings("l2",
nol(nke("foo", null, "n"), nrl(new Range(new Text("z")))), "l3",
nol(nke("foo", "n", null), nrl(new Range(new Text("a")), new Range(new Text("m"))))
);
if (i == 1 || i == 2)
runTest(ranges, metaCache, expected3);
}
}
@Test
public void testBug1() throws Exception {
// a bug that occurred while running continuous ingest
KeyExtent mte1 = new KeyExtent(MetadataTable.ID, new Text("0;0bc"), RTE.getEndRow());
KeyExtent mte2 = new KeyExtent(MetadataTable.ID, null, new Text("0;0bc"));
TServers tservers = new TServers();
TestTabletLocationObtainer ttlo = new TestTabletLocationObtainer(tservers);
RootTabletLocator rtl = new TestRootTabletLocator();
TabletLocatorImpl rootTabletCache =
new TabletLocatorImpl(MetadataTable.ID, rtl, ttlo, new YesLockChecker());
TabletLocatorImpl tab0TabletCache =
new TabletLocatorImpl(TableId.of("0"), rootTabletCache, ttlo, new YesLockChecker());
setLocation(tservers, "tserver1", RTE, mte1, "tserver2");
setLocation(tservers, "tserver1", RTE, mte2, "tserver3");
// create two tablets that straddle a metadata split point
KeyExtent ke1 = new KeyExtent(TableId.of("0"), new Text("0bbf20e"), null);
KeyExtent ke2 = new KeyExtent(TableId.of("0"), new Text("0bc0756"), new Text("0bbf20e"));
setLocation(tservers, "tserver2", mte1, ke1, "tserver4");
setLocation(tservers, "tserver3", mte2, ke2, "tserver5");
// look up something that comes after the last entry in mte1
locateTabletTest(tab0TabletCache, "0bbff", ke2, "tserver5");
}
@Test
public void testBug2() throws Exception {
// a bug that occurred while running a functional test
KeyExtent mte1 = new KeyExtent(MetadataTable.ID, new Text("~"), RTE.getEndRow());
KeyExtent mte2 = new KeyExtent(MetadataTable.ID, null, new Text("~"));
TServers tservers = new TServers();
TestTabletLocationObtainer ttlo = new TestTabletLocationObtainer(tservers);
RootTabletLocator rtl = new TestRootTabletLocator();
TabletLocatorImpl rootTabletCache =
new TabletLocatorImpl(MetadataTable.ID, rtl, ttlo, new YesLockChecker());
TabletLocatorImpl tab0TabletCache =
new TabletLocatorImpl(TableId.of("0"), rootTabletCache, ttlo, new YesLockChecker());
setLocation(tservers, "tserver1", RTE, mte1, "tserver2");
setLocation(tservers, "tserver1", RTE, mte2, "tserver3");
// create the ~ tablet so it exists
Map<KeyExtent,SortedMap<Key,Value>> ts3 = new HashMap<>();
ts3.put(mte2, new TreeMap<>());
tservers.tservers.put("tserver3", ts3);
assertNull(tab0TabletCache.locateTablet(context, new Text("row_0000000000"), false, false));
}
// this test reproduces a problem where empty metadata tablets, that were created by user tablets
// being merged away, caused locating tablets to fail
@Test
public void testBug3() throws Exception {
KeyExtent mte1 = new KeyExtent(MetadataTable.ID, new Text("1;c"), RTE.getEndRow());
KeyExtent mte2 = new KeyExtent(MetadataTable.ID, new Text("1;f"), new Text("1;c"));
KeyExtent mte3 = new KeyExtent(MetadataTable.ID, new Text("1;j"), new Text("1;f"));
KeyExtent mte4 = new KeyExtent(MetadataTable.ID, new Text("1;r"), new Text("1;j"));
KeyExtent mte5 = new KeyExtent(MetadataTable.ID, null, new Text("1;r"));
KeyExtent ke1 = new KeyExtent(TableId.of("1"), null, null);
TServers tservers = new TServers();
TestTabletLocationObtainer ttlo = new TestTabletLocationObtainer(tservers);
RootTabletLocator rtl = new TestRootTabletLocator();
TabletLocatorImpl rootTabletCache =
new TabletLocatorImpl(MetadataTable.ID, rtl, ttlo, new YesLockChecker());
TabletLocatorImpl tab0TabletCache =
new TabletLocatorImpl(TableId.of("1"), rootTabletCache, ttlo, new YesLockChecker());
setLocation(tservers, "tserver1", RTE, mte1, "tserver2");
setLocation(tservers, "tserver1", RTE, mte2, "tserver3");
setLocation(tservers, "tserver1", RTE, mte3, "tserver4");
setLocation(tservers, "tserver1", RTE, mte4, "tserver5");
setLocation(tservers, "tserver1", RTE, mte5, "tserver6");
createEmptyTablet(tservers, "tserver2", mte1);
createEmptyTablet(tservers, "tserver3", mte2);
createEmptyTablet(tservers, "tserver4", mte3);
createEmptyTablet(tservers, "tserver5", mte4);
setLocation(tservers, "tserver6", mte5, ke1, "tserver7");
locateTabletTest(tab0TabletCache, "a", ke1, "tserver7");
}
@Test
public void testAccumulo1248() {
TServers tservers = new TServers();
TabletLocatorImpl metaCache = createLocators(tservers, "tserver1", "tserver2", "foo");
KeyExtent ke1 = nke("foo", null, null);
// set two locations for a tablet, this is not supposed to happen. The metadata cache should
// throw an exception if it sees this rather than caching one of
// the locations.
setLocation(tservers, "tserver2", MTE, ke1, "L1", "I1");
setLocation(tservers, "tserver2", MTE, ke1, "L2", "I2");
try {
metaCache.locateTablet(context, new Text("a"), false, false);
fail();
} catch (Exception e) {
}
}
@Test
public void testLostLock() throws Exception {
final HashSet<String> activeLocks = new HashSet<>();
TServers tservers = new TServers();
TabletLocatorImpl metaCache =
createLocators(tservers, "tserver1", "tserver2", "foo", new TabletServerLockChecker() {
@Override
public boolean isLockHeld(String tserver, String session) {
return activeLocks.contains(tserver + ":" + session);
}
@Override
public void invalidateCache(String server) {}
});
KeyExtent ke1 = nke("foo", null, null);
setLocation(tservers, "tserver2", MTE, ke1, "L1", "5");
activeLocks.add("L1:5");
locateTabletTest(metaCache, "a", ke1, "L1");
locateTabletTest(metaCache, "a", ke1, "L1");
activeLocks.clear();
locateTabletTest(metaCache, "a", null, null);
locateTabletTest(metaCache, "a", null, null);
locateTabletTest(metaCache, "a", null, null);
clearLocation(tservers, "tserver2", MTE, ke1, "5");
setLocation(tservers, "tserver2", MTE, ke1, "L2", "6");
activeLocks.add("L2:6");
locateTabletTest(metaCache, "a", ke1, "L2");
locateTabletTest(metaCache, "a", ke1, "L2");
clearLocation(tservers, "tserver2", MTE, ke1, "6");
locateTabletTest(metaCache, "a", ke1, "L2");
setLocation(tservers, "tserver2", MTE, ke1, "L3", "7");
locateTabletTest(metaCache, "a", ke1, "L2");
activeLocks.clear();
locateTabletTest(metaCache, "a", null, null);
locateTabletTest(metaCache, "a", null, null);
activeLocks.add("L3:7");
locateTabletTest(metaCache, "a", ke1, "L3");
locateTabletTest(metaCache, "a", ke1, "L3");
List<Mutation> ml = nml(nm("a", "cf1:cq1=v1", "cf1:cq2=v2"), nm("w", "cf1:cq3=v3"));
Map<String,Map<KeyExtent,List<String>>> emb = cemb(nol("a", "L3", ke1), nol("w", "L3", ke1));
runTest(metaCache, ml, emb);
clearLocation(tservers, "tserver2", MTE, ke1, "7");
runTest(metaCache, ml, emb);
activeLocks.clear();
emb.clear();
runTest(metaCache, ml, emb, "a", "w");
runTest(metaCache, ml, emb, "a", "w");
KeyExtent ke11 = nke("foo", "m", null);
KeyExtent ke12 = nke("foo", null, "m");
setLocation(tservers, "tserver2", MTE, ke11, "L1", "8");
setLocation(tservers, "tserver2", MTE, ke12, "L2", "9");
runTest(metaCache, ml, emb, "a", "w");
activeLocks.add("L1:8");
emb = cemb(nol("a", "L1", ke11));
runTest(metaCache, ml, emb, "w");
activeLocks.add("L2:9");
emb = cemb(nol("a", "L1", ke11), nol("w", "L2", ke12));
runTest(metaCache, ml, emb);
List<Range> ranges = nrl(new Range("a"), nr("b", "o"), nr("r", "z"));
Map<String,Map<KeyExtent,List<Range>>> expected =
createExpectedBinnings("L1", nol(ke11, nrl(new Range("a"), nr("b", "o"))), "L2",
nol(ke12, nrl(nr("b", "o"), nr("r", "z"))));
runTest(ranges, metaCache, expected);
activeLocks.remove("L2:9");
expected = createExpectedBinnings("L1", nol(ke11, nrl(new Range("a"))));
runTest(ranges, metaCache, expected, nrl(nr("b", "o"), nr("r", "z")));
activeLocks.clear();
expected = createExpectedBinnings();
runTest(ranges, metaCache, expected, nrl(new Range("a"), nr("b", "o"), nr("r", "z")));
clearLocation(tservers, "tserver2", MTE, ke11, "8");
clearLocation(tservers, "tserver2", MTE, ke12, "9");
setLocation(tservers, "tserver2", MTE, ke11, "L3", "10");
setLocation(tservers, "tserver2", MTE, ke12, "L4", "11");
runTest(ranges, metaCache, expected, nrl(new Range("a"), nr("b", "o"), nr("r", "z")));
activeLocks.add("L3:10");
expected = createExpectedBinnings("L3", nol(ke11, nrl(new Range("a"))));
runTest(ranges, metaCache, expected, nrl(nr("b", "o"), nr("r", "z")));
activeLocks.add("L4:11");
expected = createExpectedBinnings("L3", nol(ke11, nrl(new Range("a"), nr("b", "o"))), "L4",
nol(ke12, nrl(nr("b", "o"), nr("r", "z"))));
runTest(ranges, metaCache, expected);
}
}
| 36.839072
| 99
| 0.627084
|
11dbfbfe4e637e6b04dacec21d0e25148ab039d9
| 741
|
package info.novatec.javaconfig.service;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import info.novatec.javaconfig.SpringConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=SpringConfiguration.class)
public class MyService1Test {
@Autowired
private MyService1 cut;
@Test
public final void testCallService2() {
assertThat("Should have got expected message", cut.callService2("World"), is("Hello World"));
}
}
| 27.444444
| 95
| 0.815115
|
784b0c6f7e1ca7c3d0b2be38896974b5823ba8d7
| 696
|
package org.xero1425.base.tankdrive ;
/// \file
import org.xero1425.base.actions.Action;
/// \brief This class is the base class for all TankDriveSubsystem actions
public abstract class TankDriveAction extends Action
{
/// \brief Create the object holding a reference to the subsystem
/// \param drive the tankdrive subsystem
public TankDriveAction(TankDriveSubsystem drive) {
super(drive.getRobot().getMessageLogger()) ;
tankdrive_ = drive ;
}
/// \brief return the tank drive subsystem
/// returns the tank drive subsystem
public TankDriveSubsystem getSubsystem() {
return tankdrive_ ;
}
private TankDriveSubsystem tankdrive_ ;
}
| 29
| 74
| 0.71408
|
8590de174f36bb49eb69ea762cd5adde807cbf75
| 1,558
|
package edu.mssm.pharm.maayanlab.Harmonizome.json.schema;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
public class ErrorSchema {
public int status;
public String message;
public String description;
public static enum Status {
BAD_REQUEST,
UNAUTHORIZED,
FORBIDDEN,
NOT_FOUND,
METHOD_NOT_ALLOWED
}
private static Map<Status, Pair<Integer, String>> statusToMessage = new HashMap<Status, Pair<Integer, String>>();
static {
statusToMessage.put(Status.BAD_REQUEST, new ImmutablePair<Integer, String>(400, "Bad request."));
statusToMessage.put(Status.UNAUTHORIZED, new ImmutablePair<Integer, String>(401, "Unauthorized."));
statusToMessage.put(Status.FORBIDDEN, new ImmutablePair<Integer, String>(403, "Forbidden."));
statusToMessage.put(Status.NOT_FOUND, new ImmutablePair<Integer, String>(404, "Not found."));
}
public ErrorSchema() {
this.status = statusToMessage.get(Status.BAD_REQUEST).getLeft();
this.message = statusToMessage.get(Status.BAD_REQUEST).getRight();
}
public ErrorSchema(Status status, String description) {
this.status = statusToMessage.get(status).getLeft();
this.message = statusToMessage.get(status).getRight();
this.description = description;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
| 25.966667
| 114
| 0.747112
|
bd232b23a3eec88f440f1ce8613531eb898bbfba
| 4,647
|
/*
* Copyright 2016, The Android Open Source Project
* Copyright (c) 2017-2018 Spotify AB
*
* 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.example.android.architecture.blueprints.todoapp.taskdetail.view;
import static com.example.android.architecture.blueprints.todoapp.taskdetail.domain.TaskDetailEvent.activateTaskRequested;
import static com.example.android.architecture.blueprints.todoapp.taskdetail.domain.TaskDetailEvent.completeTaskRequested;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import com.example.android.architecture.blueprints.todoapp.R;
import com.example.android.architecture.blueprints.todoapp.taskdetail.domain.TaskDetailEvent;
import com.spotify.mobius.Connectable;
import com.spotify.mobius.Connection;
import com.spotify.mobius.functions.Consumer;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import javax.annotation.Nonnull;
public class TaskDetailViews
implements TaskDetailViewActions, Connectable<TaskDetailViewData, TaskDetailEvent> {
private final FloatingActionButton mFab;
private final Observable<TaskDetailEvent> mMenuEvents;
private TextView mDetailTitle;
private TextView mDetailDescription;
private CheckBox mDetailCompleteStatus;
private final View mRootView;
public TaskDetailViews(
LayoutInflater inflater,
ViewGroup container,
FloatingActionButton fab,
Observable<TaskDetailEvent> menuEvents) {
mRootView = inflater.inflate(R.layout.taskdetail_frag, container, false);
mMenuEvents = menuEvents;
mDetailTitle = mRootView.findViewById(R.id.task_detail_title);
mDetailDescription = mRootView.findViewById(R.id.task_detail_description);
mDetailCompleteStatus = mRootView.findViewById(R.id.task_detail_complete);
mFab = fab;
}
public View getRootView() {
return mRootView;
}
@Override
public void showTaskMarkedComplete() {
Snackbar.make(mRootView, R.string.task_marked_complete, Snackbar.LENGTH_LONG).show();
}
@Override
public void showTaskMarkedActive() {
Snackbar.make(mRootView, R.string.task_marked_active, Snackbar.LENGTH_LONG).show();
}
@Override
public void showTaskDeletionFailed() {
Snackbar.make(mRootView, "Failed to delete task", Snackbar.LENGTH_LONG).show();
}
@Override
public void showTaskSavingFailed() {
Snackbar.make(mRootView, "Failed to save change", Snackbar.LENGTH_LONG).show();
}
private void render(TaskDetailViewData viewData) {
mDetailCompleteStatus.setChecked(viewData.completedChecked());
bindTextViewData(mDetailTitle, viewData.title());
bindTextViewData(mDetailDescription, viewData.description());
}
private void bindTextViewData(TextView textView, TaskDetailViewData.TextViewData viewData) {
textView.setVisibility(viewData.visibility());
textView.setText(viewData.text());
}
@Nonnull
@Override
public Connection<TaskDetailViewData> connect(Consumer<TaskDetailEvent> output) {
mFab.setOnClickListener(__ -> output.accept(TaskDetailEvent.editTaskRequested()));
mDetailCompleteStatus.setOnCheckedChangeListener(
(buttonView, isChecked) -> {
if (isChecked) {
output.accept(completeTaskRequested());
} else {
output.accept(activateTaskRequested());
}
});
Disposable disposable =
mMenuEvents
.retry()
.subscribe(
output::accept,
t -> Log.e(TaskDetailViews.class.getSimpleName(), "Menu events seem to fail", t));
return new Connection<TaskDetailViewData>() {
@Override
public void accept(TaskDetailViewData value) {
render(value);
}
@Override
public void dispose() {
disposable.dispose();
mFab.setOnClickListener(null);
mDetailCompleteStatus.setOnCheckedChangeListener(null);
}
};
}
}
| 34.169118
| 122
| 0.746288
|
f8469dacf6b245b01418eb6e5295982c9431b21a
| 5,715
|
package io.sphere.sdk.json;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.sphere.sdk.models.LocalizedString;
import org.junit.Test;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import static java.util.Locale.*;
import static org.assertj.core.api.Assertions.*;
public class SphereJsonUtilsTest {
@Test
public void serializeZonedDateTime() throws Exception {
final String timeAsString = "2007-12-03T10:15:30+02:00[Europe/Berlin]";
final ZonedDateTime dateTime = ZonedDateTime.parse(timeAsString);
final String actual = SphereJsonUtils.toJsonString(dateTime);
assertThat(actual).isEqualTo("\"2007-12-03T09:15:30.000Z\"");
}
@Test
public void deserializeZonedDateTime() throws Exception {
final String timeAsString = "2001-09-11T14:00:00.000Z";
final ZonedDateTime actual = SphereJsonUtils.readObject(("\"" + timeAsString + "\"").getBytes(), TypeReferences.zonedDateTimeTypeReference());
assertThat(DateTimeFormatter.ISO_INSTANT.format(actual)).isEqualTo("2001-09-11T14:00:00Z");
}
@Test
public void prettyPrint() throws Exception {
final String jsonString = "{\"de\":\"Hundefutter\",\"en\":\"dog food\"}";
final String actual = SphereJsonUtils.prettyPrint(jsonString);
assertThat(actual).isEqualTo("{\n" +
" \"de\" : \"Hundefutter\",\n" +
" \"en\" : \"dog food\"\n" +
"}"
);
}
@Test
public void toJsonString() throws Exception {
final LocalizedString value = LocalizedString.of(ENGLISH, "dog food", GERMAN, "Hundefutter");
assertThat(SphereJsonUtils.toJsonString(value))
.isEqualTo("{\"en\":\"dog food\",\"de\":\"Hundefutter\"}");
}
@Test
public void toPrettyJsonString() throws Exception {
final LocalizedString value = LocalizedString.of(ENGLISH, "dog food", GERMAN, "Hundefutter");
assertThat(SphereJsonUtils.toPrettyJsonString(value))
.isEqualTo("{\n" +
" \"en\" : \"dog food\",\n" +
" \"de\" : \"Hundefutter\"\n" +
"}");
}
@Test
public void readObjectFromJsonString() throws Exception {
final String jsonString = "{\"de\":\"Hundefutter\",\"en\":\"dog food\"}";
final LocalizedString actual =
SphereJsonUtils.readObject(jsonString, LocalizedString.typeReference());
assertThat(actual).isEqualTo(LocalizedString.of(ENGLISH, "dog food", GERMAN, "Hundefutter"));
}
@Test
public void readObjectFromJsonNode() throws Exception {
final ObjectNode jsonNode = SphereJsonUtils.newObjectNode();
jsonNode.put("de", "Hundefutter");
jsonNode.put("en", "dog food");
final LocalizedString actual =
SphereJsonUtils.readObject(jsonNode, LocalizedString.typeReference());
assertThat(actual).isEqualTo(LocalizedString.of(ENGLISH, "dog food", GERMAN, "Hundefutter"));
}
@Test
public void parse() throws Exception {
final JsonNode actual =
SphereJsonUtils.parse("{\"de\":\"Hundefutter\",\"en\":\"dog food\"}");
final ObjectNode expected = SphereJsonUtils.newObjectNode();
expected.put("de", "Hundefutter");
expected.put("en", "dog food");
assertThat(actual).isEqualTo(expected);
}
@Test
public void readObjectFromJsonNodeWithClass() throws Exception {
final ObjectNode jsonNode = SphereJsonUtils.newObjectNode();
jsonNode.put("de", "Hundefutter");
jsonNode.put("en", "dog food");
final LocalizedString actual =
SphereJsonUtils.readObject(jsonNode, LocalizedString.class);
assertThat(actual).isEqualTo(LocalizedString.of(ENGLISH, "dog food", GERMAN, "Hundefutter"));
}
@Test
public void toJsonNode() throws Exception {
final LocalizedString value = LocalizedString.of(ENGLISH, "dog food", GERMAN, "Hundefutter");
final JsonNode actual = SphereJsonUtils.toJsonNode(value);
assertThat(actual.get("de").asText()).isEqualTo("Hundefutter");
assertThat(actual.get("en").asText()).isEqualTo("dog food");
}
@Test
public void exceptionHandling() throws Exception {
final String brokenJsonString = "{\"de\":\",]]]]";
assertThatThrownBy(() -> SphereJsonUtils.readObject(brokenJsonString, LocalizedString.typeReference()))
.isInstanceOf(JsonException.class);
}
@Test
public void serializeLocale() {
final String jsonString = SphereJsonUtils.toJsonString(Locale.ENGLISH);
assertThat(jsonString).isEqualTo("\"en\"");
}
@Test
public void deserializelLocale() {
final String jsonString = "\"en\"";
final Locale locale = SphereJsonUtils.readObject(jsonString, TypeReferences.localeTypeReference());
assertThat(locale).isEqualTo(Locale.ENGLISH);
}
@Test
public void serializeFullLocale() {
final String jsonString = SphereJsonUtils.toJsonString(Locale.US);
assertThat(jsonString).isEqualTo("\"en-US\"");
}
@Test
public void deserializeFullLocale() {
final String jsonString = "\"en-US\"";
final Locale locale = SphereJsonUtils.readObject(jsonString, TypeReferences.localeTypeReference());
assertThat(locale).isEqualTo(Locale.US);
}
@Test
public void doNotFailOnEmptyBeans() {
SphereJsonUtils.toJsonNode(new EmptyBean());
}
private static class EmptyBean {
}
}
| 39.143836
| 150
| 0.645844
|
b232f2f717b5769df0a22879cc64ec447da2ea23
| 1,625
|
package com.zhangls.apijson.base.service;
import com.alibaba.fastjson.JSONObject;
import com.zhangls.apijson.annotation.NotNull;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Map;
/**
* executor for query(read) or update(write) MySQL database
*
* @author Lemon
*/
public interface SqlExecutor {
/**
* 保存缓存
*
* @param sql
* @param map
* @param isStatic
*/
void putCache(String sql, Map<Integer, JSONObject> map, boolean isStatic);
/**
* 移除缓存
*
* @param sql
* @param isStatic
*/
void removeCache(String sql, boolean isStatic);
/**
* 获取缓存
*
* @param sql
* @param position
* @param isStatic
* @return
*/
JSONObject getCache(String sql, int position, boolean isStatic);
/**
* 执行SQL
*
* @param config
* @return
* @throws Exception
*/
JSONObject execute(SqlConfig config) throws Exception;
//executeQuery和executeUpdate这两个函数因为返回类型不同,所以不好合并
/**
* 执行查询
*
* @param config
* @return
* @throws SQLException
*/
ResultSet executeQuery(@NotNull SqlConfig config) throws Exception;
/**
* 执行增、删、改
*
* @param config
* @return
* @throws SQLException
*/
int executeUpdate(@NotNull SqlConfig config) throws Exception;
/**
* 判断是否为JSON类型
*
* @param rsmd
* @param position
* @return
*/
boolean isJSONType(ResultSetMetaData rsmd, int position);
/**
* 关闭连接,释放资源
*/
void close();
}
| 17.663043
| 78
| 0.592615
|
f7c74d67c4ed91a9386c5ba52238ed3f769b007a
| 1,380
|
package devcrema.spring_jpa_rest_board_example.config;
import devcrema.spring_jpa_rest_board_example.user.domain.User;
import org.springframework.core.MethodParameter;
import org.springframework.lang.NonNull;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return User.class.isAssignableFrom(parameter.getParameterType());
}
@Override
public Object resolveArgument(@NonNull MethodParameter parameter, ModelAndViewContainer mavContainer, @NonNull NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if(authentication == null) throw new AuthenticationFailedException("user authentication must not be null");
return authentication.getPrincipal();
}
}
| 44.516129
| 181
| 0.82971
|
59977957b073f64d00e4c45ba77ac63a103acfc7
| 303
|
package com.fancyfon.mobile.android.verification;
/**
* @author: Lena Jurkiewicz <lena.jurkiewicz@fancyfon.com>
*/
public interface CallerVerificator {
boolean isCallerPermitted(int callingId);
void isCallerPermitted(int callingId, CallerVerificatiorCallback callerVerificatiorCallback);
}
| 25.25
| 97
| 0.79538
|
6455756fce1f8c507facceb548af81e875f12ee0
| 72
|
package common;
public interface IReceiver<T> {
void receive(T t);
}
| 12
| 31
| 0.708333
|
16ef169b6c033848753d90c02e0bd2953a0a9b2c
| 112
|
package estruturalAdapter;
public interface PlugueDoisPinos
{
public void conectar(TomadaDoisPinos tomada);
}
| 16
| 46
| 0.830357
|
ea39c018c550b6032f0f52728385f42e19b40025
| 572
|
package fpt.g31.fsmis.entity;
import lombok.*;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
@Entity
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "tbl_report_user")
public class ReportUser {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(columnDefinition = "TEXT")
private String description;
@NotNull
private LocalDateTime time;
@ManyToOne
private User user;
@ManyToOne
private Report report;
}
| 15.888889
| 51
| 0.729021
|
7fa1a15656161a87601b49437cf9d297650ef0bc
| 912
|
package com.mq.consumer.kafka.scheduler;
import com.mq.thread.task.DefaultTaskExecutor;
import com.mq.thread.task.TaskExecutorService;
import com.mq.thread.task.TaskExecutorTtlWrapper;
import java.util.concurrent.*;
public class KakaOffsetLogTaskExecutor extends DefaultTaskExecutor {
public KakaOffsetLogTaskExecutor(){
initialize();
}
@Override
protected void initialize() {
ExecutorService executorService = new ThreadPoolExecutor(1,
1,
180,
TimeUnit.SECONDS,
new LinkedBlockingQueue(20000),defaultThreadFactory, defaultRejectedHandler);
taskExecutor = new TaskExecutorService(executorService, TaskExecutorTtlWrapper.class);
}
@Override
public void destroy() throws Exception {
//这里重载销毁方法是为了手动控制资源释放
}
public void stop() throws Exception {
super.destroy();
}
}
| 26.823529
| 94
| 0.691886
|
f1af0c0b04b31ae31350d1bb549ab2a691d80099
| 563
|
package com.deleidos.rtws.systemcfg.composers;
import com.deleidos.rtws.commons.util.Initializable;
import com.deleidos.rtws.systemcfg.beans.SystemConfig;
import javax.xml.bind.MarshalException;
import java.io.InputStream;
/**
*
* @author rainerr
*
* Compose the objects need to build an actual file.
*
*/
public interface DefinitionComposer extends Initializable {
public void writeFile(String version, String fileName);
public void loadDefaults(InputStream stream) throws MarshalException;
public String compose(SystemConfig systemConfig);
}
| 22.52
| 71
| 0.790409
|
b241ac8a71b5bd3ecc35459c2ff656d0b8f6ee9f
| 635
|
package com.bjc.protoss.dp.module.decorator.wesley.impl;
import java.util.HashMap;
import java.util.Map;
import com.bjc.protoss.dp.module.decorator.wesley.DataCache;
public class Redis implements DataCache {
Map<String, String> cache = new HashMap<>();
@Override
public String setValue(String key, String value) {
System.out.println("** Operation [Redis setValue.]");
cache.put(key, value);
return value;
}
@Override
public String getValue(String key) {
System.out.println("** Operation [Redis getValue.]");
return cache.get(key);
}
}
| 24.423077
| 62
| 0.63937
|
2047f6d6691e0f6b6cf0616db19f12f7b33eeb3a
| 4,933
|
/**
* Copyright © 2018 spring-data-dynamodb-example (https://github.com/derjust/spring-data-dynamodb-examples)
*
* 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.github.derjust.spring_data_dynamodb_examples.multirepo;
import java.util.Date;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.socialsignin.spring.data.dynamodb.repository.config.EnableDynamoDBRepositories;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.Import;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig;
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import com.amazonaws.services.dynamodbv2.util.TableUtils;
import com.github.derjust.spring_data_dynamodb_examples.common.DynamoDBConfig;
@SpringBootApplication
@EnableJpaRepositories(includeFilters = {
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {CustomerRepository.class})})
@EnableDynamoDBRepositories(includeFilters = {
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {DeviceRepository.class})})
@Configuration
@Import(DynamoDBConfig.class)
public class Application {
private static final Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class).profiles("multirepo").run(args);
}
@Bean
public CommandLineRunner multirepo(ConfigurableApplicationContext ctx, CustomerRepository jpaRepository,
DeviceRepository dynamoDBRepository, AmazonDynamoDB amazonDynamoDB, DynamoDBMapper dynamoDBMapper,
DynamoDBMapperConfig config) {
return (args) -> {
demoJPA(jpaRepository);
CreateTableRequest ctr = dynamoDBMapper.generateCreateTableRequest(Device.class)
.withProvisionedThroughput(new ProvisionedThroughput(1L, 1L));
TableUtils.createTableIfNotExists(amazonDynamoDB, ctr);
TableUtils.waitUntilActive(amazonDynamoDB, ctr.getTableName());
demoDynamoDB(dynamoDBRepository);
ctx.close();
};
}
private void demoDynamoDB(DeviceRepository dynamoDBRepository) {
// save a couple of devices
dynamoDBRepository.save(new Device(1L, "Product A", "A", new Date()));
dynamoDBRepository.save(new Device(1L, "Product B", "B", new Date()));
dynamoDBRepository.save(new Device(2L, "Product C", "C", new Date()));
// fetch all devices
log.info("Devices found with findAll():");
log.info("-------------------------------");
for (Device device : dynamoDBRepository.findAll()) {
log.info(device.toString());
}
log.info("");
}
private void demoJPA(CustomerRepository jpaRepository) {
// save a couple of customers
jpaRepository.save(new Customer("Jack", "Bauer"));
jpaRepository.save(new Customer("Chloe", "O'Brian"));
jpaRepository.save(new Customer("Kim", "Bauer"));
jpaRepository.save(new Customer("David", "Palmer"));
jpaRepository.save(new Customer("Michelle", "Dessler"));
// fetch all customers
log.info("Customers found with findAll():");
log.info("-------------------------------");
for (Customer customer : jpaRepository.findAll()) {
log.info(customer.toString());
}
log.info("");
// fetch an individual customer by ID
Optional<Customer> customer = jpaRepository.findById(1L);
log.info("Customer found with findOne(1L):");
log.info("--------------------------------");
log.info(customer.get().toString());
log.info("");
// fetch customers by last name
log.info("Customer found with findByLastName('Bauer'):");
log.info("--------------------------------------------");
for (Customer bauer : jpaRepository.findByLastName("Bauer")) {
log.info(bauer.toString());
}
log.info("");
}
}
| 39.150794
| 107
| 0.752889
|
776bfbaacd5a31cce50dfa40e86a938dfad80595
| 5,546
|
package de.julian.baehr.immutable.allow;
import static de.julian.baehr.immutable.allow.PackageState.ALLOW;
import static de.julian.baehr.immutable.allow.PackageState.ALLOW_ALL;
import static de.julian.baehr.immutable.allow.PackageState.ALLOW_ALL_EXCEPT;
import static de.julian.baehr.immutable.allow.PackageState.NONE;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.logging.Logger;
class PackageInfo {
private static final Logger LOGGER = Logger.getLogger(PackageInfo.class.getName());
private PackageState packageState = NONE;
private final HashSet<String> classNames = new HashSet<>();
private final String packageName;
public PackageInfo(String packageName) {
this.packageName = packageName;
}
public String getPackageName() {
return packageName;
}
public PackageState getState() {
return packageState;
}
public boolean isAllowed(String simpleClassName){
switch(packageState){
case ALLOW_ALL_EXCEPT://note that any name in the list is now disallowed
return !classNames.contains(simpleClassName);
case ALLOW:
return classNames.contains(simpleClassName);
case ALLOW_ALL:
return true;
default:
return false;
}
}
private void logRedundantAllow(String operation, Collection<String> allowedClassNames){
LOGGER.warning("Package: " + getInfo() + "\n"
+ "Potential Error: redundant allow-operation '" + operation + "' for the following classes [" + String.join(", ", allowedClassNames) + "].");
}
private void logRedundantAllowBefore(String operation){
LOGGER.warning("Package: " + getInfo() + "\n"
+ "Potential Error: redundant allow-operations before '" + operation + "'.");
}
private void logAllowError(String operation, String cause){
LOGGER.severe("Package: " + getInfo() + "\n"
+ "Error: illegal allow-operation '" + operation + "'\n"
+ "Cause: " + cause);
}
/**
* Convenience method with a single string parameter.
* @param allowedClassName The name of the class that is allowed.
* @return true if the class name can be allowed, false if not.
*/
public boolean allow(String allowedClassName){
return allow(Arrays.asList(allowedClassName));
}
/**
* Allows all class names in the given collection.
* @param allowedClassNames The allowed class names.
* @return true if all the class names can be allowed, false if not.
*/
public boolean allow(Collection<String> allowedClassNames){
switch(packageState){
case ALLOW_ALL_EXCEPT: //note that any name in the list is now disallowed
//only possible if all the names are not disallowed
if(containsAnyOf(allowedClassNames)){
logAllowError("allow/allow_bulk", "already disallows at least one of these classes [" + String.join(", ", allowedClassNames) + "].");
return false;
}
//else do nothing
case ALLOW_ALL:
logRedundantAllow("allow/allow_bulk", allowedClassNames);
return true;//no fall-through because state should not change
case NONE://change state
packageState = ALLOW;
default:
if(containsAnyOf(allowedClassNames))
logRedundantAllow("allow/allow_bulk", allowedClassNames);
classNames.addAll(allowedClassNames);
return true;
}
}
/**
* Checks if at least one class name from the given collection is already in the class names list.
* @param allowedClassNames The class names to check.
* @return true if at least one class name is already in the list.
*/
private boolean containsAnyOf(Collection<String> allowedClassNames){
for(String className : allowedClassNames)
if(classNames.contains(className))
return true;
return false;
}
public boolean allowAll(){
switch(packageState){
case ALLOW_ALL_EXCEPT://transition not possible
logAllowError("allow_all", "cannot use 'allow_all' when in state " + getState().toString());
return false;
case NONE://change state and return true
packageState = ALLOW_ALL;
return true;
default://log redundant allow operation msg, change state and return true
logRedundantAllowBefore("allow_all");
packageState = ALLOW_ALL;
return true;
}
}
public boolean allowAllExcept(Collection<String> disallowedClassNames){
switch (packageState) {
case ALLOW_ALL://transition not possible
logAllowError("allow_all_except", "cannot use 'allow_all_except' when in state " + getState().toString());
return false;
case ALLOW_ALL_EXCEPT:
if(classNames.size() == disallowedClassNames.size() && classNames.containsAll(disallowedClassNames)){
logRedundantAllowBefore("allow_all_except");
return true;
}
logAllowError("allow_all_except", "already allowed at least one of [" + String.join(", ", disallowedClassNames) + "]");
return false;
case ALLOW: //note that any name in the list will now be disallowed
//if any of the given class names matches any of the current class names in the list
//this transition is not allowed
if(containsAnyOf(disallowedClassNames)){
logAllowError("allow_all_except", "already allowed at least one of [" + String.join(", ", disallowedClassNames) + "]");
return false;
}
//clear because the classes in the list will now be disallowed and therefore the ones already in the list need to be removed to fit the new logical view
classNames.clear();
logRedundantAllowBefore("allow_all_except");
default:
packageState = ALLOW_ALL_EXCEPT;
classNames.addAll(disallowedClassNames);
return true;
}
}
private String getInfo() {
return "'" + getPackageName() + "' state=" + getState().toString();
}
}
| 34.6625
| 155
| 0.731338
|
e1f2e2f11aa67ff6a6ed41d9edfd1161c27f5fc6
| 2,310
|
package com.noah.solutions.system.service.impl;
import com.noah.solutions.system.repository.RoleAuthoritiesRepository;
import com.noah.solutions.system.repository.RoleRepository;
import com.noah.solutions.common.exception.CustormException;
import com.noah.solutions.common.utils.BeanUtils;
import com.noah.solutions.system.entity.Role;
import com.noah.solutions.system.service.RoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
@Service
public class RoleServiceImpl implements RoleService {
// @Autowired
// private RoleMapper roleMapper;
// @Autowired
// private RoleAuthoritiesMapper roleAuthoritiesMapper;
@Resource
private RoleRepository roleRepository;
@Resource
private RoleAuthoritiesRepository roleAuthoritiesRepository;
@Override
public List<Role> getByUserId(Integer userId) {
return roleRepository.selectByUserId(userId);
}
@Override
public List<Role> getAllRole(Integer isDelete) {
return roleRepository.findAllByIsDelete(isDelete);
}
@Override
public boolean add(Role role) {
role.setCreateTime(new Date());
role.setIsDelete(0);
roleRepository.save(role);
return true;
}
@Override
public boolean update(Role role) {
Role oldRole = roleRepository.getOne(role.getRoleId());
BeanUtils.copyNotNullProperties(role,oldRole);
roleRepository.save(oldRole);
return true;
}
@Transactional(rollbackFor = Exception.class)
@Override
public boolean updateState(Integer roleId, int isDelete) {
if (isDelete != 0 && isDelete != 1) {
throw new CustormException("isDelete值需要在[0,1]中",1);
}
Role oldRole = roleRepository.getOne(roleId);
oldRole.setIsDelete(isDelete);
roleRepository.save(oldRole);
roleAuthoritiesRepository.deleteAllByRoleId( roleId);
return true;
}
@Override
public Role getById(Integer roleId) {
return roleRepository.getOne(roleId);
}
@Override
public boolean delete(Integer roleId) {
roleRepository.deleteById(roleId);
return true;
}
}
| 27.831325
| 70
| 0.71039
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.