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
|
|---|---|---|---|---|---|
4281f749d270a1057dfb2deb72d27e6a52b32ebc
| 385
|
/**
* Clasa unui nod ce tine informatia de tip string.
*
* @author Alin
*
*/
public class StringNode extends Node {
private String info;
public StringNode() {
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
/*
* @see Node#accept(Visitor)
*/
@Override
public void accept(Visitor v) {
v.visit(this);
}
}
| 12.833333
| 51
| 0.633766
|
7bee447aa16e6cfe0acef9babc088c2420474844
| 546
|
package main.java.com.octaviocega.effectivejavaexcercises.chapter1.item2builder;
public class Main {
public static void main(String[] args){
// Notice that customer can not be created using a constructor
//Customer customer = new Customer();
// Customer object will always have its required fields set
Customer customer = new Customer.Builder("John", "Doe", 27)
.cellphone("9999999999").build();
// Important to notice that once created, customer fields can not be changed.
}
}
| 34.125
| 85
| 0.677656
|
7fb52fcccd8e25da161be056cd73151f0a0ceed6
| 6,688
|
/**
* 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.hadoop.yarn.server.resourcemanager.scheduler.capacity.conf;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.server.records.Version;
import org.apache.hadoop.yarn.server.resourcemanager.RMContext;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateVersionIncompatibleException;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacityScheduler;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
* YarnConfigurationStore exposes the methods needed for retrieving and
* persisting {@link CapacityScheduler} configuration via key-value
* using write-ahead logging. When configuration mutation is requested, caller
* should first log it with {@code logMutation}, which persists this pending
* mutation. This mutation is merged to the persisted configuration only after
* {@code confirmMutation} is called.
*
* On startup/recovery, caller should call {@code retrieve} to get all
* confirmed mutations, then get pending mutations which were not confirmed via
* {@code getPendingMutations}, and replay/confirm them via
* {@code confirmMutation} as in the normal case.
*/
public abstract class YarnConfigurationStore {
public static final Log LOG =
LogFactory.getLog(YarnConfigurationStore.class);
/**
* LogMutation encapsulates the fields needed for configuration mutation
* audit logging and recovery.
*/
static class LogMutation implements Serializable {
private Map<String, String> updates;
private String user;
/**
* Create log mutation.
* @param updates key-value configuration updates
* @param user user who requested configuration change
*/
LogMutation(Map<String, String> updates, String user) {
this.updates = updates;
this.user = user;
}
/**
* Get key-value configuration updates.
* @return map of configuration updates
*/
public Map<String, String> getUpdates() {
return updates;
}
/**
* Get user who requested configuration change.
* @return user who requested configuration change
*/
public String getUser() {
return user;
}
}
/**
* Initialize the configuration store, with schedConf as the initial
* scheduler configuration. If a persisted store already exists, use the
* scheduler configuration stored there, and ignore schedConf.
* @param conf configuration to initialize store with
* @param schedConf Initial key-value scheduler configuration to persist.
* @param rmContext RMContext for this configuration store
* @throws IOException if initialization fails
*/
public abstract void initialize(Configuration conf, Configuration schedConf,
RMContext rmContext) throws Exception;
/**
* Closes the configuration store, releasing any required resources.
* @throws IOException on failure to close
*/
public void close() throws IOException {}
/**
* Logs the configuration change to backing store.
* @param logMutation configuration change to be persisted in write ahead log
* @throws IOException if logging fails
*/
public abstract void logMutation(LogMutation logMutation) throws Exception;
/**
* Should be called after {@code logMutation}. Gets the pending mutation
* last logged by {@code logMutation} and marks the mutation as persisted (no
* longer pending). If isValid is true, merge the mutation with the persisted
* configuration.
* @param isValid if true, update persisted configuration with pending
* mutation.
* @throws Exception if mutation confirmation fails
*/
public abstract void confirmMutation(boolean isValid) throws Exception;
/**
* Retrieve the persisted configuration.
* @return configuration as key-value
*/
public abstract Configuration retrieve();
/**
* Get a list of confirmed configuration mutations starting from a given id.
* @param fromId id from which to start getting mutations, inclusive
* @return list of configuration mutations
*/
public abstract List<LogMutation> getConfirmedConfHistory(long fromId);
/**
* Get schema version of persisted conf store, for detecting compatibility
* issues when changing conf store schema.
* @return Schema version currently used by the persisted configuration store.
* @throws Exception On version fetch failure
*/
protected abstract Version getConfStoreVersion() throws Exception;
/**
* Persist the hard-coded schema version to the conf store.
* @throws Exception On storage failure
*/
protected abstract void storeVersion() throws Exception;
/**
* Get the hard-coded schema version, for comparison against the schema
* version currently persisted.
* @return Current hard-coded schema version
*/
protected abstract Version getCurrentVersion();
public void checkVersion() throws Exception {
// TODO this was taken from RMStateStore. Should probably refactor
Version loadedVersion = getConfStoreVersion();
LOG.info("Loaded configuration store version info " + loadedVersion);
if (loadedVersion != null && loadedVersion.equals(getCurrentVersion())) {
return;
}
// if there is no version info, treat it as CURRENT_VERSION_INFO;
if (loadedVersion == null) {
loadedVersion = getCurrentVersion();
}
if (loadedVersion.isCompatibleTo(getCurrentVersion())) {
LOG.info("Storing configuration store version info "
+ getCurrentVersion());
storeVersion();
} else {
throw new RMStateVersionIncompatibleException(
"Expecting configuration store version " + getCurrentVersion()
+ ", but loading version " + loadedVersion);
}
}
}
| 37.363128
| 98
| 0.732955
|
624b8dde0706cbe348fdbd5daab2f984d1e272bf
| 4,775
|
package enderpower.backups;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import enderpower.blocks.tileentity.TileEntityMetalEnchanter;
import enderpower.items.EnderpowerItems;
import enderpower.main.R;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.potion.PotionEffect;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.IIcon;
import net.minecraft.world.World;
public class MetalEnchanter extends BlockContainer{
@SideOnly(Side.CLIENT)
public IIcon top;
@SideOnly(Side.CLIENT)
public IIcon bottom;
public ItemStack input_iron = new ItemStack(Items.iron_ingot, 0);
public ItemStack input_powder;
public ItemStack output;
public MetalEnchanter() {
super(Material.rock);
setHardness(5);
setResistance(10);
}
@Override
public TileEntity createNewTileEntity(World world, int i) {
return new TileEntityMetalEnchanter();
}
@SideOnly(Side.CLIENT)
public IIcon getIcon(int side, int metadata)
{
if(side == 0){
return bottom;
}
if(side == 1){
return top;
}
else {
return blockIcon;
}
}
@SideOnly(Side.CLIENT)
public void registerBlockIcons(IIconRegister icon)
{
this.blockIcon = icon.registerIcon(R.T + "metalenchanter_side");
this.bottom = icon.registerIcon(R.T + "metalenchanter_bottom");
this.top = icon.registerIcon(R.T + "metalenchanter_top");
}
public boolean onBlockActivated(World world, int x, int y,int z, EntityPlayer player, int side, float f1, float f2, float f3){
if(player.getCurrentEquippedItem() != null && !world.isRemote){
if(player.getCurrentEquippedItem().getItem() == Items.iron_ingot && input_iron.stackSize < 64){
player.getCurrentEquippedItem().stackSize -= 1;
input_iron.stackSize += 1;
}
if(input_powder != null){
if(input_powder.stackSize < 64){
if(player.getCurrentEquippedItem().getItem() == input_powder.getItem()){
player.getCurrentEquippedItem().stackSize -= 1;
input_powder.stackSize += 1;
}
}
}
else if(input_powder == null){
System.out.println("input_powder = null.");
if(isValidItem(player)){
input_powder = new ItemStack(player.getCurrentEquippedItem().getItem(), 1);
player.getCurrentEquippedItem().stackSize -= 1;
}
}
}
if(!world.isRemote){
System.out.println(input_iron);
}
return true;
}
public void onBlockClicked(World world, int x, int y, int z, EntityPlayer player){
if(player.getCurrentEquippedItem() != null && !world.isRemote){
if(input_iron.stackSize > 0 && player.getCurrentEquippedItem().getItem() == Items.iron_ingot){
player.inventory.addItemStackToInventory(new ItemStack(Items.iron_ingot));
input_iron.stackSize -= 1;
}
if(input_powder != null){
if(input_powder.getItem() == player.getCurrentEquippedItem().getItem() && input_powder.stackSize > 0 && player.getCurrentEquippedItem().stackSize < 64){
input_powder.stackSize -= 1;
player.getCurrentEquippedItem().stackSize += 1;
}
}
}
else if(player.getCurrentEquippedItem() == null && !world.isRemote){
if(input_iron.stackSize > 0){
player.inventory.addItemStackToInventory(new ItemStack(Items.iron_ingot, input_iron.stackSize));
input_iron.stackSize = 0;
}
if(input_powder != null){
player.inventory.addItemStackToInventory(input_powder);
input_powder = null;
}
}
}
public void breakBlock(World world, int x, int y, int z, Block block, int metadata)
{
if(input_iron.stackSize > 0){
world.spawnEntityInWorld(new EntityItem(world, x, y, z, input_iron));
}
if(input_powder != null){
world.spawnEntityInWorld(new EntityItem(world, x, y, z, input_powder));
}
if(output != null){
world.spawnEntityInWorld(new EntityItem(world, x, y, z, output));
}
super.breakBlock(world, x, y, z, block, metadata);
}
public boolean isValidItem(EntityPlayer player){
if(player.getCurrentEquippedItem().getItem() == EnderpowerItems.cursedpowder || player.getCurrentEquippedItem().getItem() == EnderpowerItems.poison || player.getCurrentEquippedItem().getItem() == EnderpowerItems.witherpowder){
return true;
}
else {
return false;
}
}
}
| 35.37037
| 231
| 0.686911
|
972a5ffb2eb016fdd1d438c7526bdf92b7e0dc39
| 1,271
|
package iskallia.itraders.util;
import javax.annotation.Nonnull;
import iskallia.itraders.Traders;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
/**
* Class: NBTHelper
* Created by HellFirePvP
* Date: 16.10.2019 / 20:09
*/
public class NBTHelper {
@Nonnull
public static NBTTagCompound getPersistentData(ItemStack item) {
return getPersistentData(getData(item));
}
@Nonnull
public static NBTTagCompound getPersistentData(NBTTagCompound base) {
NBTTagCompound compound;
if (hasPersistentData(base)) {
compound = base.getCompoundTag(Traders.MOD_ID);
} else {
compound = new NBTTagCompound();
base.setTag(Traders.MOD_ID, compound);
}
return compound;
}
public static boolean hasPersistentData(NBTTagCompound base) {
return base.hasKey(Traders.MOD_ID) && base.getTag(Traders.MOD_ID) instanceof NBTTagCompound;
}
@Nonnull
public static NBTTagCompound getData(ItemStack stack) {
NBTTagCompound compound = stack.getTagCompound();
if (compound == null) {
compound = new NBTTagCompound();
stack.setTagCompound(compound);
}
return compound;
}
}
| 26.479167
| 100
| 0.667191
|
760b31604855af4d1b70f810cdd5440656850ebc
| 2,622
|
package homework.part1.percolation;
/**
* http://coursera.cs.princeton.edu/algs4/assignments/percolation.html
*/
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.StdStats;
public class PercolationStats {
private final double meanVal;
private final double stddevVal;
private final double halfInterval;
// perform trials independent experiments on an n-by-n grid
public PercolationStats(int n, int trials) {
if (n <= 0 || trials <= 0)
throw new IllegalArgumentException();
double[] samples = new double[trials];
final int times = trials;
for (int i = 0; i < trials; i++) {
Percolation percolation = new Percolation(n);
while (!percolation.percolates()) {
int openSite = StdRandom.uniform(n * n) + 1;
int row, col;
if (openSite % n == 0) {
row = openSite / n;
col = n;
} else {
row = openSite / n + 1;
col = openSite % n;
}
percolation.open(row, col);
}
double num = n * n;
samples[i] = percolation.numberOfOpenSites() / num;
}
meanVal = StdStats.mean(samples);
stddevVal = StdStats.stddev(samples);
halfInterval = 1.96 * stddevVal / java.lang.Math.sqrt(times);
}
// sample mean of percolation threshold
public double mean() {
return meanVal;
}
// sample standard deviation of percolation threshold
public double stddev() {
return stddevVal;
}
// low endpoint of 95% confidence interval
public double confidenceLo() {
return meanVal - halfInterval;
}
// high endpoint of 95% confidence interval
public double confidenceHi() {
return meanVal + halfInterval;
}
// test client (described below)
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int times = Integer.parseInt(args[1]);
// int n=4, times=5;
PercolationStats percolationStats = new PercolationStats(n, times);
double mean = percolationStats.mean();
double stddev = percolationStats.stddev();
double conLo = percolationStats.confidenceLo();
double conHi = percolationStats.confidenceHi();
StdOut.printf("mean%20s= %f\n", " ", mean);
StdOut.printf("stddev%18s= %f\n", " ", stddev);
StdOut.printf("95%% confidence interval = [%f, %f]", conLo, conHi);
}
}
| 33.615385
| 75
| 0.584287
|
277790784f731034c8369fde004b0cabeb193fa6
| 2,665
|
/*
* (C) Copyright 2020 Radix DLT Ltd
*
* Radix DLT Ltd 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 com.radixdlt.integration.distributed.simulation.tests.consensus;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
import com.radixdlt.integration.distributed.simulation.NetworkLatencies;
import com.radixdlt.integration.distributed.simulation.NetworkOrdering;
import com.radixdlt.integration.distributed.simulation.SimulationTest.TestResults;
import com.radixdlt.integration.distributed.simulation.SimulationTest;
import com.radixdlt.integration.distributed.simulation.SimulationTest.Builder;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
public class FPlusOneOutOfBoundsTest {
private final int latency = 50;
private final int synchronousTimeout = 8 * latency;
private final int outOfBoundsLatency = synchronousTimeout;
private final Builder bftTestBuilder = SimulationTest.builder()
.pacemakerTimeout(synchronousTimeout)
.checkConsensusSafety("safety")
.checkConsensusLiveness("liveness", synchronousTimeout, TimeUnit.MILLISECONDS);
/**
* Tests a configuration of 0 out of 3 nodes out of synchrony bounds
*/
@Test
public void given_0_out_of_3_nodes_out_of_synchrony_bounds() {
SimulationTest test = bftTestBuilder
.numNodes(3)
.networkModules(
NetworkOrdering.inOrder(),
NetworkLatencies.fixed(latency)
)
.build();
TestResults results = test.run();
assertThat(results.getCheckResults())
.allSatisfy((name, error) -> assertThat(error).isNotPresent());
}
/**
* Tests a configuration of 1 out of 3 nodes out of synchrony bounds
*/
@Test
public void given_1_out_of_3_nodes_out_of_synchrony_bounds() {
SimulationTest test = bftTestBuilder
.numNodes(3)
.networkModules(
NetworkOrdering.inOrder(),
NetworkLatencies.oneOutOfBounds(latency, outOfBoundsLatency)
)
.build();
TestResults results = test.run();
assertThat(results.getCheckResults())
.hasEntrySatisfying("liveness", error -> assertThat(error).isPresent())
.hasEntrySatisfying("safety", error -> assertThat(error).isNotPresent());
}
}
| 34.61039
| 82
| 0.771857
|
a792ca20be11d72a50befb3095738cc5d551f02d
| 7,399
|
package github.tornaco.xposedmoduletest.ui.activity.ag;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Fragment;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.SwitchPreference;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import github.tornaco.permission.requester.RequiresPermission;
import github.tornaco.permission.requester.RuntimePermissions;
import github.tornaco.xposedmoduletest.R;
import github.tornaco.xposedmoduletest.provider.AppKey;
import github.tornaco.xposedmoduletest.provider.AppSettings;
import github.tornaco.xposedmoduletest.provider.LockStorage;
import github.tornaco.xposedmoduletest.provider.XKey;
import github.tornaco.xposedmoduletest.ui.activity.PhotoViewerActivity;
import github.tornaco.xposedmoduletest.xposed.app.XAppLockManager;
import github.tornaco.xposedmoduletest.xposed.bean.VerifySettings;
/**
* Created by guohao4 on 2017/11/2.
* Email: Tornaco@163.com
*/
@RuntimePermissions
public class SecureGuardSettings extends GuardSettingsActivity {
private static final String CATEGORY_KEY_LOCK = "category_lock";
@Override
protected Fragment onCreateSettingsFragment() {
return new SecureSettingsFragment();
}
public static class SecureSettingsFragment extends GuardSettingsActivity.SettingsFragment {
private VerifySettings verifySettings = null;
private void onRequestSetupSecurePassport() {
if (getActivity() == null) return;
final int[] selection = {0};
String[] choice = new String[LockStorage.LockMethod.values().length];
for (int i = 0; i < choice.length; i++) {
choice[i] = getString(LockStorage.LockMethod.values()[i].getNameRes());
}
LockStorage.LockMethod currentLockMethod = LockStorage.getLockMethod(getActivity());
new AlertDialog.Builder(getActivity())
.setSingleChoiceItems(choice, currentLockMethod.ordinal(), (dialog, which) -> {
selection[0] = which;
if (selection[0] == 0) {
PinSetupActivity.start(getActivity());
} else {
PatternSetupActivity.start(getActivity());
}
dialog.dismiss();
})
.show();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.ag_secure);
}
private void bindAndUpdatePrefs() {
Preference lockSettingsPref = findPreference("verify_method");
LockStorage.LockMethod currentLockMethod = LockStorage.getLockMethod(getActivity());
lockSettingsPref.setSummary(currentLockMethod.getNameRes());
lockSettingsPref.setOnPreferenceClickListener(preference -> {
onRequestSetupSecurePassport();
return true;
});
SwitchPreference workaround = (SwitchPreference) findPreference(AppKey.APPLOCK_WORKAROUND);
workaround.setChecked(AppSettings.isAppLockWorkaroundEnabled(getActivity()));
if (XAppLockManager.get().isServiceAvailable()) {
verifySettings = XAppLockManager.get().getVerifySettings();
if (verifySettings == null) verifySettings = new VerifySettings();
final boolean hidePatternEnabled = LockStorage.isShowPatternEnabled(getActivity());
SwitchPreference hidePattern = (SwitchPreference) findPreference(LockStorage.KEY_HIDE_PATTERN);
hidePattern.setChecked(hidePatternEnabled);
hidePattern.setEnabled(currentLockMethod == LockStorage.LockMethod.Pattern);
hidePattern.setOnPreferenceChangeListener((preference, newValue) -> {
boolean v = (boolean) newValue;
LockStorage.setHidePatternEnabled(getActivity(), v);
return true;
});
final boolean verifyOnHome = verifySettings.isVerifyOnAppSwitch();
SwitchPreference homePref = (SwitchPreference) findPreference("ver_on_home");
homePref.setChecked(verifyOnHome);
homePref.setOnPreferenceChangeListener((preference, newValue) -> {
boolean v = (boolean) newValue;
verifySettings.setVerifyOnAppSwitch(v);
XAppLockManager.get().setVerifySettings(verifySettings);
return true;
});
boolean verifyOnScreen = verifySettings != null && verifySettings.isVerifyOnScreenOff();
SwitchPreference screenPref = (SwitchPreference) findPreference("ver_on_screenoff");
screenPref.setChecked(verifyOnScreen);
screenPref.setOnPreferenceChangeListener((preference, newValue) -> {
boolean v = (boolean) newValue;
verifySettings.setVerifyOnScreenOff(v);
XAppLockManager.get().setVerifySettings(verifySettings);
return true;
});
boolean verifyOnTaskRemoved = verifySettings != null && verifySettings.isVerifyOnTaskRemoved();
SwitchPreference taskPref = (SwitchPreference) findPreference("ver_on_task_removed");
taskPref.setChecked(verifyOnTaskRemoved);
taskPref.setOnPreferenceChangeListener((preference, newValue) -> {
boolean v = (boolean) newValue;
verifySettings.setVerifyOnTaskRemoved(v);
XAppLockManager.get().setVerifySettings(verifySettings);
return true;
});
SwitchPreference photoPref = (SwitchPreference) findPreference(XKey.TAKE_PHOTO_ENABLED);
if (photoPref != null) {
photoPref.setOnPreferenceChangeListener((preference, newValue) -> {
SecureGuardSettingsPermissionRequester
.requestCameraPermissionChecked((SecureGuardSettings) getActivity());
return true;
});
}
findPreference("key_view_photos")
.setOnPreferenceClickListener(preference -> {
startActivity(new Intent(getActivity(), PhotoViewerActivity.class));
return true;
});
} else {
getPreferenceScreen().setEnabled(false);
}
}
@Override
public void onResume() {
super.onResume();
bindAndUpdatePrefs();
}
}
@RequiresPermission({Manifest.permission.CAMERA})
void requestCameraPermission() {
}
@TargetApi(Build.VERSION_CODES.M)
@RequiresPermission({Manifest.permission.USE_FINGERPRINT})
void requestFPPermission() {
}
}
| 43.017442
| 112
| 0.614272
|
725d4f23cf607bae57f652972d033f2468f2b213
| 3,996
|
package com.mauriciotogneri.mandy.input;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import com.mauriciotogneri.mandy.screen.Camera;
public class Input implements OnTouchListener
{
private final Object touchLock = new Object();
private final TouchEvent[] touchEvents = new TouchEvent[TOUCH_EVENT_SIZE];
private final Camera camera;
private static final int TOUCH_EVENT_SIZE = 5;
public Input(View view, Camera camera)
{
this.camera = camera;
for (int i = 0; i < TOUCH_EVENT_SIZE; i++)
{
this.touchEvents[i] = new TouchEvent();
}
view.setOnTouchListener(this);
}
@Override
public boolean onTouch(View view, MotionEvent event)
{
int pointerIndex = event.getActionIndex();
int pointerId = event.getPointerId(pointerIndex);
if (pointerId < TOUCH_EVENT_SIZE)
{
switch (event.getActionMasked())
{
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_POINTER_DOWN:
case MotionEvent.ACTION_MOVE:
updateTouchEvent(pointerId, event.getX(pointerIndex), event.getY(pointerIndex));
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
case MotionEvent.ACTION_CANCEL:
updateTouchEvent(pointerId);
break;
}
}
return true;
}
private void updateTouchEvent(int index, float x, float y)
{
synchronized (touchLock)
{
TouchEvent touchEvent = touchEvents[index];
touchEvent.pressed = true;
touchEvent.x = (int) ((x * camera.width) / camera.screenWidth);
touchEvent.y = (int) (((camera.screenHeight - y) * camera.height) / camera.screenHeight);
}
}
private void updateTouchEvent(int index)
{
synchronized (touchLock)
{
TouchEvent touchEvent = touchEvents[index];
touchEvent.pressed = false;
}
}
public boolean isPressed()
{
synchronized (touchLock)
{
for (int i = 0; i < TOUCH_EVENT_SIZE; i++)
{
if (touchEvents[i].isPressed())
{
return true;
}
}
}
return false;
}
public boolean isPressed(float left, float right, float bottom, float top)
{
synchronized (touchLock)
{
for (int i = 0; i < TOUCH_EVENT_SIZE; i++)
{
if (touchEvents[i].isPressed(left, right, bottom, top))
{
return true;
}
}
}
return false;
}
public boolean isPressedHorizontal(float left, float right)
{
synchronized (touchLock)
{
for (int i = 0; i < TOUCH_EVENT_SIZE; i++)
{
if (touchEvents[i].isPressedHorizontal(left, right))
{
return true;
}
}
}
return false;
}
public boolean isPressedRightHalf()
{
return isPressedHorizontal(camera.width / 2, camera.width);
}
public boolean isPressedLeftHalf()
{
return isPressedHorizontal(0, camera.width / 2);
}
public boolean isPressedVertical(float bottom, float top)
{
synchronized (touchLock)
{
for (int i = 0; i < TOUCH_EVENT_SIZE; i++)
{
if (touchEvents[i].isPressedVertical(bottom, top))
{
return true;
}
}
}
return false;
}
}
| 26.818792
| 102
| 0.511512
|
a1f7e835fea8658d6f9053ca8ed67ba8c7c16c6b
| 4,302
|
package com.librato.metrics.client;
import java.util.*;
public class TaggedMeasure extends AbstractMeasure {
private double sum;
private long count;
private double min;
private double max;
private List<Tag> tags = new LinkedList<>();
public TaggedMeasure(GaugeMeasure measure) {
super(measure);
if (measure.getValue() != null) {
this.sum = measure.getValue();
this.count = 1;
this.min = sum;
this.max = sum;
} else {
this.sum = measure.getSum();
this.count = measure.getCount();
this.min = measure.getMin();
this.max = measure.getMax();
}
}
public TaggedMeasure(String name, double value, Tag tag, Tag...tags) {
this(name, value, 1, value, value, tag, tags);
}
public TaggedMeasure(String name, double sum, long count, double min, double max, Tag tag, Tag...tags) {
super(name);
this.sum = sum;
this.count = count;
this.min = min;
this.max = max;
addTag(tag);
addTags(tags);
}
public void addTags(Tag... tags) {
for (Tag tag : tags) {
addTag(tag);
}
}
public void addTag(Tag tag) {
String tagName = sanitizeTagName(tag.name);
String tagValue = sanitizeTagValue(tag.value);
this.tags.add(new Tag(tagName, tagValue));
}
private String sanitizeTagValue(String value) {
value = Sanitizer.TAG_VALUE_SANITIZER.apply(value);
return trimToSize(value, 255);
}
private String sanitizeTagName(String name) {
name = Sanitizer.TAG_NAME_SANITIZER.apply(name);
return trimToSize(name, 64);
}
private String trimToSize(String string, int size) {
if (string == null || string.length() <= size) {
return string;
}
return string.substring(0, size);
}
@Override
public Map<String, Object> toMap() {
Map<String, Object> map = super.toMap();
Maps.putIfNotNull(map, "time", epoch);
map.put("sum", sum);
map.put("count", count);
map.put("min", min);
map.put("max", max);
if (!tags.isEmpty()) {
map.put("tags", Tags.toMap(tags));
}
return map;
}
@Override
public boolean isTagged() {
return true;
}
@Override
public boolean isGauge() {
return true;
}
public TaggedMeasure setPeriod(int period) {
this.period = period;
return this;
}
public TaggedMeasure setMetricAttributes(Map<String, Object> attributes) {
this.metricAttributes = attributes;
return this;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("{");
sb.append("name=").append(name);
sb.append(", epoch=").append(epoch);
sb.append(", tags=").append(tags);
sb.append(", sum=").append(sum);
sb.append(", count=").append(count);
sb.append(", min=").append(min);
sb.append(", max=").append(max);
sb.append('}');
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
TaggedMeasure that = (TaggedMeasure) o;
if (Double.compare(that.sum, sum) != 0) return false;
if (count != that.count) return false;
if (Double.compare(that.min, min) != 0) return false;
if (Double.compare(that.max, max) != 0) return false;
return tags != null ? tags.equals(that.tags) : that.tags == null;
}
@Override
public int hashCode() {
int result;
long temp;
temp = Double.doubleToLongBits(sum);
result = (int) (temp ^ (temp >>> 32));
result = 31 * result + (int) (count ^ (count >>> 32));
temp = Double.doubleToLongBits(min);
result = 31 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(max);
result = 31 * result + (int) (temp ^ (temp >>> 32));
result = 31 * result + (tags != null ? tags.hashCode() : 0);
return result;
}
}
| 28.872483
| 108
| 0.555788
|
ddb54cd32adb6447f2a2bd9ea8c30fc768fbc7c7
| 1,364
|
package android.aspen.leidos.com.sri.data;
//
// This file was generated by the BinaryNotes compiler.
// See http://bnotes.sourceforge.net
// Any modifications to this file will be lost upon recompilation of the source ASN.1.
//
import org.bn.*;
import org.bn.annotations.*;
import org.bn.annotations.constraints.*;
import org.bn.coders.*;
import org.bn.types.*;
@ASN1PreparedElement
@ASN1BoxedType ( name = "Longitude" )
public class Longitude implements IASN1PreparedElement {
@ASN1Integer( name = "Longitude" )
@ASN1ValueRangeConstraint (
min = -1800000000L,
max = 1800000001L
)
private Integer value;
public Longitude() {
}
public Longitude(Integer value) {
this.value = value;
}
public void setValue(Integer value) {
this.value = value;
}
public Integer getValue() {
return this.value;
}
public void initWithDefaults() {
}
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(Longitude.class);
public IASN1PreparedElementData getPreparedData() {
return preparedData;
}
}
| 23.517241
| 130
| 0.583578
|
1665ab1b4a34d9aada4289584f282660ff54ac38
| 3,448
|
package ldbc.snb.datagen.entities.dynamic.person;
import org.apache.hadoop.io.Writable;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.Serializable;
import java.util.Objects;
public final class PersonSummary implements Writable, Serializable {
private long accountId;
private long creationDate;
private long deletionDate;
private int browserId;
private int country;
private IP ipAddress;
private boolean isLargePoster;
public PersonSummary() {
ipAddress = new IP();
}
public PersonSummary(Person p) {
accountId = p.getAccountId();
creationDate = p.getCreationDate();
deletionDate = p.getDeletionDate();
browserId = p.getBrowserId();
country = p.getCountryId();
ipAddress = new IP(p.getIpAddress());
isLargePoster = p.getIsLargePoster();
}
public PersonSummary(PersonSummary p) {
accountId = p.getAccountId();
creationDate = p.getCreationDate();
deletionDate = p.getDeletionDate();
browserId = p.getBrowserId();
country = p.getCountryId();
ipAddress = new IP(p.getIpAddress());
isLargePoster = p.getIsLargePoster();
}
public void copy(PersonSummary p) {
accountId = p.getAccountId();
creationDate = p.getCreationDate();
deletionDate = p.getDeletionDate();
browserId = p.getBrowserId();
country = p.getCountryId();
ipAddress = new IP(p.getIpAddress());
isLargePoster = p.getIsLargePoster();
}
public long getAccountId() {
return accountId;
}
public long getCreationDate() {
return creationDate;
}
public long getDeletionDate() {
return deletionDate;
}
public int getBrowserId() {
return browserId;
}
public int getCountryId() {
return country;
}
public IP getIpAddress() {
return ipAddress;
}
public boolean getIsLargePoster() {
return isLargePoster;
}
public void readFields(DataInput arg0) throws IOException {
accountId = arg0.readLong();
creationDate = arg0.readLong();
deletionDate = arg0.readLong();
browserId = arg0.readInt();
country = arg0.readInt();
ipAddress.readFields(arg0);
isLargePoster = arg0.readBoolean();
}
public void write(DataOutput arg0) throws IOException {
arg0.writeLong(accountId);
arg0.writeLong(creationDate);
arg0.writeLong(deletionDate);
arg0.writeInt(browserId);
arg0.writeInt(country);
ipAddress.write(arg0);
arg0.writeBoolean(isLargePoster);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PersonSummary that = (PersonSummary) o;
return accountId == that.accountId &&
creationDate == that.creationDate &&
deletionDate == that.deletionDate &&
browserId == that.browserId &&
country == that.country &&
isLargePoster == that.isLargePoster &&
Objects.equals(ipAddress, that.ipAddress);
}
@Override
public int hashCode() {
return Objects.hash(accountId, creationDate, deletionDate, browserId, country, ipAddress, isLargePoster);
}
}
| 28.495868
| 113
| 0.62326
|
8668a65a019430db804e7dcfc89fb3f8363b120b
| 322
|
/**
*
*/
package org.javarosa.core.services.locale;
/**
* @author ctsims
*
*/
public class LocaleTextException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = -2852964609244258589L;
public LocaleTextException(String message) {
super(message);
}
}
| 16.1
| 71
| 0.649068
|
09838831f84b1ca042b9e0570d85f4f71e05a85b
| 456
|
//package org.funtime.client;
//
//import org.junit.Test;
//import org.junit.runner.RunWith;
//import org.springframework.boot.test.SpringApplicationConfiguration;
//import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
//
//@RunWith(SpringJUnit4ClassRunner.class)
//@SpringApplicationConfiguration(classes = DatasourceApplication.class)
//public class DatasourceApplicationTests {
//
// @Test
// public void contextLoads() {
// }
//
//}
| 26.823529
| 73
| 0.778509
|
d3ecec01931c6e5abe356ec203289ee33a557ec8
| 1,883
|
package org.infinispan.client.hotrod.impl.protocol;
import java.io.IOException;
import java.io.OutputStream;
import org.infinispan.client.hotrod.impl.transport.Transport;
import org.infinispan.client.hotrod.impl.transport.tcp.TcpTransport;
import net.jcip.annotations.NotThreadSafe;
/**
* Implements an {@link OutputStream} around a {@link Transport}.
* The transport is marked as <b>busy</b> so that it won't be released automatically
*
* @author Tristan Tarrant
* @since 9.0
*/
@NotThreadSafe
class TransportOutputStream extends OutputStream {
private final Transport transport;
private final Runnable afterClose;
private byte buf[];
private int count;
public TransportOutputStream(Transport transport, Runnable afterClose) {
this.transport = transport;
buf = new byte[TcpTransport.SOCKET_STREAM_BUFFER];
this.afterClose = afterClose;
}
private void internalFlush() throws IOException {
if (count > 0) {
transport.writeArray(buf, 0, count);
transport.flush();
count = 0;
}
}
public void write(int b) throws IOException {
if (count >= buf.length) {
internalFlush();
}
buf[count++] = (byte)b;
}
public void write(byte b[], int off, int len) throws IOException {
if (len >= buf.length) {
internalFlush();
transport.writeArray(b, off, len);
return;
}
if (len > buf.length - count) {
internalFlush();
}
System.arraycopy(b, off, buf, count, len);
count += len;
}
public void flush() throws IOException {
internalFlush();
}
@Override
public void close() throws IOException {
flush();
transport.writeVInt(0); // 0-sized buffer to indicate end of data
transport.flush();
if (afterClose != null) {
afterClose.run();
}
}
}
| 25.794521
| 84
| 0.643654
|
bc69d5e03c8672d3d8cad1159abadb786433ac6e
| 13,597
|
package org.uniprot.api.aa.controller;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.emptyOrNullString;
import static org.hamcrest.Matchers.emptyString;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.uniprot.api.aa.AARestApplication;
import org.uniprot.api.aa.repository.UniRuleQueryRepository;
import org.uniprot.api.common.repository.search.SolrQueryRepository;
import org.uniprot.api.rest.controller.AbstractGetByIdControllerIT;
import org.uniprot.api.rest.controller.param.ContentTypeParam;
import org.uniprot.api.rest.controller.param.GetIdContentTypeParam;
import org.uniprot.api.rest.controller.param.GetIdParameter;
import org.uniprot.api.rest.controller.param.resolver.AbstractGetIdContentTypeParamResolver;
import org.uniprot.api.rest.controller.param.resolver.AbstractGetIdParameterResolver;
import org.uniprot.api.rest.output.UniProtMediaType;
import org.uniprot.api.rest.validation.error.ErrorHandlerConfig;
import org.uniprot.core.unirule.UniRuleEntry;
import org.uniprot.core.unirule.UniRuleId;
import org.uniprot.core.unirule.impl.UniRuleEntryBuilder;
import org.uniprot.core.unirule.impl.UniRuleEntryBuilderTest;
import org.uniprot.core.unirule.impl.UniRuleIdBuilder;
import org.uniprot.store.indexer.DataStoreManager;
import org.uniprot.store.indexer.uniprot.mockers.TaxonomyRepoMocker;
import org.uniprot.store.indexer.unirule.UniRuleDocumentConverter;
import org.uniprot.store.search.SolrCollection;
import org.uniprot.store.search.document.unirule.UniRuleDocument;
/**
* @author sahmad
* @created 11/11/2020
*/
@ContextConfiguration(
classes = {DataStoreTestConfig.class, AARestApplication.class, ErrorHandlerConfig.class})
@ActiveProfiles(profiles = "offline")
@WebMvcTest(UniRuleController.class)
@ExtendWith(
value = {
SpringExtension.class,
UniRuleGetIdControllerIT.UniRuleGetIdParameterResolver.class,
UniRuleGetIdControllerIT.UniRuleGetIdContentTypeParamResolver.class
})
public class UniRuleGetIdControllerIT extends AbstractGetByIdControllerIT {
private static final String UNIRULE_ID = "UR000100241";
@Autowired private UniRuleQueryRepository repository;
@Override
protected DataStoreManager.StoreType getStoreType() {
return DataStoreManager.StoreType.UNIRULE;
}
@Override
protected SolrCollection getSolrCollection() {
return SolrCollection.unirule;
}
@Override
protected SolrQueryRepository getRepository() {
return repository;
}
@Override
protected void saveEntry() {
UniRuleEntry entry = create();
UniRuleDocumentConverter converter =
new UniRuleDocumentConverter(TaxonomyRepoMocker.getTaxonomyRepo());
UniRuleDocument document = converter.convertToDocument(entry);
getStoreManager().saveDocs(getStoreType(), document);
}
private UniRuleEntry create() {
UniRuleId uniRuleId = new UniRuleIdBuilder(UNIRULE_ID).build();
UniRuleEntry uniRule = UniRuleEntryBuilderTest.createObject();
return UniRuleEntryBuilder.from(uniRule).uniRuleId(uniRuleId).build();
}
@Override
protected String getIdRequestPath() {
return "/unirule/{uniruleid}";
}
static class UniRuleGetIdParameterResolver extends AbstractGetIdParameterResolver {
@Override
public GetIdParameter validIdParameter() {
return GetIdParameter.builder()
.id(UNIRULE_ID)
.resultMatcher(jsonPath("$.uniRuleId", is(UNIRULE_ID)))
.resultMatcher(jsonPath("$.information", notNullValue()))
.resultMatcher(jsonPath("$.mainRule", notNullValue()))
.resultMatcher(jsonPath("$.otherRules", notNullValue()))
.resultMatcher(jsonPath("$.samFeatureSets", notNullValue()))
.resultMatcher(jsonPath("$.positionFeatureSets", notNullValue()))
.resultMatcher(jsonPath("$.statistics", notNullValue()))
.resultMatcher(jsonPath("$.statistics.reviewedProteinCount", notNullValue()))
.resultMatcher(jsonPath("$.statistics.unreviewedProteinCount", notNullValue()))
.resultMatcher(jsonPath("$.createdDate", notNullValue()))
.resultMatcher(jsonPath("$.modifiedDate", notNullValue()))
.build();
}
@Override
public GetIdParameter invalidIdParameter() {
return GetIdParameter.builder()
.id("INVALID")
.resultMatcher(jsonPath("$.url", not(emptyOrNullString())))
.resultMatcher(
jsonPath(
"$.messages.*",
contains(
"The UniRule id value has invalid format. It should match the regular expression 'UR[0-9]{9}'")))
.build();
}
@Override
public GetIdParameter nonExistentIdParameter() {
return GetIdParameter.builder()
.id("UR123456789")
.resultMatcher(jsonPath("$.url", not(emptyOrNullString())))
.resultMatcher(jsonPath("$.messages.*", contains("Resource not found")))
.build();
}
@Override
public GetIdParameter withFilterFieldsParameter() {
return GetIdParameter.builder()
.id(UNIRULE_ID)
.fields("template_entries")
.resultMatcher(jsonPath("$.uniRuleId", is(UNIRULE_ID)))
.resultMatcher(jsonPath("$.information", notNullValue()))
.resultMatcher(jsonPath("$.mainRule").doesNotExist())
.resultMatcher(jsonPath("$.otherRules").doesNotExist())
.resultMatcher(jsonPath("$.samFeatureSets").doesNotExist())
.resultMatcher(jsonPath("$.positionFeatureSets").doesNotExist())
.resultMatcher(jsonPath("$.statistics").doesNotExist())
.resultMatcher(jsonPath("$.createdDate").doesNotExist())
.resultMatcher(jsonPath("$.modifiedDate").doesNotExist())
.build();
}
@Override
public GetIdParameter withInvalidFilterParameter() {
return GetIdParameter.builder()
.id(UNIRULE_ID)
.fields("invalid")
.resultMatcher(jsonPath("$.url", not(emptyOrNullString())))
.resultMatcher(
jsonPath(
"$.messages.*",
contains("Invalid fields parameter value 'invalid'")))
.build();
}
}
static class UniRuleGetIdContentTypeParamResolver
extends AbstractGetIdContentTypeParamResolver {
@Override
public GetIdContentTypeParam idSuccessContentTypesParam() {
return GetIdContentTypeParam.builder()
.id(UNIRULE_ID)
.contentTypeParam(
ContentTypeParam.builder()
.contentType(MediaType.APPLICATION_JSON)
.resultMatcher(jsonPath("$.uniRuleId", is(UNIRULE_ID)))
.resultMatcher(jsonPath("$.information", notNullValue()))
.resultMatcher(jsonPath("$.mainRule", notNullValue()))
.resultMatcher(
jsonPath(
"$.otherRules",
Matchers.hasSize(greaterThan(0))))
.resultMatcher(
jsonPath(
"$.samFeatureSets",
Matchers.hasSize(greaterThan(0))))
.resultMatcher(
jsonPath(
"$.positionFeatureSets",
Matchers.hasSize(greaterThan(0))))
.resultMatcher(jsonPath("$.statistics", notNullValue()))
.resultMatcher(
jsonPath(
"$.statistics.reviewedProteinCount",
notNullValue()))
.resultMatcher(
jsonPath(
"$.statistics.unreviewedProteinCount",
notNullValue()))
.resultMatcher(jsonPath("$.createdDate", notNullValue()))
.resultMatcher(jsonPath("$.modifiedDate", notNullValue()))
.build())
.contentTypeParam(
ContentTypeParam.builder()
.contentType(UniProtMediaType.LIST_MEDIA_TYPE)
.resultMatcher(content().string(containsString(UNIRULE_ID)))
.build())
.contentTypeParam(
ContentTypeParam.builder()
.contentType(UniProtMediaType.TSV_MEDIA_TYPE)
.resultMatcher(
content()
.string(
containsString(
"UniRule ID\tTemplate Entries")))
.resultMatcher(
content()
.string(
containsString(
"UR000100241\taccession-")))
.build())
.contentTypeParam(
ContentTypeParam.builder()
.contentType(UniProtMediaType.XLS_MEDIA_TYPE)
.resultMatcher(
content().contentType(UniProtMediaType.XLS_MEDIA_TYPE))
.build())
.build();
}
@Override
public GetIdContentTypeParam idBadRequestContentTypesParam() {
return GetIdContentTypeParam.builder()
.id("INVALID")
.contentTypeParam(
ContentTypeParam.builder()
.contentType(MediaType.APPLICATION_JSON)
.resultMatcher(jsonPath("$.url", not(emptyOrNullString())))
.resultMatcher(
jsonPath(
"$.messages.*",
contains(
"The UniRule id value has invalid format. It should match the regular expression 'UR[0-9]{9}'")))
.build())
.contentTypeParam(
ContentTypeParam.builder()
.contentType(UniProtMediaType.LIST_MEDIA_TYPE)
.resultMatcher(content().string(emptyString()))
.build())
.contentTypeParam(
ContentTypeParam.builder()
.contentType(UniProtMediaType.XLS_MEDIA_TYPE)
.resultMatcher(content().string(emptyString()))
.build())
.contentTypeParam(
ContentTypeParam.builder()
.contentType(UniProtMediaType.TSV_MEDIA_TYPE)
.resultMatcher(content().string(emptyString()))
.build())
.build();
}
}
}
| 50.546468
| 157
| 0.528867
|
85ce3809a974d54c9d6a12b77eaa8e37d57dd94a
| 2,255
|
/*
* 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.iceberg.avro;
import java.util.List;
import java.util.function.Supplier;
import org.apache.avro.Schema;
import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
/**
* Lazily evaluates the schema to see if any field ids are set.
* Returns true when a first field is found which has field id set
*/
class HasIds extends AvroCustomOrderSchemaVisitor<Boolean, Boolean> {
@Override
public Boolean record(Schema record, List<String> names, Iterable<Boolean> fields) {
return Iterables.any(fields, Boolean.TRUE::equals);
}
@Override
public Boolean field(Schema.Field field, Supplier<Boolean> fieldResult) {
// see if field id is present, if not, try to find it in the sub tree
return AvroSchemaUtil.hasFieldId(field) || fieldResult.get();
}
@Override
public Boolean map(Schema map, Supplier<Boolean> value) {
return AvroSchemaUtil.hasProperty(map, AvroSchemaUtil.KEY_ID_PROP) ||
AvroSchemaUtil.hasProperty(map, AvroSchemaUtil.VALUE_ID_PROP) ||
value.get();
}
@Override
public Boolean array(Schema array, Supplier<Boolean> element) {
return AvroSchemaUtil.hasProperty(array, AvroSchemaUtil.ELEMENT_ID_PROP) || element.get();
}
@Override
public Boolean union(Schema union, Iterable<Boolean> options) {
return Iterables.any(options, Boolean.TRUE::equals);
}
@Override
public Boolean primitive(Schema primitive) {
return false;
}
}
| 34.692308
| 94
| 0.743237
|
58d9da35d5a38aa5608fb8d8b84f5d59a8a635b9
| 404
|
package io.github.qf6101.rmisdk.base;
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
* User: qfeng
* Date: 15-11-11 下午5:00
* Usage: RMI绑定接口
*/
public interface IBound extends Remote {
/**
* 检测心跳
*
* @param clientMessage 客户端发上来的检测信息
* @return 服务端返回心跳信息
* @throws RemoteException
*/
String heartBeat(String clientMessage) throws RemoteException;
}
| 19.238095
| 66
| 0.673267
|
d870debf53806541928cd397452fcbaf45317a30
| 7,390
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See License.txt in the repository root.
package com.microsoft.tfs.client.common.framework.resources.command;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import com.microsoft.tfs.client.common.framework.command.CancellableCommand;
import com.microsoft.tfs.client.common.framework.command.CommandCancellableListener;
import com.microsoft.tfs.client.common.framework.command.CommandWrapper;
import com.microsoft.tfs.client.common.framework.command.ICancellableCommand;
import com.microsoft.tfs.client.common.framework.command.ICommand;
import com.microsoft.tfs.client.common.framework.command.exception.ICommandExceptionHandler;
import com.microsoft.tfs.util.Check;
/**
* <p>
* {@link WorkspaceCommand} wraps any {@link ICommand}, giving the wrapped
* {@link ICommand} workspace batched semantics. Using {@link WorkspaceCommand}
* is the equivalent, for example, of calling the
* {@link IWorkspace#run(org.eclipse.core.resources.IWorkspaceRunnable, ISchedulingRule, int, IProgressMonitor)}
* method inside a command.
* </p>
*
* <p>
* A {@link WorkspaceCommand} is associated with an {@link ISchedulingRule},
* which will be passed to the
* {@link IWorkspace#run(org.eclipse.core.resources.IWorkspaceRunnable, ISchedulingRule, int, IProgressMonitor)}
* method. The default scheduling rule is the workspace root - this should be
* overridden when appropriate.
* </p>
*
* <p>
* See the {@link #run(IProgressMonitor)} command's Javadoc for an important
* warning.
* </p>
*/
public class WorkspaceCommand extends CancellableCommand implements CommandWrapper {
private final static Log log = LogFactory.getLog(WorkspaceCommand.class);
/**
* The wrapped {@link ICommand} (never <code>null</code>).
*/
private final ICommand wrappedCommand;
/**
* The {@link ISchedulingRule} rule to use when running the command (never
* <code>null</code>).
*/
private final ISchedulingRule schedulingRule;
/**
* Creates a new {@link WorkspaceCommand} that wraps the specified
* {@link ICommand} and uses the default scheduling rule.
*
* @param wrappedCommand
* an {@link ICommand} to wrap (must not be <code>null</code>)
*/
public WorkspaceCommand(final ICommand wrappedCommand) {
this(wrappedCommand, null);
}
/**
* Creates a new {@link WorkspaceCommand} that wraps the specified
* {@link ICommand} and uses the specified {@link ISchedulingRule}.
*
* @param wrappedCommand
* an {@link ICommand} to wrap (must not be <code>null</code>)
* @param schedulingRule
* an {@link ISchedulingRule} rule to use, or <code>null</code> to
* use the default scheduling rule (the workspace root)
*/
public WorkspaceCommand(final ICommand wrappedCommand, ISchedulingRule schedulingRule) {
Check.notNull(wrappedCommand, "wrappedCommand"); //$NON-NLS-1$
this.wrappedCommand = wrappedCommand;
if (schedulingRule == null) {
schedulingRule = ResourcesPlugin.getWorkspace().getRoot();
}
this.schedulingRule = schedulingRule;
}
/*
* (non-Javadoc)
*
* @see com.microsoft.tfs.client.common.shared.command.ICommand#
* getExceptionHandler ()
*/
@Override
public ICommandExceptionHandler getExceptionHandler() {
return wrappedCommand.getExceptionHandler();
}
/*
* (non-Javadoc)
*
* @see com.microsoft.tfs.client.common.shared.command.ICommand#getName()
*/
@Override
public String getName() {
return wrappedCommand.getName();
}
/*
* (non-Javadoc)
*
* @see com.microsoft.tfs.client.common.shared.command.ICommand#
* getErrorDescription ()
*/
@Override
public String getErrorDescription() {
return wrappedCommand.getErrorDescription();
}
/*
* (non-Javadoc)
*
* @see com.microsoft.tfs.client.common.framework.command.ICommand#
* getLoggingDescription()
*/
@Override
public String getLoggingDescription() {
return wrappedCommand.getLoggingDescription();
}
/*
* (non-Javadoc)
*
* @see
* com.microsoft.tfs.client.common.shared.command.ICommand#isCancelable()
*/
@Override
public boolean isCancellable() {
return wrappedCommand.isCancellable();
}
/**
* {@inheritDoc}
*/
@Override
public void addCancellableChangedListener(final CommandCancellableListener listener) {
if (wrappedCommand instanceof ICancellableCommand) {
((ICancellableCommand) wrappedCommand).addCancellableChangedListener(listener);
}
}
/**
* {@inheritDoc}
*/
@Override
public void removeCancellableChangedListener(final CommandCancellableListener listener) {
if (wrappedCommand instanceof ICancellableCommand) {
((ICancellableCommand) wrappedCommand).removeCancellableChangedListener(listener);
}
}
/*
* (non-Javadoc)
*
* @see com.microsoft.tfs.client.common.framework.command.CommandWrapper#
* getWrappedCommand()
*/
@Override
public ICommand getWrappedCommand() {
return wrappedCommand;
}
/**
* {@inheritDoc}
*
* <b>Aesthetic Warning</b>
* <p>
* This method calls
* {@link IWorkspace#run(org.eclipse.core.resources.IWorkspaceRunnable, ISchedulingRule, int, IProgressMonitor)}
* , which opens a new sub-monitor on the given {@link IProgressMonitor}, in
* order to display its "Refreshing /some/path" messages. Howerver, the
* {@link IWorkspace} implementation always forces the
* {@link SubProgressMonitor#PREPEND_MAIN_LABEL_TO_SUBTASK} style bit, which
* prepends any existing label the task monitor had (like "Downloading") to
* the refresh sublabel, resulting in something ugly like
* "Downloading Refreshing /some/path" appearing in the dialog. You might
* want to make sure the existing label ends in a colon or some other
* separator so it looks good in the dialog, or pass in a
* {@link NullProgressMonitor} if you just don't care to see refreshing
* status.
* <p>
*/
@Override
public IStatus run(final IProgressMonitor progressMonitor) throws Exception {
final WorkspaceRunnableCommandAdapter adapter = new WorkspaceRunnableCommandAdapter(wrappedCommand);
try {
ResourcesPlugin.getWorkspace().run(adapter, schedulingRule, IResource.NONE, progressMonitor);
} catch (final CoreException e) {
log.error("Workspace command error", e.getStatus().getException()); //$NON-NLS-1$
throw (Exception) e.getStatus().getException();
}
return adapter.getStatus();
}
}
| 34.694836
| 116
| 0.690798
|
e49d17555c8c33dca8e07c86266cb187020fee91
| 1,917
|
/*******************************************************************************
* Copyright 2021 Dell 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.alvarium;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import com.alvarium.contracts.AnnotationType;
import com.alvarium.hash.HashType;
import com.alvarium.sign.SignType;
import com.alvarium.streams.MqttConfig;
import org.junit.Test;
public class SdkInfoTest {
private final String testJson;
private final AnnotationType[] annotators = {AnnotationType.TLS,AnnotationType.MOCK};
public SdkInfoTest() throws IOException {
String path = "./src/test/java/com/alvarium/sdk-info.json";
this.testJson = Files.readString(Paths.get(path), StandardCharsets.US_ASCII);
}
@Test
public void fromJsonShouldReturnSdkInfo(){
SdkInfo sdkInfo = SdkInfo.fromJson(this.testJson);
assertEquals(true, Arrays.equals(this.annotators, sdkInfo.getAnnotators()));
assertEquals(HashType.SHA256Hash, sdkInfo.getHash().getType());
assertEquals(SignType.Ed25519, sdkInfo.getSignature().getPrivateKey().getType());
assertEquals(MqttConfig.class, sdkInfo.getStream().getConfig().getClass());
}
}
| 37.588235
| 100
| 0.701617
|
7032fcced126e170f8398a680586d0db5a8390ca
| 3,622
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.react;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.modules.core.ExceptionsManagerModule;
import com.facebook.react.modules.core.JSTimersExecution;
import com.facebook.react.modules.core.RCTNativeAppEventEmitter;
import com.facebook.react.modules.core.Timing;
import com.facebook.react.modules.debug.AnimationsDebugModule;
import com.facebook.react.modules.debug.SourceCodeModule;
import com.facebook.react.modules.systeminfo.AndroidInfoModule;
import com.facebook.react.uimanager.AppRegistry;
import com.facebook.react.uimanager.ReactNative;
import com.facebook.react.uimanager.UIManagerModule;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.uimanager.debug.DebugComponentOwnershipModule;
import com.facebook.react.uimanager.events.RCTEventEmitter;
/**
* Package defining core framework modules (e.g. UIManager). It should be used for modules that
* require special integration with other framework parts (e.g. with the list of packages to load
* view managers from).
*/
/* package */ class CoreModulesPackage implements ReactPackage {
private final ReactInstanceManager mReactInstanceManager;
private final DefaultHardwareBackBtnHandler mHardwareBackBtnHandler;
CoreModulesPackage(
ReactInstanceManager reactInstanceManager,
DefaultHardwareBackBtnHandler hardwareBackBtnHandler) {
mReactInstanceManager = reactInstanceManager;
mHardwareBackBtnHandler = hardwareBackBtnHandler;
}
@Override
public List<NativeModule> createNativeModules(
ReactApplicationContext catalystApplicationContext) {
return Arrays.<NativeModule>asList(
new AnimationsDebugModule(
catalystApplicationContext,
mReactInstanceManager.getDevSupportManager().getDevSettings()),
new AndroidInfoModule(),
new DeviceEventManagerModule(catalystApplicationContext, mHardwareBackBtnHandler),
new ExceptionsManagerModule(mReactInstanceManager.getDevSupportManager()),
new Timing(catalystApplicationContext),
new SourceCodeModule(
mReactInstanceManager.getSourceUrl(),
mReactInstanceManager.getDevSupportManager().getSourceMapUrl()),
new UIManagerModule(
catalystApplicationContext,
mReactInstanceManager.createAllViewManagers(catalystApplicationContext)),
new DebugComponentOwnershipModule(catalystApplicationContext));
}
@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Arrays.asList(
DeviceEventManagerModule.RCTDeviceEventEmitter.class,
JSTimersExecution.class,
RCTEventEmitter.class,
RCTNativeAppEventEmitter.class,
AppRegistry.class,
ReactNative.class,
DebugComponentOwnershipModule.RCTDebugComponentOwnership.class);
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return new ArrayList<>(0);
}
}
| 40.696629
| 97
| 0.786582
|
3c087bb11176171a4d6b07ff18594c5b0b77c354
| 5,628
|
/*--------------------------------------------------------------------------
* Copyright 2004 Taro L. Saito
*
* 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.
*--------------------------------------------------------------------------*/
//--------------------------------------
// XerialJ
//
// PageBlock.java
// Since: 2005/07/21 1:38:52
//
// $URL$
// $Author$
//--------------------------------------
package org.xerial.mlpress;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.xerial.core.XerialException;
import org.xerial.db.VariableLengthInteger;
enum PageType { EMPTY, ARCHIVE_HEADER, DICTIONARY, TREE_STRUCTURE, TEXT, PAGE_INDEX };
class PageHeader
{
PageType pageType;
public PageHeader(PageType pageType)
{
this.pageType = pageType;
}
void load(PageBlock pb)
{
pageType = PageType.values()[pb.read()];
}
void store(PageBlock pb)
{
pb.write(pageType.ordinal());
}
int size()
{
return 1; // PageType
}
}
class Entry
{
// EntryHeader
private VariableLengthInteger entry_id = null;
private VariableLengthInteger size = null; // size of the entry data
private VariableLengthInteger nextPageID = null; // 0: the last of the chain. otherwise: next pageID
// EntryData
private byte[] _entryData = null;
public Entry(ByteArrayInputStream pageBuffer) throws XerialException, IOException
{
entry_id = VariableLengthInteger.readFrom(pageBuffer);
size = VariableLengthInteger.readFrom(pageBuffer);
nextPageID = VariableLengthInteger.readFrom(pageBuffer);
_entryData = new byte[size.intValue()];
pageBuffer.read(_entryData);
}
public Entry(int id, int size, int nextPageID, byte[] data)
{
this.entry_id = new VariableLengthInteger(id);
this.size = new VariableLengthInteger(size);
this.nextPageID = new VariableLengthInteger(nextPageID);
_entryData = data;
}
public VariableLengthInteger getId()
{
return entry_id;
}
public void setId(VariableLengthInteger id)
{
this.entry_id = id;
}
public VariableLengthInteger getNextPageID()
{
return nextPageID;
}
public void setNextPageID(VariableLengthInteger nextPageID)
{
this.nextPageID = nextPageID;
}
public VariableLengthInteger getSize()
{
return size;
}
public void setSize(VariableLengthInteger size)
{
this.size = size;
}
}
/**
* PageBlock represents a unit to read/write a disk page.
*
*
* | PageHeader | PageBody ............................|
* | page type | page type specific info | entries ... |
*
* @author leo
*
*/
class PageBlock
{
private PageHeader _pageHeader = null;
private long _nextPageID = 0;
private byte[] _buf = null;
private int _pageSize;
private int _cursor = 0;
public PageBlock(int pageSize, PageType pageType)
{
_buf = new byte[pageSize];
_pageSize = pageSize;
_pageHeader = new PageHeader(pageType);
_pageHeader.store(this);
}
public PageHeader getPageHeader()
{
return _pageHeader;
}
public ByteArrayInputStream getPageBodyInputStream()
{
int pageHeaderSize = _pageHeader.size();
return new ByteArrayInputStream(_buf, pageHeaderSize, _pageSize - pageHeaderSize );
}
public byte[] read(int length)
{
byte[] readData = new byte[length];
for(int i=0; i<length; i++)
{
readData[i] = _buf[_cursor++];
}
return readData;
}
/**
* Reads the next byte of data
* @return
*/
public int read()
{
return _buf[_cursor++];
}
/**
* write a long value as 4 bytes data in the big-endian format
* @param value
*/
public void write4Bytes(long value)
{
long mask = 0xFF000000;
for(int i=0; i<4; i++)
{
int v = (int) ( (value & mask) >> (24 - 8 * i));
write(v);
mask >>= 8;
}
}
public void write(VariableLengthInteger v)
{
write(v.getByte());
}
public void write(int b)
{
_buf[_cursor++] = (byte) b;
}
public void write(byte[] data)
{
for(int i=0; i<data.length; i++)
_buf[_cursor++] = data[i];
}
public void moveCursor(int cursorPosition)
{
assert cursorPosition < _pageSize;
_cursor =- cursorPosition;
}
}
class TreeStructurePageBlock extends PageBlock
{
public TreeStructurePageBlock(int pageSize)
{
super(pageSize, PageType.TREE_STRUCTURE);
}
}
| 24.469565
| 108
| 0.552594
|
2c41f6cb9292107e5330321089a63bd731e79dcd
| 3,200
|
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextArea;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class GasDetector {
private JFrame frame;
/**
* Launch the application.
*/
/*public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GasDetector window = new GasDetector();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GasDetector() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame("GAS DETECTOR");
frame.getContentPane().setBackground(new Color(250, 250, 210));
frame.getContentPane().setFont(new Font("Tahoma", Font.BOLD, 14));
frame.setBounds(100, 100, 841, 734);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
frame.setVisible(true);
JLabel lblDescription = new JLabel("Description :");
lblDescription.setFont(new Font("Tahoma", Font.BOLD, 14));
lblDescription.setBounds(10, 10, 200, 29);
frame.getContentPane().add(lblDescription);
JTextArea txtrAGasDetector = new JTextArea();
txtrAGasDetector.setEditable(false);
txtrAGasDetector.setFont(new Font("Monospaced", Font.PLAIN, 15));
txtrAGasDetector.setText("A Gas Detector is a device that detects the pressure of gasses in an area, \r\noften as part of safety system. This type eqipment is used to detect a gas leak \r\nor other emissions and can interface with a control system, so a process can be\r\nautomatically shut down. A gas detector can sound an alarm to operations in the \r\narea where there is a leak, giving them an opportunity to leave. This type of \r\ndevice is important because there are many gases that can be harmful to organic \r\nlife, such as humans or animals.");
txtrAGasDetector.setBounds(10, 50, 719, 151);
frame.getContentPane().add(txtrAGasDetector);
JLabel lblImage = new JLabel("Image :");
lblImage.setFont(new Font("Tahoma", Font.BOLD, 14));
lblImage.setBounds(10, 212, 200, 36);
frame.getContentPane().add(lblImage);
JLabel lblGraph = new JLabel("Graph :");
lblGraph.setFont(new Font("Tahoma", Font.BOLD, 14));
lblGraph.setBounds(326, 212, 200, 36);
frame.getContentPane().add(lblGraph);
JLabel label = new JLabel("");
label.setIcon(new ImageIcon("D:\\gasDetector.jpg"));
label.setBounds(10, 259, 236, 187);
frame.getContentPane().add(label);
JButton btnPrevious = new JButton("Previous");
btnPrevious.setBounds(10, 661, 112, 23);
frame.getContentPane().add(btnPrevious);
JLabel label_1 = new JLabel("");
label_1.setIcon(new ImageIcon("D:\\GraphGasdetector.jpg"));
label_1.setBounds(320, 248, 409, 319);
frame.getContentPane().add(label_1);
btnPrevious.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent m){
frame.setVisible(false);
Sensors s = new Sensors();
}
});
}
}
| 32
| 559
| 0.713438
|
58f5bae6e87ebd6b5146b9e7f434e2635d2bb6ce
| 2,762
|
package day14.MapversionDoudizhu;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
/**
* @author lbf
* @date 2020/7/30 10:34
*/
public class Poker3 {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
ArrayList<String> numbers = new ArrayList<>();
ArrayList<String> colors = new ArrayList<>();
Collections.addAll(numbers,"2","3","4","5","6","7","8","9","10","J","Q","K","A");
Collections.addAll(colors,"♥","♠","♣","♦");
int count = 1;
map.put(count++,"大王");
map.put(count++,"小王");
for (String number:numbers){
for (String color: colors){
map.put(count++,color+number);
}
}
System.out.println(map);
//洗牌
ArrayList<Integer> shufflePoker = new ArrayList<>();
shufflePoker.addAll(map.keySet());
// System.out.println(shufflePoker);
Collections.shuffle(shufflePoker);
System.out.println(shufflePoker);
//发牌
ArrayList<Integer> one = new ArrayList<>();
ArrayList<Integer> two = new ArrayList<>();
ArrayList<Integer> three = new ArrayList<>();
ArrayList<Integer> di = new ArrayList<>();
for (int i = 0; i < shufflePoker.size(); i++) {
if (i >= 51){
di.add(shufflePoker.get(i));
}
else {
if (i % 3 == 0){
one.add(shufflePoker.get(i));
}else if (i % 3 == 1){
two.add(shufflePoker.get(i));
}else {
three.add(shufflePoker.get(i));
}
}
}
System.out.println(one);
System.out.println(two);
System.out.println(three);
System.out.println(di);
Collections.sort(one);
Collections.sort(two);
Collections.sort(three);
Collections.sort(di);
//
ArrayList<String> player1 = new ArrayList<>();
ArrayList<String> player2 = new ArrayList<>();
ArrayList<String> player3 = new ArrayList<>();
ArrayList<String> dipai = new ArrayList<>();
for (Integer integer:one){
player1.add(map.get(integer));
}
for (Integer integer:two){
player2.add(map.get(integer));
}
for (Integer integer:three){
player3.add(map.get(integer));
}
for (Integer integer:di){
dipai.add(map.get(integer));
}
System.out.println(player1);
System.out.println(player2);
System.out.println(player3);
System.out.println(dipai);
}
}
| 30.351648
| 89
| 0.522085
|
973272d2cd41c9b02a0c9800b26942ffb1a48d89
| 930
|
package com.peterwanghao.samples.springboot.autoconfiguration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.test.context.junit4.SpringRunner;
import com.peterwanghao.samples.springboot.autoconfiguration.example.AutoconfigurationApplication;
/**
* @ClassName: SpringContextLiveTest
* @Description:TODO(这里用一句话描述这个类的作用)
* @author: wanghao
* @date: 2019年2月21日 下午4:58:23
* @version V1.0
*
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = AutoconfigurationApplication.class)
@EnableJpaRepositories(basePackages = { "com.peterwanghao.samples.springboot.autoconfiguration.example" })
public class SpringContextLiveTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}
| 33.214286
| 107
| 0.783871
|
5bafe18b00c5c97a0c66a5b85655e100726b12ab
| 976
|
package io.github.noeppi_noeppi.mods.minemention.mentions;
import io.github.noeppi_noeppi.mods.minemention.api.SpecialMention;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.chat.TranslatableComponent;
import net.minecraft.server.level.ServerPlayer;
import java.util.function.Predicate;
public class OnePlayerMention implements SpecialMention {
public final String name;
public OnePlayerMention(String name) {
this.name = name;
}
@Override
public MutableComponent description() {
return new TranslatableComponent("minemention.one_player", this.name);
}
@Override
public Predicate<ServerPlayer> selectPlayers(ServerPlayer sender) {
return player -> this.name.equals(player.getGameProfile().getName());
}
@Override
public boolean available(ServerPlayer sender) {
return sender.getLevel().getServer().getPlayerList().getPlayerByName(this.name) != null;
}
}
| 29.575758
| 96
| 0.746926
|
174753e0d19721cc5c6421864b40b22d420fa4a3
| 40,381
|
// Copyright (c) 2016, the R8 project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
package com.android.tools.r8.utils;
import com.android.tools.r8.ClassFileConsumer;
import com.android.tools.r8.DataResourceConsumer;
import com.android.tools.r8.DataResourceProvider;
import com.android.tools.r8.DexFilePerClassFileConsumer;
import com.android.tools.r8.DexIndexedConsumer;
import com.android.tools.r8.ProgramConsumer;
import com.android.tools.r8.StringConsumer;
import com.android.tools.r8.Version;
import com.android.tools.r8.dex.Marker;
import com.android.tools.r8.errors.CompilationError;
import com.android.tools.r8.errors.InvalidDebugInfoException;
import com.android.tools.r8.experimental.graphinfo.GraphConsumer;
import com.android.tools.r8.graph.DexEncodedMethod;
import com.android.tools.r8.graph.DexItemFactory;
import com.android.tools.r8.graph.DexMethod;
import com.android.tools.r8.graph.DexType;
import com.android.tools.r8.ir.code.IRCode;
import com.android.tools.r8.ir.optimize.Inliner;
import com.android.tools.r8.naming.InterfaceMethodNameMinifier;
import com.android.tools.r8.origin.Origin;
import com.android.tools.r8.shaking.ProguardConfiguration;
import com.android.tools.r8.shaking.ProguardConfigurationRule;
import com.android.tools.r8.utils.IROrdering.IdentityIROrdering;
import com.android.tools.r8.utils.IROrdering.NondeterministicIROrdering;
import com.google.common.base.Equivalence.Wrapper;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Consumer;
import org.objectweb.asm.Opcodes;
public class InternalOptions {
// Set to true to run compilation in a single thread and without randomly shuffling the input.
// This makes life easier when running R8 in a debugger.
public static final boolean DETERMINISTIC_DEBUGGING = false;
public enum LineNumberOptimization {
OFF,
ON
}
public static final int ASM_VERSION = Opcodes.ASM7;
public final DexItemFactory itemFactory;
public ProguardConfiguration getProguardConfiguration() {
return proguardConfiguration;
}
private final ProguardConfiguration proguardConfiguration;
public final Reporter reporter;
// TODO(zerny): Make this private-final once we have full program-consumer support.
public ProgramConsumer programConsumer = null;
public final List<DataResourceProvider> dataResourceProviders = new ArrayList<>();
public DataResourceConsumer dataResourceConsumer;
// Constructor for testing and/or other utilities.
public InternalOptions() {
reporter = new Reporter();
itemFactory = new DexItemFactory();
proguardConfiguration = null;
enableTreeShaking = false;
enableMinification = false;
}
// Constructor for D8.
public InternalOptions(DexItemFactory factory, Reporter reporter) {
assert reporter != null;
assert factory != null;
this.reporter = reporter;
itemFactory = factory;
proguardConfiguration = null;
enableTreeShaking = false;
enableMinification = false;
disableGlobalOptimizations();
}
// Constructor for R8.
public InternalOptions(ProguardConfiguration proguardConfiguration, Reporter reporter) {
assert reporter != null;
assert proguardConfiguration != null;
this.reporter = reporter;
this.proguardConfiguration = proguardConfiguration;
itemFactory = proguardConfiguration.getDexItemFactory();
enableTreeShaking = proguardConfiguration.isShrinking();
enableMinification = proguardConfiguration.isObfuscating();
// -dontoptimize disables optimizations by flipping related flags.
if (!proguardConfiguration.isOptimizing()) {
disableAllOptimizations();
}
}
void disableAllOptimizations() {
disableGlobalOptimizations();
enableNonNullTracking = false;
}
public void disableGlobalOptimizations() {
enableArgumentRemoval = false;
enableDynamicTypeOptimization = false;
enableInlining = false;
enableClassInlining = false;
enableClassStaticizer = false;
enableDevirtualization = false;
enableLambdaMerging = false;
enableHorizontalClassMerging = false;
enableVerticalClassMerging = false;
enableUninstantiatedTypeOptimization = false;
enableUnusedArgumentRemoval = false;
outline.enabled = false;
enableSwitchMapRemoval = false;
enableValuePropagation = false;
enableSideEffectAnalysis = false;
}
public boolean printTimes = System.getProperty("com.android.tools.r8.printtimes") != null;
// Flag to toggle if DEX code objects should pass-through without IR processing.
public boolean passthroughDexCode = false;
// Optimization-related flags. These should conform to -dontoptimize and disableAllOptimizations.
public boolean enableDynamicTypeOptimization = true;
public boolean enableHorizontalClassMerging = true;
public boolean enableVerticalClassMerging = true;
public boolean enableArgumentRemoval = true;
public boolean enableUnusedArgumentRemoval = true;
public boolean enableDevirtualization = true;
public boolean enableNonNullTracking = true;
public boolean enableInlining =
!Version.isDev() || System.getProperty("com.android.tools.r8.disableinlining") == null;
// TODO(b/130202534): Enable this once code size regressions are fixed.
public boolean enableInliningOfInvokesWithNullableReceivers = false;
public boolean enableClassInlining = true;
public boolean enableClassStaticizer = true;
public boolean enableInitializedClassesAnalysis = true;
public boolean enableSideEffectAnalysis = true;
public boolean enableServiceLoaderRewriting = true;
// TODO(b/120138731): Enable this when it is worthwhile, e.g., combined with Class#forName.
public boolean enableNameReflectionOptimization = false;
public int classInliningInstructionLimit = 50;
// This defines the limit of instructions in the inlinee
public int inliningInstructionLimit = 3;
// This defines how many instructions of inlinees we can inlinee overall.
public int inliningInstructionAllowance = 1500;
// Maximum number of control flow resolution blocks that setup the register state before
// the actual catch handler allowed when inlining. Threshold found empirically by testing on
// GMS Core.
public int inliningControlFlowResolutionBlocksThreshold = 15;
public boolean enableSwitchMapRemoval = true;
public final OutlineOptions outline = new OutlineOptions();
public boolean enableValuePropagation = true;
public boolean enableUninstantiatedTypeOptimization = true;
// Number of threads to use while processing the dex files.
public int numberOfThreads = DETERMINISTIC_DEBUGGING ? 1 : ThreadUtils.NOT_SPECIFIED;
// Print smali disassembly.
public boolean useSmaliSyntax = false;
// Verbose output.
public boolean verbose = false;
// Silencing output.
public boolean quiet = false;
// Throw exception if there is a warning about invalid debug info.
public boolean invalidDebugInfoFatal = false;
// When dexsplitting we ignore main dex classes missing in the application. These will be
// fused together by play store when shipped for pre-L devices.
public boolean ignoreMainDexMissingClasses = false;
// Hidden marker for classes.dex
private boolean hasMarker = false;
private Marker marker;
public boolean hasMarker() {
return hasMarker;
}
public void setMarker(Marker marker) {
this.hasMarker = true;
this.marker = marker;
}
public Marker getMarker() {
assert hasMarker();
return marker;
}
public boolean hasConsumer() {
return programConsumer != null;
}
public InternalOutputMode getInternalOutputMode() {
assert hasConsumer();
if (isGeneratingDexIndexed()) {
return InternalOutputMode.DexIndexed;
} else if (isGeneratingDexFilePerClassFile()) {
return InternalOutputMode.DexFilePerClassFile;
} else if (isGeneratingClassFiles()) {
return InternalOutputMode.ClassFile;
}
throw new UnsupportedOperationException("Cannot find internal output mode.");
}
public boolean isGeneratingDex() {
return isGeneratingDexIndexed() || isGeneratingDexFilePerClassFile();
}
public boolean isGeneratingDexIndexed() {
return programConsumer instanceof DexIndexedConsumer;
}
public boolean isGeneratingDexFilePerClassFile() {
return programConsumer instanceof DexFilePerClassFileConsumer;
}
public boolean isGeneratingClassFiles() {
return programConsumer instanceof ClassFileConsumer;
}
public DexIndexedConsumer getDexIndexedConsumer() {
return (DexIndexedConsumer) programConsumer;
}
public DexFilePerClassFileConsumer getDexFilePerClassFileConsumer() {
return (DexFilePerClassFileConsumer) programConsumer;
}
public ClassFileConsumer getClassFileConsumer() {
return (ClassFileConsumer) programConsumer;
}
public void signalFinishedToConsumers() {
if (programConsumer != null) {
programConsumer.finished(reporter);
if (dataResourceConsumer != null) {
dataResourceConsumer.finished(reporter);
}
}
}
public Set<String> extensiveLoggingFilter = getExtensiveLoggingFilter();
public Set<String> extensiveFieldMinifierLoggingFilter = getExtensiveFieldMinifierLoggingFilter();
public Set<String> extensiveInterfaceMethodMinifierLoggingFilter =
getExtensiveInterfaceMethodMinifierLoggingFilter();
public List<String> methodsFilter = ImmutableList.of();
public int minApiLevel = AndroidApiLevel.getDefault().getLevel();
// Skipping min_api check and compiling an intermediate result intended for later merging.
// Intermediate builds also emits or update synthesized classes mapping.
public boolean intermediate = false;
public List<String> logArgumentsFilter = ImmutableList.of();
// Flag to turn on/off lambda class merging in R8.
public boolean enableLambdaMerging = false;
// Flag to turn on/off desugaring in D8/R8.
public boolean enableDesugaring = true;
// Defines interface method rewriter behavior.
public OffOrAuto interfaceMethodDesugaring = OffOrAuto.Auto;
// Defines try-with-resources rewriter behavior.
public OffOrAuto tryWithResourcesDesugaring = OffOrAuto.Auto;
// Flag to turn on/off processing of @dalvik.annotation.codegen.CovariantReturnType and
// @dalvik.annotation.codegen.CovariantReturnType$CovariantReturnTypes.
public boolean processCovariantReturnTypeAnnotations = true;
// Whether or not to check for valid multi-dex builds.
//
// For min-api levels that did not support native multi-dex the user should provide a main dex
// list. However, DX, didn't check that this was the case. Therefore, for CompatDX we have a flag
// to disable the check that the build makes sense for multi-dexing.
public boolean enableMainDexListCheck = true;
private final boolean enableTreeShaking;
private final boolean enableMinification;
public boolean isShrinking() {
return enableTreeShaking;
}
public boolean isMinifying() {
return enableMinification;
}
public boolean printCfg = false;
public String printCfgFile;
public boolean ignoreMissingClasses = false;
// EXPERIMENTAL flag to get behaviour as close to Proguard as possible.
public boolean forceProguardCompatibility = false;
public boolean disableAssertions = true;
public boolean debugKeepRules = false;
// Read input classes into CfCode format (instead of JarCode).
public boolean enableCfFrontend = false;
// Don't convert Code objects to IRCode.
public boolean skipIR = false;
public boolean debug = false;
public final TestingOptions testing = new TestingOptions();
public List<ProguardConfigurationRule> mainDexKeepRules = ImmutableList.of();
public boolean minimalMainDex;
/**
* Enable usage of InheritanceClassInDexDistributor for multidex legacy builds.
* This allows distribution of classes to minimize DexOpt LinearAlloc usage by minimizing linking
* errors during DexOpt and controlling the load of classes with linking issues.
* This has the consequence of making minimal main dex not absolutely minimal regarding runtime
* execution constraints because it's adding classes in the main dex to satisfy also DexOpt
* constraints.
*/
public boolean enableInheritanceClassInDexDistributor = true;
public LineNumberOptimization lineNumberOptimization = LineNumberOptimization.ON;
public static boolean shouldEnableKeepRuleSynthesisForRecompilation() {
return System.getProperty("com.android.tools.r8.keepRuleSynthesisForRecompilation") != null;
}
private static Set<String> getExtensiveLoggingFilter() {
String property = System.getProperty("com.android.tools.r8.extensiveLoggingFilter");
if (property != null) {
ImmutableSet.Builder<String> builder = ImmutableSet.builder();
for (String method : property.split(";")) {
builder.add(method);
}
return builder.build();
}
return ImmutableSet.of();
}
private static Set<String> getExtensiveFieldMinifierLoggingFilter() {
String property =
System.getProperty("com.android.tools.r8.extensiveFieldMinifierLoggingFilter");
if (property != null) {
ImmutableSet.Builder<String> builder = ImmutableSet.builder();
for (String method : property.split(";")) {
builder.add(method);
}
return builder.build();
}
return ImmutableSet.of();
}
private static Set<String> getExtensiveInterfaceMethodMinifierLoggingFilter() {
String property =
System.getProperty("com.android.tools.r8.extensiveInterfaceMethodMinifierLoggingFilter");
if (property != null) {
ImmutableSet.Builder<String> builder = ImmutableSet.builder();
for (String method : property.split(";")) {
builder.add(method);
}
return builder.build();
}
return ImmutableSet.of();
}
public static class InvalidParameterAnnotationInfo {
final DexMethod method;
final int expectedParameterCount;
final int actualParameterCount;
public InvalidParameterAnnotationInfo(
DexMethod method, int expectedParameterCount, int actualParameterCount) {
this.method = method;
this.expectedParameterCount = expectedParameterCount;
this.actualParameterCount = actualParameterCount;
}
}
private static class TypeVersionPair {
final int version;
final DexType type;
public TypeVersionPair(int version, DexType type) {
this.version = version;
this.type = type;
}
}
private final Map<Origin, List<TypeVersionPair>> missingEnclosingMembers = new HashMap<>();
private final Map<Origin, List<InvalidParameterAnnotationInfo>> warningInvalidParameterAnnotations
= new HashMap<>();
private final Map<Origin, List<Pair<DexEncodedMethod, String>>> warningInvalidDebugInfo
= new HashMap<>();
// Don't read code from dex files. Used to extract non-code information from vdex files where
// the code contains unsupported byte codes.
public boolean skipReadingDexCode = false;
// If null, no main-dex list needs to be computed.
// If non null it must be and passed to the consumer.
public StringConsumer mainDexListConsumer = null;
// If null, no proguad map needs to be computed.
// If non null it must be and passed to the consumer.
public StringConsumer proguardMapConsumer = null;
// If null, no proguad seeds info needs to be computed.
// If non null it must be and passed to the consumer.
public StringConsumer proguardSeedsConsumer = null;
// If null, no usage information needs to be computed.
// If non-null, it must be and is passed to the consumer.
public StringConsumer usageInformationConsumer = null;
// If null, no configuration information needs to be printed.
// If non-null, configuration must be passed to the consumer.
public StringConsumer configurationConsumer = null;
// If null, no graph information needs to be provided for the keep/inclusion of classes
// in the output. If non-null, each edge pertaining to kept parts of the resulting program
// must be reported to the consumer.
public GraphConsumer keptGraphConsumer = null;
// If null, no graph information needs to be provided for the keep/inclusion of classes
// in the main-dex output. If non-null, each edge pertaining to kept parts in the main-dex output
// of the resulting program must be reported to the consumer.
public GraphConsumer mainDexKeptGraphConsumer = null;
public Path proguardCompatibilityRulesOutput = null;
public Consumer<List<ProguardConfigurationRule>> syntheticProguardRulesConsumer = null;
public static boolean assertionsEnabled() {
boolean assertionsEnabled = false;
assert assertionsEnabled = true; // Intentional side-effect.
return assertionsEnabled;
}
public void warningMissingEnclosingMember(DexType clazz, Origin origin, int version) {
TypeVersionPair pair = new TypeVersionPair(version, clazz);
synchronized (missingEnclosingMembers) {
missingEnclosingMembers.computeIfAbsent(origin, k -> new ArrayList<>()).add(pair);
}
}
public void warningInvalidParameterAnnotations(
DexMethod method, Origin origin, int expected, int actual) {
InvalidParameterAnnotationInfo info =
new InvalidParameterAnnotationInfo(method, expected, actual);
synchronized (warningInvalidParameterAnnotations) {
warningInvalidParameterAnnotations.computeIfAbsent(origin, k -> new ArrayList<>()).add(info);
}
}
public void warningInvalidDebugInfo(
DexEncodedMethod method, Origin origin, InvalidDebugInfoException e) {
if (invalidDebugInfoFatal) {
throw new CompilationError("Fatal warning: Invalid debug info", e);
}
synchronized (warningInvalidDebugInfo) {
warningInvalidDebugInfo.computeIfAbsent(
origin, k -> new ArrayList<>()).add(new Pair<>(method, e.getMessage()));
}
}
public boolean printWarnings() {
boolean printed = false;
boolean printOutdatedToolchain = false;
if (warningInvalidParameterAnnotations.size() > 0) {
// TODO(b/67626202): Add a regression test with a program that hits this issue.
reporter.info(
new StringDiagnostic(
"Invalid parameter counts in MethodParameter attributes. "
+ "This is likely due to Proguard having removed a parameter."));
for (Origin origin : new TreeSet<>(warningInvalidParameterAnnotations.keySet())) {
StringBuilder builder =
new StringBuilder("Methods with invalid MethodParameter attributes:");
for (InvalidParameterAnnotationInfo info : warningInvalidParameterAnnotations.get(origin)) {
builder
.append("\n ")
.append(info.method)
.append(" expected count: ")
.append(info.expectedParameterCount)
.append(" actual count: ")
.append(info.actualParameterCount);
}
reporter.info(new StringDiagnostic(builder.toString(), origin));
}
printed = true;
}
if (warningInvalidDebugInfo.size() > 0) {
int count = 0;
for (List<Pair<DexEncodedMethod, String>> methods : warningInvalidDebugInfo.values()) {
count += methods.size();
}
reporter.info(
new StringDiagnostic(
"Stripped invalid locals information from "
+ count
+ (count == 1 ? " method." : " methods.")));
for (Origin origin : new TreeSet<>(warningInvalidDebugInfo.keySet())) {
StringBuilder builder = new StringBuilder("Methods with invalid locals information:");
for (Pair<DexEncodedMethod, String> method : warningInvalidDebugInfo.get(origin)) {
builder.append("\n ").append(method.getFirst().toSourceString());
builder.append("\n ").append(method.getSecond());
}
reporter.info(new StringDiagnostic(builder.toString(), origin));
}
printed = true;
printOutdatedToolchain = true;
}
if (missingEnclosingMembers.size() > 0) {
reporter.info(
new StringDiagnostic(
"InnerClass annotations are missing corresponding EnclosingMember annotations."
+ " Such InnerClass annotations are ignored."));
for (Origin origin : new TreeSet<>(missingEnclosingMembers.keySet())) {
StringBuilder builder = new StringBuilder("Classes with missing enclosing members: ");
boolean first = true;
for (TypeVersionPair pair : missingEnclosingMembers.get(origin)) {
if (first) {
first = false;
} else {
builder.append(", ");
}
builder.append(pair.type);
printOutdatedToolchain |= pair.version < 49;
}
reporter.info(new StringDiagnostic(builder.toString(), origin));
}
printed = true;
}
if (printOutdatedToolchain) {
reporter.info(
new StringDiagnostic(
"Some warnings are typically a sign of using an outdated Java toolchain."
+ " To fix, recompile the source with an updated toolchain."));
}
return printed;
}
public boolean hasMethodsFilter() {
return methodsFilter.size() > 0;
}
public boolean methodMatchesFilter(DexEncodedMethod method) {
// Not specifying a filter matches all methods.
if (!hasMethodsFilter()) {
return true;
}
// Currently the filter is simple string equality on the qualified name.
String qualifiedName = method.qualifiedName();
return methodsFilter.indexOf(qualifiedName) >= 0;
}
public boolean methodMatchesLogArgumentsFilter(DexEncodedMethod method) {
// Not specifying a filter matches no methods.
if (logArgumentsFilter.size() == 0) {
return false;
}
// Currently the filter is simple string equality on the qualified name.
String qualifiedName = method.qualifiedName();
return logArgumentsFilter.indexOf(qualifiedName) >= 0;
}
public enum PackageObfuscationMode {
// General package obfuscation.
NONE,
// Repackaging all classes into the single user-given (or top-level) package.
REPACKAGE,
// Repackaging all packages into the single user-given (or top-level) package.
FLATTEN
}
public static class OutlineOptions {
public static final String CLASS_NAME = "com.android.tools.r8.GeneratedOutlineSupport";
public static final String METHOD_PREFIX = "outline";
public boolean enabled = true;
public int minSize = 3;
public int maxSize = 99;
public int threshold = 20;
}
public static class TestingOptions {
public IROrdering irOrdering =
InternalOptions.assertionsEnabled() && !InternalOptions.DETERMINISTIC_DEBUGGING
? NondeterministicIROrdering.getInstance()
: IdentityIROrdering.getInstance();
public boolean allowProguardRulesThatUseExtendsOrImplementsWrong = true;
public boolean allowTypeErrors =
!Version.isDev() || System.getProperty("com.android.tools.r8.allowTypeErrors") != null;;
public boolean alwaysUsePessimisticRegisterAllocation = false;
public boolean invertConditionals = false;
public boolean placeExceptionalBlocksLast = false;
public boolean dontCreateMarkerInD8 = false;
public boolean forceJumboStringProcessing = false;
public boolean nondeterministicCycleElimination = false;
public Set<Inliner.Reason> validInliningReasons = null;
public boolean noLocalsTableOnInput = false;
public boolean forceNameReflectionOptimization = false;
public boolean disallowLoadStoreOptimization = false;
public Consumer<IRCode> irModifier = null;
// TODO(b/129458850) When fixed, remove this and change all usages to "true".
public boolean enableStatefulLambdaCreateInstanceMethod = false;
public MinifierTestingOptions minifier = new MinifierTestingOptions();
public static class MinifierTestingOptions {
public Comparator<DexMethod> interfaceMethodOrdering = null;
public Comparator<Wrapper<DexMethod>> createInterfaceMethodOrdering(
InterfaceMethodNameMinifier minifier) {
if (interfaceMethodOrdering != null) {
return (a, b) -> interfaceMethodOrdering.compare(a.get(), b.get());
}
return minifier.createDefaultInterfaceMethodOrdering();
}
}
}
private boolean hasMinApi(AndroidApiLevel level) {
assert isGeneratingDex();
return minApiLevel >= level.getLevel();
}
public boolean canUseInvokePolymorphicOnVarHandle() {
return isGeneratingClassFiles() || hasMinApi(AndroidApiLevel.P);
}
public boolean canUseInvokePolymorphic() {
return isGeneratingClassFiles() || hasMinApi(AndroidApiLevel.O);
}
public boolean canUseConstantMethodHandle() {
return isGeneratingClassFiles() || hasMinApi(AndroidApiLevel.P);
}
public boolean canUseConstantMethodType() {
return isGeneratingClassFiles() || hasMinApi(AndroidApiLevel.P);
}
public boolean canUseInvokeCustom() {
return isGeneratingClassFiles() || hasMinApi(AndroidApiLevel.O);
}
public boolean canUseDefaultAndStaticInterfaceMethods() {
return isGeneratingClassFiles() || hasMinApi(AndroidApiLevel.N);
}
public boolean canLeaveStaticInterfaceMethodInvokes() {
return isGeneratingClassFiles() || hasMinApi(AndroidApiLevel.L);
}
public boolean canUseTwrCloseResourceMethod() {
return isGeneratingClassFiles() || hasMinApi(AndroidApiLevel.K);
}
public boolean canUseJava8Methods() {
return hasMinApi(AndroidApiLevel.N);
}
public boolean canUsePrivateInterfaceMethods() {
return isGeneratingClassFiles() || hasMinApi(AndroidApiLevel.N);
}
public boolean isInterfaceMethodDesugaringEnabled() {
// This condition is to filter out tests that never set program consumer.
if (!hasConsumer()) {
return false;
}
return enableDesugaring
&& interfaceMethodDesugaring == OffOrAuto.Auto
&& !canUseDefaultAndStaticInterfaceMethods();
}
public boolean canUseMultidex() {
assert isGeneratingDex();
return intermediate || hasMinApi(AndroidApiLevel.L);
}
public boolean canUseLongCompareAndObjectsNonNull() {
return isGeneratingClassFiles() || hasMinApi(AndroidApiLevel.K);
}
public boolean canUseSuppressedExceptions() {
return isGeneratingClassFiles() || hasMinApi(AndroidApiLevel.K);
}
// APIs for accessing parameter names annotations are not available before Android O, thus does
// not emit them to avoid wasting space in Dex files because runtimes before Android O will ignore
// them.
public boolean canUseParameterNameAnnotations() {
if (!hasConsumer()) {
return false;
}
return isGeneratingClassFiles() || hasMinApi(AndroidApiLevel.O);
}
// Dalvik x86-atom backend had a bug that made it crash on filled-new-array instructions for
// arrays of objects. This is unfortunate, since this never hits arm devices, but we have
// to disallow filled-new-array of objects for dalvik until kitkat. The buggy code was
// removed during the jelly-bean release cycle and is not there from kitkat.
//
// Buggy code that accidentally call code that only works on primitives arrays.
//
// https://android.googlesource.com/platform/dalvik/+/ics-mr0/vm/mterp/out/InterpAsm-x86-atom.S#25106
public boolean canUseFilledNewArrayOfObjects() {
assert isGeneratingDex();
return hasMinApi(AndroidApiLevel.K);
}
// Art had a bug (b/68761724) for Android N and O in the arm32 interpreter
// where an aget-wide instruction using the same register for the array
// and the first register of the result could lead to the wrong exception
// being thrown on out of bounds.
public boolean canUseSameArrayAndResultRegisterInArrayGetWide() {
assert isGeneratingDex();
return minApiLevel > AndroidApiLevel.O_MR1.getLevel();
}
// Some Lollipop versions of Art found in the wild perform invalid bounds
// check elimination. There is a fast path of loops and a slow path.
// The bailout to the slow path is performed too early and therefore
// the array-index variable might not be defined in the slow path code leading
// to use of undefined registers as indices into arrays. The result
// is ArrayIndexOutOfBounds exceptions.
//
// In an attempt to help these Art VMs, all single-width constants are initialized and not moved.
//
// There is no guarantee that this works, but it does make the problem
// disappear on the one known instance of this problem.
//
// See b/69364976 and b/77996377.
public boolean canHaveBoundsCheckEliminationBug() {
return isGeneratingDex() && minApiLevel < AndroidApiLevel.M.getLevel();
}
// MediaTek JIT compilers for KitKat phones did not implement the not
// instruction as it was not generated by DX. Therefore, apps containing
// not instructions would crash if the code was JIT compiled. Therefore,
// we can only use not instructions if we are targeting Art-based
// phones.
public boolean canUseNotInstruction() {
return isGeneratingClassFiles() || hasMinApi(AndroidApiLevel.L);
}
// Art before M has a verifier bug where the type of the contents of the receiver register is
// assumed to not change. If the receiver register is reused for something else the verifier
// will fail and the code will not run.
public boolean canHaveThisTypeVerifierBug() {
return isGeneratingDex() && minApiLevel < AndroidApiLevel.M.getLevel();
}
// Art crashes if we do dead reference elimination of the receiver in release mode and Art
// is asked for the |this| object over a JDWP connection at a point where the receiver
// register has been clobbered.
//
// See b/116683601 and b/116837585.
public boolean canHaveThisJitCodeDebuggingBug() {
return minApiLevel < AndroidApiLevel.Q.getLevel();
}
// The dalvik jit had a bug where the long operations add, sub, or, xor and and would write
// the first part of the result long before reading the second part of the input longs.
public boolean canHaveOverlappingLongRegisterBug() {
return isGeneratingDex() && minApiLevel < AndroidApiLevel.L.getLevel();
}
// Some dalvik versions found in the wild perform invalid JIT compilation of cmp-long
// instructions where the result register overlaps with the input registers.
// See b/74084493.
//
// The same dalvik versions also have a bug where the JIT compilation of code such as:
//
// void method(long l) {
// if (l < 0) throw new RuntimeException("less than");
// if (l == 0) throw new RuntimeException("equal");
// }
//
// Will enter the case for l==0 even when l is non-zero. The code generated for this is of
// the form:
//
// 0: 0x00: ConstWide16 v0, 0x0000000000000000 (0)
// 1: 0x02: CmpLong v2, v4, v0
// 2: 0x04: IfLtz v2, 0x0c (+8)
// 3: 0x06: IfNez v2, 0x0a (+4)
//
// However, the jit apparently clobbers the input register in the IfLtz instruction. Therefore,
// for dalvik VMs we have to instead generate the following code:
//
// 0: 0x00: ConstWide16 v0, 0x0000000000000000 (0)
// 1: 0x02: CmpLong v2, v4, v0
// 2: 0x04: IfLtz v2, 0x0e (+10)
// 3: 0x06: CmpLong v2, v4, v0
// 4: 0x08: IfNez v2, 0x0c (+4)
//
// See b/75408029.
public boolean canHaveCmpLongBug() {
return isGeneratingDex() && minApiLevel < AndroidApiLevel.L.getLevel();
}
// Some Lollipop VMs crash if there is a const instruction between a cmp and an if instruction.
//
// Crashing code:
//
// :goto_0
// cmpg-float v0, p0, p0
// const/4 v1, 0
// if-gez v0, :cond_0
// add-float/2addr p0, v1
// goto :goto_0
// :cond_0
// return p0
//
// Working code:
// :goto_0
// const/4 v1, 0
// cmpg-float v0, p0, p0
// if-gez v0, :cond_0
// add-float/2addr p0, v1
// goto :goto_0
// :cond_0
// return p0
//
// See b/115552239.
public boolean canHaveCmpIfFloatBug() {
return minApiLevel < AndroidApiLevel.M.getLevel();
}
// Some Lollipop VMs incorrectly optimize code with mul2addr instructions. In particular,
// the following hash code method produces wrong results after optimizations:
//
// 0: 0x00: IgetObject v0, v3, Field java.lang.Class MultiClassKey.first
// 1: 0x02: InvokeVirtual { v0 } Ljava/lang/Object;->hashCode()I
// 2: 0x05: MoveResult v0
// 3: 0x06: Const16 v1, 0x001f (31)
// 4: 0x08: MulInt2Addr v1, v0
// 5: 0x09: IgetObject v2, v3, Field java.lang.Class MultiClassKey.second
// 6: 0x0b: InvokeVirtual { v2 } Ljava/lang/Object;->hashCode()I
// 7: 0x0e: MoveResult v2
// 8: 0x0f: AddInt2Addr v1, v2
// 9: 0x10: Return v1
//
// It seems that the issue is the MulInt2Addr instructions. Avoiding that, the VM computes
// hash codes correctly also after optimizations.
//
// This issue has only been observed on a Verizon Ellipsis 8 tablet. See b/76115465.
public boolean canHaveMul2AddrBug() {
return isGeneratingDex() && minApiLevel < AndroidApiLevel.M.getLevel();
}
// Some Marshmallow VMs create an incorrect doubly-linked list of instructions. When the VM
// attempts to create a fixup for a Cortex 53 long add/sub issue, it may diverge due to the cyclic
// list.
//
// See b/77842465.
public boolean canHaveDex2OatLinkedListBug() {
return isGeneratingDex() && minApiLevel < AndroidApiLevel.N.getLevel();
}
// dex2oat on Marshmallow VMs does aggressive inlining which can eat up all the memory on
// devices for self-recursive methods.
//
// See b/111960171
public boolean canHaveDex2OatInliningIssue() {
return isGeneratingDex() && minApiLevel < AndroidApiLevel.N.getLevel();
}
// Art 7.0.0 and later Art JIT may perform an invalid optimization if a string new-instance does
// not flow directly to the init call.
//
// See b/78493232 and b/80118070.
public boolean canHaveArtStringNewInitBug() {
return isGeneratingDex() && minApiLevel < AndroidApiLevel.Q.getLevel();
}
// Dalvik tracing JIT may perform invalid optimizations when int/float values are converted to
// double and used in arithmetic operations.
//
// See b/77496850.
public boolean canHaveNumberConversionRegisterAllocationBug() {
return isGeneratingDex() && minApiLevel < AndroidApiLevel.L.getLevel();
}
// Some Lollipop mediatek VMs have a peculiar bug where the inliner crashes if there is a
// simple constructor that just forwards its arguments to the super constructor. Strangely,
// this happens only for specific signatures: so far the only reproduction we have is for
// a constructor accepting two doubles and one object.
//
// To workaround this we insert a materializing const instruction before the super init
// call. Having a temporary register seems to disable the buggy optimizations.
//
// See b/68378480.
public boolean canHaveForwardingInitInliningBug() {
return isGeneratingDex() && minApiLevel < AndroidApiLevel.M.getLevel();
}
// Some Lollipop x86_64 VMs have a bug causing a segfault if an exception handler directly targets
// a conditional-loop header. This cannot happen for debug builds as the existence of a
// move-exception instruction will ensure a non-direct target.
//
// To workaround this in release builds, we insert a materializing nop instruction in the
// exception handler forcing it not directly target any loop header.
//
// See b/111337896.
public boolean canHaveExceptionTargetingLoopHeaderBug() {
return isGeneratingDex() && !debug && minApiLevel < AndroidApiLevel.M.getLevel();
}
// The Dalvik tracing JIT can trace past the end of the instruction stream and end up
// parsing non-code bytes as code (typically leading to a crash). See b/117907456.
//
// In order to workaround this we insert a goto past the throw, and another goto after the throw
// jumping back to the throw.
// We used to insert a empty loop at the end, however, mediatek has an optimizer
// on lollipop devices that cannot deal with an unreachable infinite loop, so we
// couldn't do that. See b/119895393.
// We also could not insert any dead code (e.g. a return) because that would make mediatek
// dominator calculations on 7.0.0 crash. See b/128926846.
public boolean canHaveTracingPastInstructionsStreamBug() {
return minApiLevel < AndroidApiLevel.L.getLevel();
}
// The art verifier incorrectly propagates type information for the following pattern:
//
// move vA, vB
// instance-of vB, vA, Type
// if-eqz/nez vB
//
// In that case it will assume that vB has object type after the if. Therefore, if the
// result of the instance-of operation is reused in a boolean context the verifier will
// fail with a type conflict.
//
// In order to make sure that cannot happen, we insert a nop between the move and
// the instance-of instruction so that this pattern in the art verifier does not
// match.
//
// move vA, vB
// nop
// instance-of vB, vA, Type
// if-eqz/nez vB
//
// This happens rarely, but it can happen in debug mode where the move
// put a value into a new register which has associated locals information.
//
// Fixed in Android Q, see b/120985556.
public boolean canHaveArtInstanceOfVerifierBug() {
assert isGeneratingDex();
return minApiLevel < AndroidApiLevel.Q.getLevel();
}
// Some Art Lollipop version do not deal correctly with long-to-int conversions.
//
// In particular, the following code performs an out of bounds array access when the
// long loaded from the long array is very large (has non-zero values in the upper 32 bits).
//
// aget-wide v9, v3, v1
// long-to-int v9, v9
// aget-wide v10, v3, v9
//
// The issue seems to be that the higher bits of the 64-bit register holding the long
// are not cleared and the integer is therefore a 64-bit integer that is not truncated
// to 32 bits.
//
// As a workaround, we do not allow long-to-int to have the same source and target register
// for min-apis where lollipop devices could be targeted.
//
// See b/80262475.
public boolean canHaveLongToIntBug() {
// We have only seen this happening on Lollipop arm64 backends. We have tested on
// Marshmallow and Nougat arm64 devices and they do not have the bug.
return minApiLevel < AndroidApiLevel.M.getLevel();
}
// The Art VM for Android N through P has a bug in the JIT that means that if the same
// exception block with a move-exception instruction is targeted with more than one type
// of exception the JIT will incorrectly assume that the exception object has one of these
// types and will optimize based on that one type instead of taking all the types into account.
//
// In order to workaround that, we always generate distinct move-exception instructions for
// distinct dex types.
//
// See b/120164595.
public boolean canHaveExceptionTypeBug() {
return minApiLevel < AndroidApiLevel.Q.getLevel();
}
// Art 4.0.4 fails with a verification error when a null-literal is being passed directly to an
// aget instruction. We therefore need to be careful when performing trivial check-cast
// elimination of check-cast instructions where the value being cast is the constant null.
// See b/123269162.
public boolean canHaveArtCheckCastVerifierBug() {
return minApiLevel < AndroidApiLevel.J.getLevel();
}
// The verifier will merge A[] and B[] to Object[], even when both A and B implement an interface
// I, i.e., the join should have been I[]. This can lead to verification errors when the value is
// used as an I[].
//
// See b/69826014.
public boolean canHaveIncorrectJoinForArrayOfInterfacesBug() {
return true;
}
}
| 39.705998
| 103
| 0.724351
|
5243f6033ca6503c535882af5e4d404b91e8e34a
| 6,087
|
package org.kohsuke.stapler.jelly.issue76;
import org.kohsuke.stapler.ForwardingFunction;
import org.kohsuke.stapler.Function;
import org.kohsuke.stapler.FunctionList;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.TraversalMethodContext;
import org.kohsuke.stapler.lang.FieldRef;
import org.kohsuke.stapler.lang.Klass;
import org.kohsuke.stapler.lang.KlassNavigator;
import org.kohsuke.stapler.lang.MethodRef;
import org.kohsuke.stapler.lang.util.FieldRefFilter;
import javax.servlet.ServletException;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* Used as 'C' of {@code Klass<C>} to represents a protected version of a {@link Class}.
*
* @author Kohsuke Kawaguchi
*/
public class ProtectedClass {
private final Class c;
public ProtectedClass(Class c) {
this.c = c;
}
public static KlassNavigator<ProtectedClass> NAVIGATOR = new KlassNavigator<ProtectedClass>() {
@Override
public boolean isArray(ProtectedClass clazz) {
return JAVA.isArray(clazz.c);
}
@Override
public Object getArrayElement(Object o, int index) throws IndexOutOfBoundsException {
return w(JAVA.getArrayElement(u(o),index));
}
@Override
public boolean isMap(ProtectedClass clazz) {
return JAVA.isMap(clazz.c);
}
@Override
public Object getMapElement(Object o, String key) {
return w(JAVA.getMapElement(u(o),key));
}
private Klass<ProtectedClass> protect(Klass<?/*should be Class*/> c) {
if (c==null) return null;
return new Klass<ProtectedClass>(new ProtectedClass((Class)c.clazz), NAVIGATOR);
}
// no view
@Override
public URL getResource(ProtectedClass clazz, String resourceName) {
return null;
}
@Override
public Iterable<Klass<?>> getAncestors(ProtectedClass clazz) {
List<Klass<?>> r = new ArrayList<Klass<?>>();
for (Klass<?> c : JAVA.getAncestors(clazz.c)) {
r.add(protect(c));
}
return r;
}
@Override
public Klass<ProtectedClass> getSuperClass(ProtectedClass clazz) {
return protect(JAVA.getSuperClass(clazz.c));
}
@Override
public Class toJavaClass(ProtectedClass clazz) {
return ProtectedClass.class;
}
@Override
public List<MethodRef> getDeclaredMethods(ProtectedClass clazz) {
return JAVA.getDeclaredMethods(clazz.c);
}
@Override
public List<FieldRef> getDeclaredFields(ProtectedClass clazz) {
List<FieldRef> r = new ArrayList<FieldRef>();
for (final FieldRef f : JAVA.getDeclaredFields(clazz.c)) {
r.add(new FieldRefFilter() {
@Override
protected FieldRef getBase() {
return f;
}
@Override
public String getSignature() {
return f.getQualifiedName(); // doesn't really matter
}
@Override
public Object get(Object instance) throws IllegalAccessException {
// as we route requests, keep protecting objects
return w(super.get(u(instance)));
}
@Override
public Class<?> getReturnType() {
return f.getReturnType();
}
});
}
return r;
}
private Object u(Object instance) {
if (instance==null) return null;
return ((Protection)instance).o;
}
private Protection w(Object instance) {
if (instance==null) return null;
return new Protection(instance);
}
@Override
public List<Function> getFunctions(ProtectedClass clazz) {
List<Function> r = new ArrayList<Function>();
// insert this at the top to make sure that shadows doIndex in subtypes
r.addAll(new FunctionList(JAVA.getFunctions(Protection.class)).name("doIndex"));
// expose all the functions from the base type
for (Function f : JAVA.getFunctions(clazz.c)) {
r.add(protect(f));
}
return r;
}
/**
* Decorates {@link Function} so that it can be invoked on {@link Protection} and the
* return value gets protected as well.
*
* <p>
* If the function is used for object traversal, the return value needs to be wrapped to {@link Protection}.
*/
private Function protect(Function f) {
final Function traversal = new ForwardingFunction(f) {
@Override
public Object invoke(StaplerRequest req, StaplerResponse rsp, Object o, Object... args) throws IllegalAccessException, InvocationTargetException, ServletException {
return w(super.invoke(req, rsp, u(o), args));
}
};
final Function service = new ForwardingFunction(f) {
@Override
public Function contextualize(Object usage) {
if (usage instanceof TraversalMethodContext) {
return traversal;
} else {
return super.contextualize(usage);
}
}
@Override
public Object invoke(StaplerRequest req, StaplerResponse rsp, Object o, Object... args) throws IllegalAccessException, InvocationTargetException, ServletException {
return super.invoke(req, rsp, u(o), args);
}
};
return service;
}
};
}
| 34.585227
| 180
| 0.57286
|
2ffc4f60066885190ff6cf1150adb495dd06cce1
| 468
|
package hero.concentrationcamp.mvp.presenter;
import hero.concentrationcamp.mvp.BasePresenter;
import hero.concentrationcamp.mvp.contract.MainContract;
import hero.concentrationcamp.mvp.data.MainActivityDataFactory;
/**
* Created by hero on 2016/11/30 0030.
*/
public class MainActivityPresenter extends BasePresenter<MainContract.IMainActivityView> implements MainContract.IMainPresenter {
MainActivityDataFactory factory = new MainActivityDataFactory();
}
| 31.2
| 129
| 0.833333
|
59b840260419d4653f1ba655e4d4c71d7b4de719
| 6,571
|
package com.osrsbox.squirrel;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.FileWriter;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.HelpFormatter;
import net.runelite.cache.IndexType;
import net.runelite.cache.ItemManager;
import net.runelite.cache.NpcManager;
import net.runelite.cache.ObjectManager;
import net.runelite.cache.TextureManager;
import net.runelite.cache.definitions.ModelDefinition;
import net.runelite.cache.definitions.loaders.ModelLoader;
import net.runelite.cache.fs.Store;
import net.runelite.cache.fs.Storage;
import net.runelite.cache.fs.flat.FlatStorage;
import net.runelite.cache.fs.Index;
import net.runelite.cache.fs.Archive;
import net.runelite.cache.models.ObjExporter;
public class Nuts
{
public static void main(String[] args) throws IOException
{
Options options = new Options();
options.addOption("h", "help", false, "Print this help menu");
options.addOption("v", "version", false, "Print the version number");
options.addOption("c", "cache", true, "Load cache from specific target folder");
options.addOption("f", "flatcache", true, "Load flat cache from specific target folder");
options.addOption("i", "items", false, "Dump ItemDefinitions in JSON to specific target folder");
options.addOption("n", "npcs", false, "Dump NpcDefinitions in JSON to specific target folder");
options.addOption("o", "objects", false, "Dump ObjectDefinitions in JSON to specific target folder");
options.addOption("m", "models", false, "Dump models in OBJ + MTL to specific target folder");
CommandLineParser parser = new DefaultParser();
CommandLine cmd;
try
{
cmd = parser.parse(options, args);
}
catch (ParseException ex)
{
System.err.println("Error parsing command line options: " + ex.getMessage());
System.exit(-1);
return;
}
if (cmd.hasOption("help"))
{
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp( "squirrel" , options );
return;
}
if (cmd.hasOption("version"))
{
String version = Nuts.class.getPackage().getImplementationVersion();
System.out.println("squirrel - " + version);
String runeliteCacheVersion = Nuts.class.getPackage().getImplementationTitle();
System.out.println("runelite - " + runeliteCacheVersion);
return;
}
// Load cache store
Store store;
if (cmd.hasOption("cache"))
{
String cache = cmd.getOptionValue("cache");
System.out.println("[*] Loading cache from: " + cache);
store = loadStore(cache);
}
else if (cmd.hasOption("flatcache"))
{
String cache = cmd.getOptionValue("flatcache");
System.out.println("[*] Loading flatcache from: " + cache);
store = loadStoreFlat(cache);
}
else
{
String cache = "osrs-cache";
System.out.println("[*] Loading default flatcache from: " + cache);
store = loadStoreFlat(cache);
}
// Try do something
if (cmd.hasOption("items"))
{
String itemdir;
itemdir = cmd.getOptionValue("items");
if (itemdir == null)
{
itemdir = "dumped-objects";
}
System.out.println("[*] Dumping items to: " + itemdir);
dumpItems(store, new File(itemdir));
}
else if (cmd.hasOption("npcs"))
{
String npcdir;
npcdir = cmd.getOptionValue("npcs");
if (npcdir == null)
{
npcdir = "dumped-npcs";
}
System.out.println("[*] Dumping npcs to: " + npcdir);
dumpNpcs(store, new File(npcdir));
}
else if (cmd.hasOption("objects"))
{
String objectdir;
objectdir = cmd.getOptionValue("objects");
if (objectdir == null)
{
objectdir = "dumped-objects";
}
System.out.println("[*] Dumping objects to: " + objectdir);
dumpObjects(store, new File(objectdir));
}
else if (cmd.hasOption("models"))
{
String modeldir;
modeldir = cmd.getOptionValue("models");
if (modeldir == null)
{
modeldir = "dumped-models";
}
System.out.println("[*] Dumping models to: " + modeldir);
dumpModels(store, new File(modeldir));
}
else
{
System.err.println("[*] Nothing to do. Provide a command line argument to do something...");
System.exit(-1);
return;
}
System.out.println("[*] Finished.");
}
private static Store loadStore(String cache) throws IOException
{
Store store = new Store(new File(cache));
store.load();
return store;
}
private static Store loadStoreFlat(String cache) throws IOException
{
FlatStorage fs = new FlatStorage(new File(cache));
Store store = new Store(fs);
store.load();
return store;
}
private static void dumpItems(Store store, File itemdir) throws IOException
{
ItemManager dumper = new ItemManager(store);
dumper.load();
dumper.export(itemdir);
dumper.java(itemdir);
}
private static void dumpNpcs(Store store, File npcdir) throws IOException
{
NpcManager dumper = new NpcManager(store);
dumper.load();
dumper.dump(npcdir);
dumper.java(npcdir);
}
private static void dumpObjects(Store store, File objectdir) throws IOException
{
ObjectManager dumper = new ObjectManager(store);
dumper.load();
dumper.dump(objectdir);
dumper.java(objectdir);
}
private static void dumpModels(Store store, File modelDir) throws IOException
{
modelDir.mkdirs();
Storage storage = store.getStorage();
Index index = store.getIndex(IndexType.MODELS);
for (Archive archive : index.getArchives())
{
int modelIndex = archive.getArchiveId();
byte[] contents = archive.decompress(storage.loadArchive(archive));
TextureManager tm = new TextureManager(store);
tm.load();
ModelLoader loader = new ModelLoader();
ModelDefinition model;
try
{
model = loader.load(archive.getArchiveId(), contents);
}
catch (NullPointerException ex)
{
System.err.println("[*] Error extracting models: " + ex.getMessage());
System.out.println("[*] Try using the default flatcache provided with the project");
System.exit(-1);
return;
}
ObjExporter exporter = new ObjExporter(tm, model);
String objFileOut = modelDir + File.separator + modelIndex + ".obj";
String mtlFileOut = modelDir + File.separator + modelIndex + ".mtl";
try (PrintWriter objWriter = new PrintWriter(new FileWriter(new File(objFileOut)));
PrintWriter mtlWriter = new PrintWriter(new FileWriter(new File(mtlFileOut))))
{
exporter.export(objWriter, mtlWriter);
}
}
}
}
| 27.26556
| 103
| 0.698067
|
04351c25c835231228b70550a9cb452f7c7e3f91
| 1,597
|
/**
*/
package org.iobserve.model.correspondence;
import org.palladiosimulator.pcm.repository.RepositoryComponent;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Component Entry</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link org.iobserve.model.correspondence.ComponentEntry#getComponent <em>Component</em>}</li>
* </ul>
*
* @see org.iobserve.model.correspondence.CorrespondencePackage#getComponentEntry()
* @model
* @generated
*/
public interface ComponentEntry extends AbstractEntry {
/**
* Returns the value of the '<em><b>Component</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Component</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Component</em>' reference.
* @see #setComponent(RepositoryComponent)
* @see org.iobserve.model.correspondence.CorrespondencePackage#getComponentEntry_Component()
* @model required="true"
* @generated
*/
RepositoryComponent getComponent();
/**
* Sets the value of the '{@link org.iobserve.model.correspondence.ComponentEntry#getComponent <em>Component</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Component</em>' reference.
* @see #getComponent()
* @generated
*/
void setComponent(RepositoryComponent value);
} // ComponentEntry
| 31.313725
| 130
| 0.647464
|
9d9601235b93b18adc8104b5db3e66dd5b373679
| 4,439
|
package com.demo.transfer.domain.service;
import com.demo.transfer.common.MqTemplate;
import com.demo.transfer.domain.factory.TransferRecordFactory;
import com.demo.transfer.domain.model.account.Account;
import com.demo.transfer.domain.model.account.DeductAccountEvent;
import com.demo.transfer.domain.model.transfer.Transfer;
import com.demo.transfer.domain.model.transfer.TransferRecord;
import com.demo.transfer.domain.repository.AccountRepository;
import com.demo.transfer.domain.repository.TransferRecordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.time.LocalDateTime;
import static com.demo.transfer.common.MqMessageStatus.DONE;
import static com.demo.transfer.common.MqMessageStatus.PREPARE;
import static com.demo.transfer.domain.model.transfer.TransferStatus.*;
@Service
public class TransferService {
private final AccountRepository accountRepository;
private final TransferRecordRepository transferRecordRepository;
private final MqTemplate mqTemplate;
@Autowired
public TransferService(AccountRepository accountRepository,
TransferRecordRepository transferRecordRepository,
MqTemplate mqTemplate) {
this.accountRepository = accountRepository;
this.transferRecordRepository = transferRecordRepository;
this.mqTemplate = mqTemplate;
}
/**
* description: 创建转账记录,防止重复转账,以 orderSeq 作为唯一约束
* 如果抛 DuplicateKeyException 异常,表明库中已经存在该记录,直接
* 查询返回库中的转账记录
*
* @param transfer: 转账对象,包含转账相关信息
* @return: com.demo.transfer.domain.model.transfer.TransferRecord
* date: 2020/2/9 <br>
* version: 1.0 <br>
*/
public TransferRecord findExistedOrCreateTransferRecord(Transfer transfer) {
try {
TransferRecord transferRecord = TransferRecordFactory.create(transfer);
transferRecordRepository.save(transferRecord);
return transferRecord;
} catch (DuplicateKeyException e) {
return transferRecordRepository.findByOrderSeq(transfer.getOrderSeq());
}
}
/**
* description: 转账失败操作 <br>
*
* @param transferRecord: 转账记录
* @param failedMessage: 失败信息
* @return: void
* date: 2020/2/9 <br>
* version: 1.0 <br>
*/
public void fail(TransferRecord transferRecord, String failedMessage) {
transferRecord.setFailedMessage(failedMessage);
transferRecord.setEndTime(LocalDateTime.now());
transferRecordRepository.updateTransferStatus(transferRecord, transferRecord.getStatus(), FAILED);
}
/**
* description: 扣款操作,主要分为 3 个步骤:
* 步骤1: 先向队列发送 prepare 消息,通知准备扣款,并拿到消息在队列中的地址,
* prepare 消息对用户不可见
* 如果发送失败,直接转账失败,成功进入 步骤 2;
* 步骤2: 执行本地扣款操作,并更新交易状态,本地事务可以保证操作的原子性;
* 步骤3: 用步骤 1 的消息地址,更改消息状态为 done,表示可以被消费
*
* @param payerAccount: 扣款账户
* @param transferRecord: 转账记录
* @return: void
* date: 2020/2/8 <br>
* version: 1.0 <br>
*/
@Transactional
public void minusBalance(Account payerAccount, TransferRecord transferRecord) {
String messageAddress = mqTemplate.syncSend(new DeductAccountEvent(PREPARE, transferRecord));
if (messageAddress == null) {
fail(transferRecord, "预扣款失败");
return;
}
// 采用乐观锁以version字段作为区分,如果更新的行数为0,则表示转账失败
boolean success = accountRepository.minusAmount(payerAccount, transferRecord.getAmount())
&& transferRecordRepository.updateTransferStatus(transferRecord, transferRecord.getStatus(), SUCCEED);
if (!success) {
fail(transferRecord, "预款失败");
return;
}
mqTemplate.overrideMessage(messageAddress, new DeductAccountEvent(DONE, transferRecord));
transferRecordRepository.updateTransferStatus(transferRecord, BEGIN, DEDUCTED);
}
/**
* description: 冲正转账
*
* @param transferRecord: 上一次的转账记录
* @return: void
* date: 2020/2/8 <br>
* version: 1.0 <br>
*/
public void reverse(TransferRecord transferRecord) {
Account payerAccount = accountRepository.findByNumber(transferRecord.getPayerAccountNumber());
accountRepository.addBalance(payerAccount, transferRecord.getAmount());
}
}
| 36.68595
| 114
| 0.706465
|
cf89aaf40e13473d68acd3acc0b273baf40b4fca
| 1,517
|
/*
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 md.mdobs.andyPush;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import org.apache.cordova.*;
import org.usergrid.cordova.WakeLocker;
import com.google.android.gcm.GCMRegistrar;
public class andyPush extends DroidGap
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.loadUrl(Config.getStartUrl());
}
}
| 29.173077
| 67
| 0.735003
|
fcfd6b2395a14b63f3786a17f5b6b09b326ac83f
| 2,012
|
/*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.druid.segment;
import io.druid.collections.bitmap.BitmapFactory;
import io.druid.segment.data.Indexed;
import org.joda.time.Interval;
import java.io.Closeable;
import java.io.IOException;
import java.util.Map;
/**
* Direct interface to memory mapped segments. Not a public API for extensions; site specific queries should be
* using {@link StorageAdapter}.
*
* @see QueryableIndexStorageAdapter for query path adapter
* @see QueryableIndexIndexableAdapter for indexing path adapter
*/
public interface QueryableIndex extends ColumnSelector, Closeable
{
public Interval getDataInterval();
public int getNumRows();
public Indexed<String> getAvailableDimensions();
public BitmapFactory getBitmapFactoryForDimensions();
public Metadata getMetadata();
public Map<String, DimensionHandler> getDimensionHandlers();
/**
* The close method shouldn't actually be here as this is nasty. We will adjust it in the future.
* @throws IOException if an exception was thrown closing the index
*/
//@Deprecated // This is still required for SimpleQueryableIndex. It should not go away unitl SimpleQueryableIndex is fixed
@Override
public void close() throws IOException;
}
| 37.259259
| 125
| 0.771372
|
73355e87202a778b50fb2c6a98279630cc029d44
| 350
|
package io.crnk.core.mock.repository;
import io.crnk.core.mock.models.ProjectPolymorphic;
import io.crnk.core.repository.InMemoryResourceRepository;
public class ProjectPolymorphicRepository extends InMemoryResourceRepository<ProjectPolymorphic, Long> {
public ProjectPolymorphicRepository() {
super(ProjectPolymorphic.class);
}
}
| 29.166667
| 104
| 0.808571
|
07c19958cb07fc80d6351528f4bc48d150249da4
| 972
|
package es.usc.citius.hipster.model.problem;
import es.usc.citius.hipster.model.Node;
import es.usc.citius.hipster.model.function.NodeExpander;
/**
* Defines a search problems in terms of a initial node to start with and the node expander
* function that generates new successor nodes. A SearchProblem can be fully defined using
* the {@link es.usc.citius.hipster.model.problem.ProblemBuilder} class assistant builder.
*
* @author Pablo Rodríguez Mier <<a href="mailto:pablo.rodriguez.mier@usc.es">pablo.rodriguez.mier@usc.es</a>>
*/
public class SearchProblem<A,S,N extends Node<A,S,N>> {
private N initialNode;
private NodeExpander<A,S,N> expander;
public SearchProblem(N initialNode, NodeExpander<A, S, N> expander) {
this.initialNode = initialNode;
this.expander = expander;
}
public N getInitialNode() {
return initialNode;
}
public NodeExpander<A, S, N> getExpander() {
return expander;
}
}
| 32.4
| 110
| 0.712963
|
e94e701ca400856859227e3fce3efc63f98af18f
| 2,283
|
package com.api.clustermanage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import com.api.util.ActiveKeyValueStore;
/**
* Zookeeper-集群管理
* Watcher 监控,使用原生api连接Zookeeper
* @author wangheng
*
*/
public class ChildrenWatcher implements Watcher {
private ActiveKeyValueStore _store;
//临时节点列表
List<String> oldChildrenList = new ArrayList<String>();
public ChildrenWatcher(String hosts) throws InterruptedException, IOException, KeeperException {
_store = new ActiveKeyValueStore();
// 连接Zookeeper
_store.connect(hosts);
//查询临时节点集合
oldChildrenList = _store.readChildren(ClientRegister1.rootPATH, this);
}
/**
* 读取znode节点数据
*
* @throws InterruptedException
* @throws KeeperException
*/
public void displayConfig() throws InterruptedException, KeeperException {
try {
//查询当前临时节点集合
List<String> currentChildrenList = _store.readChildren(ClientRegister1.rootPATH,
this);
for (String child : currentChildrenList) {
if (!oldChildrenList.contains(child)) {
System.out.println("新增加的regionServer节点为:" + child);
}
}
for (String child : oldChildrenList) {
if (!currentChildrenList.contains(child)) {
System.out.println("挂掉的regionServer节点为:" + child);
}
}
//临时子节点集合更新
this.oldChildrenList = currentChildrenList;
} catch (Exception e) {
e.printStackTrace();
}
}
// 监控临时节点变化
public void process(WatchedEvent event) {
if (event.getType() == Event.EventType.NodeChildrenChanged) {
try {
// 调用具体业务代码
displayConfig();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (KeeperException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException,
InterruptedException, KeeperException {
String hosts = "192.168.80.131:2181";
// 创建watcher
ChildrenWatcher watcher = new ChildrenWatcher(hosts);
// 调用display方法
watcher.displayConfig();
// 然后一直处于监控状态
Thread.sleep(Long.MAX_VALUE);
}
}
| 26.241379
| 98
| 0.693386
|
bbb7340398c69040c5b7076f065a599aad26e727
| 1,068
|
import java.util.ArrayList;
/**
* Created by davidwestgate on 5/1/15.
*/
public class Organization {
private String name;
private ArrayList<Address> addresses;
/**
* Constructor for Organization data object
* @param name
* @param address
*/
public Organization(String name, Address address) {
this.name = name;
this.addresses = new ArrayList<Address>();
this.addresses.add(address);
}
/**
* Constructor for Organization data object
* @param name
*/
public Organization(String name) {
this.name = name;
this.addresses = new ArrayList<Address>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ArrayList<Address> getAddresses() {
return addresses;
}
public void setAddresses(ArrayList<Address> addresses) {
this.addresses = addresses;
}
public void addAddress(Address address) {
this.addresses.add(address);
}
}
| 20.150943
| 60
| 0.607678
|
e41fb58574e2ef22b18e06d880a3bb0c5e0d92d4
| 3,575
|
/*
* $Id: OgexIndexArray.java 3827 2014-11-23 08:13:36Z pspeed $
*
* Copyright (c) 2014, Simsilica, LLC
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.simsilica.ogex;
import java.lang.reflect.Array;
import com.simsilica.oddl.PrimitiveType;
/**
*
*
* @author Paul Speed
*/
public class OgexIndexArray {
private long material;
private long restart;
private VertexWinding front;
private int elementSize;
private int elementCount;
private PrimitiveType elementType;
private Object array;
public OgexIndexArray() {
}
public void setMaterial( long material ) {
this.material = material;
}
public long getMaterial() {
return material;
}
public void setRestart( long restart ) {
this.restart = restart;
}
public long getRestart() {
return restart;
}
public void setFront( VertexWinding front ) {
this.front = front;
}
public VertexWinding getFront() {
return front;
}
public void setArray( Object array, PrimitiveType elementType, int elementSize ) {
this.elementCount = Array.getLength(array);
this.elementSize = elementSize;
this.array = array;
this.elementType = elementType;
}
public PrimitiveType getElementType() {
return elementType;
}
public int getElementSize() {
return elementSize;
}
public int getSize() {
return elementCount;
}
public Object getArray() {
return array;
}
@Override
public String toString() {
return getClass().getSimpleName() + "[material=" + material + ", restart=" + restart
+ ", arrayType=" + elementType.getId() + "[" + elementCount + "]"
+ (elementSize <= 1 ? "" : "[" + elementSize + "]" + "]");
}
}
| 31.086957
| 94
| 0.638322
|
6efcddf7e7740f3412d8076036ca8efe165ed3d8
| 1,739
|
/**
* Copyright (c) 2009-2011, The HATS Consortium. All rights reserved.
* This file is licensed under the terms of the Modified BSD License.
*/
package org.abs_models.frontend.mtvl;
import org.abs_models.common.WrongProgramArgumentException;
import org.abs_models.frontend.delta.DeltaModellingException;
import org.junit.Test;
import org.abs_models.frontend.FrontendTest;
import org.abs_models.frontend.ast.Model;
public class FeatureModel extends FrontendTest {
@Test
public void minimalFM() {
Model model = assertParse("root FM");
}
@Test
public void minimalFMwithProduct() throws DeltaModellingException, WrongProgramArgumentException {
Model model = assertParse("productline PL; features FM;"
+ "product P(FM);"
+ "root FM");
model.flattenForProduct("P");
}
@Test
public void attributeUnbounded() throws DeltaModellingException, WrongProgramArgumentException {
Model model = assertParse("productline PL; features FM;"
+ "product P();"
+ "root FM { Int attr; }");
model.flattenForProduct("P");
}
@Test
public void attributeUnbounded2() throws DeltaModellingException, WrongProgramArgumentException {
Model model = assertParse("productline PL; features FM;"
+ "product P();"
+ "root FM { Int attr in [*..*]; }");
model.flattenForProduct("P");
}
@Test
public void attributeBounded() throws DeltaModellingException, WrongProgramArgumentException {
Model model = assertParse("productline PL; features FM;"
+ "product P();"
+ "root FM { Int attr in [0 .. 99]; }");
model.flattenForProduct("P");
}
}
| 31.618182
| 102
| 0.658999
|
74faa859c35c8c25122dfa6e487d801ded268a1f
| 1,784
|
package dynks.cache;
import javax.servlet.http.HttpServletRequest;
/**
* Key retrieving strategy that applies namespace in in form:
* <pre>namespace:uri</pre> which can later be saved in repository.
*
* @author jszczepankiewicz
* @since 2015-04-17
*/
public class NamespacedURIKeyStrategy implements KeyStrategy {
public static final String EMPTY_NAMESPACE = "";
private final String namespace;
public NamespacedURIKeyStrategy(String namespace) {
if (namespace == null) {
throw new NullPointerException("Namespace should not be null");
}
this.namespace = namespace;
}
public static NamespacedURIKeyStrategy keyStrategyWithEmptyNamespace() {
return new NamespacedURIKeyStrategy(EMPTY_NAMESPACE);
}
@Override
public String wildcardKeyFor(CacheRegion region) {
StringBuilder builder = new StringBuilder(3 + namespace.length() + region.getId().length());
builder.append(namespace);
builder.append(':');
builder.append(region.getId());
builder.append(":*");
return builder.toString();
}
@Override
public String keyFor(HttpServletRequest request, CacheRegion region) {
String uri = request.getRequestURI();
// this should be pooled probably
StringBuilder builder = new StringBuilder(uri.length() + 2 + namespace.length() + region.getId().length());
builder.append(namespace);
builder.append(':');
builder.append(region.getId());
builder.append(':');
builder.append(uri);
return builder.toString();
}
@Override
public int hashCode() {
return this.getClass().toGenericString().hashCode();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
return true;
}
}
| 27.030303
| 111
| 0.697309
|
0fc40050a7f796367d1da98a7be34ed490d81f05
| 2,069
|
package anno16_17.poo.file;
import java.io.*;
import java.util.*;
/**
* Dato un file tipato di interi, supposto ordinato per
* valori crescenti, ed un numero x, si desidera aggiungere
* x al file preservando l'ordine (insertion sort su file).
* A questo scopo si usa un file temporaneo su cui si
* copiano tutti i valori del file originario minori o uguali ad x.
* Quindi si copia x e, infine, tutti i restanti valori
* del file di partenza. Dopo questo si cancella il file di
* partenza (con i servizi degli oggetti File) e si ridenomina
* il file temporaneo con lo stesso nome del file di origine.
* @author Libero Nigro
*/
public class AggiornamentoSelettivo{
public static void main( String []args )throws IOException {
Scanner sc=new Scanner( System.in );
System.out.print("nome file=");
String nome=sc.next();
System.out.print("intero da aggiungere ");
int x=sc.nextInt();
inserisci( nome, x );
sc.close();
}//main
static void mostra( String nome ) throws IOException{
System.out.println("Contenuto del file "+nome);
InputStream in=new BufferedInputStream( new FileInputStream(nome) );
DataInputStream dis=new DataInputStream( in );
for(;;){
try{
int x=dis.readInt();
System.out.println(x);
}catch(Exception e ){ break; }
}
dis.close();
}//mostra
static void inserisci( String nome, int x )throws IOException{
mostra( nome );
RandomAccessFile raf=new RandomAccessFile( nome, "r" );
DataOutputStream tmp=
new DataOutputStream( new FileOutputStream("tmp") );
long pos=0;
int y=0;
boolean flag=false;
while( pos<raf.length() && !flag ){
y=raf.readInt();
if( y>x ) flag=true;
else tmp.writeInt( y );
pos=raf.getFilePointer();
}//while
tmp.writeInt( x );
if( flag ){
for(;;){
tmp.writeInt( y );
pos=raf.getFilePointer();
if( pos==raf.length() ) break;
y=raf.readInt();
}
}
tmp.close(); raf.close();
mostra("tmp");
File f=new File(nome); f.delete();
File ff=new File("tmp");
System.out.println(ff.renameTo(f));
}
}//AggiornamentoSelettivo
| 30.426471
| 70
| 0.679072
|
371bb59c436cd9903589a486b928e7becaea2885
| 1,886
|
package sorm.util;
/**
* 封装常用的字符串操作
*
* @Date 2020/02/18 23:08
* @Created by lan-mao.top
*/
public class StringUtils {
/**
* 将字符串转为UpperCamelCase风格
* @param str 目标字符串
* @return 首字符大写的字符串
*/
public static String toUpperCamelCase(String str) {
String[] list = str.split("_");
StringBuilder sb = new StringBuilder();
for (String s : list) {
sb.append(s.toUpperCase().substring(0, 1)).append(s.substring(1));
}
return sb.toString();
}
/**
* 将以字符串转为lowerCamelCase风格
* @param str 目标字符串
* @return lowerCamelCase风格
*/
public static String toLowerCamelCase(String str){
String[] list = str.split("_");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.length; i++) {
if (i == 0) {
sb.append(list[i].toLowerCase().substring(0, 1) + list[i].substring(1));
} else {
sb.append(list[i].toUpperCase().substring(0, 1) + list[i].substring(1));
}
}
return sb.toString();
}
public static String javaPath2FilePath(String javaPath){
return javaPath.replaceAll("\\.", JavaFileUtils.pathSeparator);
}
public static String covertFromJavaCamelCase(String str){
char[] strArray = str.toCharArray();
StringBuilder result = new StringBuilder();
for (char c : strArray) {
if (c>='A'&&c<='Z'){
if (result.length()>0){
result.append('_');
}
result.append((char)('a' + c - 'A'));
} else {
result.append(c);
}
}
return result.toString();
}
public static void main(String[] args) {
String name = "empName";
System.out.println(covertFromJavaCamelCase(name));
}
}
| 28.149254
| 88
| 0.531813
|
a614c510c7f73705a85f828dbffde1b1d139afda
| 1,759
|
/*
* Copyright 2019 DeNA Co., Ltd.
*
* 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 packetproxy.gui;
import javax.swing.*;
public class Splash{
private JWindow mSplashScreen;
public Splash(){
createSplash();
}
private void runAsync(final Runnable runnable){
if(SwingUtilities.isEventDispatchThread()){
runnable.run();
}else {
SwingUtilities.invokeLater(runnable);
}
}
private void createSplash(){
ImageIcon img = new ImageIcon(getClass().getResource("/gui/splash.png"));
JLabel splashLabel = new JLabel(img);
mSplashScreen = new JWindow(new JFrame());
mSplashScreen.getContentPane().add(splashLabel);
mSplashScreen.pack();
mSplashScreen.setLocationRelativeTo(null);
}
public void show(){
runAsync(new Runnable() {
@Override
public void run() {
mSplashScreen.setVisible(true);
}
});
}
public void close(){
runAsync(new Runnable() {
@Override
public void run() {
mSplashScreen.setVisible(false);
mSplashScreen = null;
}
});
}
}
| 27.484375
| 81
| 0.616259
|
257aba6bdfeff62cf6b6d833ee2dfd3a04905817
| 8,620
|
/**
* NotifyWorkersRequest.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package com.amazonaws.mturk.requester;
public class NotifyWorkersRequest implements java.io.Serializable {
private java.lang.String subject;
private java.lang.String messageText;
private java.lang.String[] workerId;
private java.lang.String[] responseGroup;
public NotifyWorkersRequest() {
}
public NotifyWorkersRequest(
java.lang.String subject,
java.lang.String messageText,
java.lang.String[] workerId,
java.lang.String[] responseGroup) {
this.subject = subject;
this.messageText = messageText;
this.workerId = workerId;
this.responseGroup = responseGroup;
}
/**
* Gets the subject value for this NotifyWorkersRequest.
*
* @return subject
*/
public java.lang.String getSubject() {
return subject;
}
/**
* Sets the subject value for this NotifyWorkersRequest.
*
* @param subject
*/
public void setSubject(java.lang.String subject) {
this.subject = subject;
}
/**
* Gets the messageText value for this NotifyWorkersRequest.
*
* @return messageText
*/
public java.lang.String getMessageText() {
return messageText;
}
/**
* Sets the messageText value for this NotifyWorkersRequest.
*
* @param messageText
*/
public void setMessageText(java.lang.String messageText) {
this.messageText = messageText;
}
/**
* Gets the workerId value for this NotifyWorkersRequest.
*
* @return workerId
*/
public java.lang.String[] getWorkerId() {
return workerId;
}
/**
* Sets the workerId value for this NotifyWorkersRequest.
*
* @param workerId
*/
public void setWorkerId(java.lang.String[] workerId) {
this.workerId = workerId;
}
public java.lang.String getWorkerId(int i) {
return this.workerId[i];
}
public void setWorkerId(int i, java.lang.String _value) {
this.workerId[i] = _value;
}
/**
* Gets the responseGroup value for this NotifyWorkersRequest.
*
* @return responseGroup
*/
public java.lang.String[] getResponseGroup() {
return responseGroup;
}
/**
* Sets the responseGroup value for this NotifyWorkersRequest.
*
* @param responseGroup
*/
public void setResponseGroup(java.lang.String[] responseGroup) {
this.responseGroup = responseGroup;
}
public java.lang.String getResponseGroup(int i) {
return this.responseGroup[i];
}
public void setResponseGroup(int i, java.lang.String _value) {
this.responseGroup[i] = _value;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof NotifyWorkersRequest)) return false;
NotifyWorkersRequest other = (NotifyWorkersRequest) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.subject==null && other.getSubject()==null) ||
(this.subject!=null &&
this.subject.equals(other.getSubject()))) &&
((this.messageText==null && other.getMessageText()==null) ||
(this.messageText!=null &&
this.messageText.equals(other.getMessageText()))) &&
((this.workerId==null && other.getWorkerId()==null) ||
(this.workerId!=null &&
java.util.Arrays.equals(this.workerId, other.getWorkerId()))) &&
((this.responseGroup==null && other.getResponseGroup()==null) ||
(this.responseGroup!=null &&
java.util.Arrays.equals(this.responseGroup, other.getResponseGroup())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getSubject() != null) {
_hashCode += getSubject().hashCode();
}
if (getMessageText() != null) {
_hashCode += getMessageText().hashCode();
}
if (getWorkerId() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(getWorkerId());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getWorkerId(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
if (getResponseGroup() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(getResponseGroup());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getResponseGroup(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(NotifyWorkersRequest.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("http://requester.mturk.amazonaws.com/doc/2007-06-21", "NotifyWorkersRequest"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("subject");
elemField.setXmlName(new javax.xml.namespace.QName("http://requester.mturk.amazonaws.com/doc/2007-06-21", "Subject"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("messageText");
elemField.setXmlName(new javax.xml.namespace.QName("http://requester.mturk.amazonaws.com/doc/2007-06-21", "MessageText"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("workerId");
elemField.setXmlName(new javax.xml.namespace.QName("http://requester.mturk.amazonaws.com/doc/2007-06-21", "WorkerId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("responseGroup");
elemField.setXmlName(new javax.xml.namespace.QName("http://requester.mturk.amazonaws.com/doc/2007-06-21", "ResponseGroup"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
elemField.setMaxOccursUnbounded(true);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| 32.775665
| 138
| 0.606729
|
e6c4012a55f46f14c58c90b6f19287036bccfbd4
| 6,135
|
package com.project.convertedCode.globalNamespace.namespaces.Monolog.namespaces.Handler.classes;
import com.runtimeconverter.runtime.references.ReferenceContainer;
import com.runtimeconverter.runtime.passByReference.PassByReferenceArgs;
import com.runtimeconverter.runtime.references.BasicReferenceContainer;
import com.runtimeconverter.runtime.classes.RuntimeClassBase;
import com.runtimeconverter.runtime.RuntimeEnv;
import com.runtimeconverter.runtime.ZVal;
import com.runtimeconverter.runtime.reflection.ReflectionClassData;
import com.project.convertedCode.globalNamespace.namespaces.Monolog.namespaces.Handler.classes.AbstractHandler;
import com.runtimeconverter.runtime.annotations.ConvertedParameter;
import com.runtimeconverter.runtime.arrays.ZPair;
import java.lang.invoke.MethodHandles;
import com.runtimeconverter.runtime.nativeFunctions.runtime.function_call_user_func;
import com.runtimeconverter.runtime.classes.NoConstructor;
import com.runtimeconverter.runtime.annotations.ConvertedMethod;
import com.runtimeconverter.runtime.passByReference.RuntimeArgsWithInfo;
import static com.runtimeconverter.runtime.ZVal.toObjectR;
import static com.runtimeconverter.runtime.ZVal.assignParameter;
/*
Converted with The Runtime Converter (runtimeconverter.com)
vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php
*/
public abstract class AbstractProcessingHandler extends AbstractHandler {
public AbstractProcessingHandler(RuntimeEnv env, Object... args) {
super(env);
if (this.getClass() == AbstractProcessingHandler.class) {
this.__construct(env, args);
}
}
public AbstractProcessingHandler(NoConstructor n) {
super(n);
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "record", typeHint = "array")
public Object handle(RuntimeEnv env, Object... args) {
ReferenceContainer record = new BasicReferenceContainer(assignParameter(args, 0, false));
if (!ZVal.isTrue(
env.callMethod(
this, "isHandling", AbstractProcessingHandler.class, record.getObject()))) {
return ZVal.assign(false);
}
record.setObject(this.processRecord(env, record.getObject()));
record.arrayAccess(env, "formatted")
.set(
env.callMethod(
env.callMethod(
this, "getFormatter", AbstractProcessingHandler.class),
"format",
AbstractProcessingHandler.class,
record.getObject()));
env.callMethod(this, "write", AbstractProcessingHandler.class, record.getObject());
return ZVal.assign(
ZVal.strictEqualityCheck(
false,
"===",
toObjectR(this).accessProp(this, env).name("bubble").value()));
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "record", typeHint = "array")
protected Object processRecord(RuntimeEnv env, Object... args) {
Object record = assignParameter(args, 0, false);
Object processor = null;
if (toObjectR(this).accessProp(this, env).name("processors").getBool()) {
for (ZPair zpairResult763 :
ZVal.getIterable(
toObjectR(this).accessProp(this, env).name("processors").value(),
env,
true)) {
processor = ZVal.assign(zpairResult763.getValue());
record =
function_call_user_func
.f
.env(env)
.addReferenceArgs(new RuntimeArgsWithInfo(args, this))
.call(processor, record)
.value();
}
}
return ZVal.assign(record);
}
public static final Object CONST_class = "Monolog\\Handler\\AbstractProcessingHandler";
// Runtime Converter Internals
// RuntimeStaticCompanion contains static methods
// RequestStaticProperties contains static (per-request) properties
// ReflectionClassData contains php reflection data used by the runtime library
public static class RuntimeStaticCompanion extends AbstractHandler.RuntimeStaticCompanion {
private static final MethodHandles.Lookup staticCompanionLookup = MethodHandles.lookup();
}
public static final RuntimeStaticCompanion runtimeStaticObject = new RuntimeStaticCompanion();
private static final ReflectionClassData runtimeConverterReflectionData =
ReflectionClassData.builder()
.setName("Monolog\\Handler\\AbstractProcessingHandler")
.setLookup(
AbstractProcessingHandler.class,
MethodHandles.lookup(),
RuntimeStaticCompanion.staticCompanionLookup)
.setLocalProperties("bubble", "formatter", "level", "processors")
.setFilename(
"vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php")
.addInterface("Monolog\\Handler\\HandlerInterface")
.addExtendsClass("Monolog\\Handler\\AbstractHandler")
.get();
@Override
public ReflectionClassData getRuntimeConverterReflectionData() {
return runtimeConverterReflectionData;
}
@Override
public Object converterRuntimeCallExtended(
RuntimeEnv env,
String method,
Class<?> caller,
PassByReferenceArgs passByReferenceArgs,
Object... args) {
return RuntimeClassBase.converterRuntimeCallExtendedWithDataStatic(
this,
runtimeConverterReflectionData,
env,
method,
caller,
passByReferenceArgs,
args);
}
}
| 42.604167
| 111
| 0.633904
|
954ab77fbf6599bc76eff93b6b1953bf09e82c43
| 904
|
package org.jeecg.modules.salary.service;
import org.jeecg.modules.salary.entity.CostManagement;
import com.baomidou.mybatisplus.extension.service.IService;
import org.springframework.http.ResponseEntity;
import java.util.List;
/**
* @Description: 成本管理
* @Author: jeecg-boot
* @Date: 2020-08-13
* @Version: V1.0
*/
public interface ICostManagementService extends IService<CostManagement> {
/**
* 成本管理插入姓名
*/
public void costInsert();
/**
* 更新资金成本
*/
public void costUpdate();
/**
* 更新利润
*/
public void profitUpdate();
/**
* 报销取整
*/
public void intReimbursement();
/**
* @param ids
* @return
*/
ResponseEntity<byte[]> exportLand2ndClassIndex(String ids);
public List<CostManagement> queryAllClassIndex(List<CostManagement> list);
public List<CostManagement> queryBankCard(String id);
}
| 18.833333
| 78
| 0.658186
|
1ca3f2569e461312464520854ab911016266a60b
| 5,365
|
/******************************************************************
* Copyright (C) 2002-2005 Andrew Girow. All rights reserved. *
* ---------------------------------------------------------------*
* This software is published under the terms of the TinyLine *
* License, a copy of which has been included with this *
* distribution in the TINYLINE_LICENSE.TXT file. *
* *
* For more information on the TinyLine, *
* please see <http://www.tinyline.com/>. *
*****************************************************************/
package com.tinyline.app;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventTarget;
/**
* The <tt>SVGEvent</tt> class is used to provide contextual information
* about an event to the handler processing the event.
* <p>
* SVGT 1.1 only allows interactivity with declarative animation.
* The list of event-symbols available for a given event-base element
* is the list of event attributes available for the given element as
* defined by the SVG DTD, with the one difference that the leading
* 'on' is removed from the event name (i.e., the animation event name
* is 'click', not 'onclick').
* <p>
* @author Andrew Girow
* @version 1.9
*/
public class SVGEvent implements Event
{
/** The Event Names */
public static String [] EVENT_NAMES =
{
"animate",
"begin",
"click",
"end",
"error",
"focushide",
"focusin",
"focusnext",
"focusout",
"focuspressed",
"focusprev",
"focusshow",
"load",
"origview",
"pauseresume",
"quality",
"repeat",
"scroll",
"unload",
"update",
"zoom"
};
/** Internal Event. Occurs when an element is animated. */
public static final int EVENT_ANIMATE = 0;
/** Occurs when an animation element begins. */
public static final int EVENT_BEGIN = 1;
/** Occurs when the pointing device button is clicked over an element. */
public static final int EVENT_CLICK = 2;
/** Occurs when an animation element ends. */
public static final int EVENT_END = 3;
/** The error event occurs when an element does not load properly
* or when an error occurs during script execution. */
public static final int EVENT_ERROR = 4;
/** Occurs when a list of linked elements is being hided. */
public static final int EVENT_FOCUSHIDE = 5;
/** Occurs when an element receives focus. */
public static final int EVENT_FOCUSIN = 6;
/** Occurs when an focus is being shifted to the next linked element. */
public static final int EVENT_FOCUSNEXT = 7;
/** Occurs when an element loses focus. */
public static final int EVENT_FOCUSOUT = 8;
/** Occurs when an focus is being shifted to the previous linked element. */
public static final int EVENT_FOCUSPRESSED = 9;
/** Occurs when an focus is being shifted to the previous linked element. */
public static final int EVENT_FOCUSPREV = 10;
/** Occurs when a list of linked elements is being showed. */
public static final int EVENT_FOCUSSHOW = 11;
/** The event is triggered at the point at which the user agent
* has fully parsed the element and its descendants and is ready
* to act appropriately upon that element, such as being ready
* to render the element to the target device. */
public static final int EVENT_LOAD = 12;
/** Occurs when a document view is being returned to the original one. */
public static final int EVENT_ORIGVIEW = 13;
/** Occurs when animations are being paused or resumed. */
public static final int EVENT_PAUSERESUME = 14;
/** Occurs when an antialising is being switched on or off. */
public static final int EVENT_QUALITY = 15;
/** Occurs when an animation element repeats. */
public static final int EVENT_REPEAT = 16;
/** Occurs when a document view is being shifted along the
* X or Y or both axis */
public static final int EVENT_SCROLL = 17;
/** The unload event occurs when the DOM implementation
* removes a document from a window or frame. */
public static final int EVENT_UNLOAD = 18;
/** Internal Event. Occurs when an element is updated. */
public static final int EVENT_UPDATE = 19;
/** Occurs when the zoom level of a document view is being changed. */
public static final int EVENT_ZOOM = 20;
/** The unknown event. */
public static final int EVENT_UNKNOWN = 21;
/** <b>uDOM:</b> Returns the event type */
public String getType()
{
if(id >= EVENT_UNKNOWN)
{
return "unknown";
}
return EVENT_NAMES[id];
}
/** <b>uDOM:</b> Returns the current EventTarget to which the event was originally dispatched. */
public EventTarget getCurrentTarget()
{
return eventTarget;
}
/**
* Creates a new <tt>SVGEvent</tt> object.
* @param id The event type.
* @param data The event data.
*/
public SVGEvent(int id, Object data)
{
this.id = id;
this.data = data;
}
/** The event type */
public int id;
/** The event data */
public Object data;
/** The event target */
EventTarget eventTarget;
/** The next event */
SVGEvent next;
}
| 34.612903
| 99
| 0.618826
|
47cbf1abc3301c9c2b4af68c1340ebd80cab1533
| 562
|
import java.util.Scanner;
/**
* Created by Atanas on 17/02/2017.
*/
public class Test {
public static void main(String[] args) {
//for (int i = 0; i < 26; i++) {
// char upper = (char) ('A' + i);
// char lower = (char) ('a' + i);
// System.out.println(upper +" " + lower);
//}
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());
for (char i = 'a'; i <(char)('a' + n) ; i++) {
System.out.println(i);
}
}
}
| 25.545455
| 55
| 0.450178
|
42379c78544428dc2b0064eee9b5e8a3f1e6ebd1
| 136
|
package site.hanschen.pretty.widget;
/**
* @author HansChen
*/
public interface FragmentBackHandler {
boolean onBackPressed();
}
| 15.111111
| 38
| 0.727941
|
b29d069380149776532d0c1f81580f8ada30bbe4
| 719
|
package com.softplan.apigerenciarprocessos.modules.usuarios.entities;
import java.io.Serializable;
public class AuthenticationRequest implements Serializable {
private static final long serialVersionUID = 1L;
private String email;
private String senha;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
//need default constructor for JSON Parsing
public AuthenticationRequest(){}
public AuthenticationRequest(String email, String senha) {
this.setEmail(email);
this.setSenha(senha);
}
}
| 19.972222
| 69
| 0.709318
|
b298ca31bcb60b5af9ffc05d57aaa562d16e4f65
| 126
|
package com.sachinvarma.betterdoctor.model;
public class SpecialisationModel {
public String uid;
public String actor;
}
| 18
| 43
| 0.793651
|
4db33447f5aa342a0094a68fb569e43b1ca62953
| 9,691
|
/*
* 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 test.org.apache.commons.math.geometry;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.util.Locale;
import test.org.apache.commons.math.exception.MathParseException;
import test.org.apache.commons.math.util.CompositeFormat;
/**
* Formats a vector in components list format "{x; y; ...}".
* <p>The prefix and suffix "{" and "}" and the separator "; " can be replaced by
* any user-defined strings. The number format for components can be configured.</p>
* <p>White space is ignored at parse time, even if it is in the prefix, suffix
* or separator specifications. So even if the default separator does include a space
* character that is used at format time, both input string "{1;1;1}" and
* " { 1 ; 1 ; 1 } " will be parsed without error and the same vector will be
* returned. In the second case, however, the parse position after parsing will be
* just after the closing curly brace, i.e. just before the trailing space.</p>
*
* @param <S> Type of the space.
* @version $Id$
* @since 3.0
*/
public abstract class VectorFormat<S extends Space> {
/** The default prefix: "{". */
public static final String DEFAULT_PREFIX = "{";
/** The default suffix: "}". */
public static final String DEFAULT_SUFFIX = "}";
/** The default separator: ", ". */
public static final String DEFAULT_SEPARATOR = "; ";
/** Prefix. */
private final String prefix;
/** Suffix. */
private final String suffix;
/** Separator. */
private final String separator;
/** Trimmed prefix. */
private final String trimmedPrefix;
/** Trimmed suffix. */
private final String trimmedSuffix;
/** Trimmed separator. */
private final String trimmedSeparator;
/** The format used for components. */
private final NumberFormat format;
/**
* Create an instance with default settings.
* <p>The instance uses the default prefix, suffix and separator:
* "{", "}", and "; " and the default number format for components.</p>
*/
protected VectorFormat() {
this(DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_SEPARATOR,
CompositeFormat.getDefaultNumberFormat());
}
/**
* Create an instance with a custom number format for components.
* @param format the custom format for components.
*/
protected VectorFormat(final NumberFormat format) {
this(DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_SEPARATOR, format);
}
/**
* Create an instance with custom prefix, suffix and separator.
* @param prefix prefix to use instead of the default "{"
* @param suffix suffix to use instead of the default "}"
* @param separator separator to use instead of the default "; "
*/
protected VectorFormat(final String prefix, final String suffix,
final String separator) {
this(prefix, suffix, separator, CompositeFormat.getDefaultNumberFormat());
}
/**
* Create an instance with custom prefix, suffix, separator and format
* for components.
* @param prefix prefix to use instead of the default "{"
* @param suffix suffix to use instead of the default "}"
* @param separator separator to use instead of the default "; "
* @param format the custom format for components.
*/
protected VectorFormat(final String prefix, final String suffix,
final String separator, final NumberFormat format) {
this.prefix = prefix;
this.suffix = suffix;
this.separator = separator;
trimmedPrefix = prefix.trim();
trimmedSuffix = suffix.trim();
trimmedSeparator = separator.trim();
this.format = format;
}
/**
* Get the set of locales for which point/vector formats are available.
* <p>This is the same set as the {@link NumberFormat} set.</p>
* @return available point/vector format locales.
*/
public static Locale[] getAvailableLocales() {
return NumberFormat.getAvailableLocales();
}
/**
* Get the format prefix.
* @return format prefix.
*/
public String getPrefix() {
return prefix;
}
/**
* Get the format suffix.
* @return format suffix.
*/
public String getSuffix() {
return suffix;
}
/**
* Get the format separator between components.
* @return format separator.
*/
public String getSeparator() {
return separator;
}
/**
* Get the components format.
* @return components format.
*/
public NumberFormat getFormat() {
return format;
}
/**
* Formats a {@link Vector} object to produce a string.
* @param vector the object to format.
* @return a formatted string.
*/
public String format(Vector<S> vector) {
return format(vector, new StringBuffer(), new FieldPosition(0)).toString();
}
/**
* Formats a {@link Vector} object to produce a string.
* @param vector the object to format.
* @param toAppendTo where the text is to be appended
* @param pos On input: an alignment field, if desired. On output: the
* offsets of the alignment field
* @return the value passed in as toAppendTo.
*/
public abstract StringBuffer format(Vector<S> vector,
StringBuffer toAppendTo, FieldPosition pos);
/**
* Formats the coordinates of a {@link Vector} to produce a string.
* @param toAppendTo where the text is to be appended
* @param pos On input: an alignment field, if desired. On output: the
* offsets of the alignment field
* @param coordinates coordinates of the object to format.
* @return the value passed in as toAppendTo.
*/
protected StringBuffer format(StringBuffer toAppendTo, FieldPosition pos,
double ... coordinates) {
pos.setBeginIndex(0);
pos.setEndIndex(0);
// format prefix
toAppendTo.append(prefix);
// format components
for (int i = 0; i < coordinates.length; ++i) {
if (i > 0) {
toAppendTo.append(separator);
}
CompositeFormat.formatDouble(coordinates[i], format, toAppendTo, pos);
}
// format suffix
toAppendTo.append(suffix);
return toAppendTo;
}
/**
* Parses a string to produce a {@link Vector} object.
* @param source the string to parse
* @return the parsed {@link Vector} object.
* @throws MathParseException if the beginning of the specified string
* cannot be parsed.
*/
public abstract Vector<S> parse(String source) throws MathParseException;
/**
* Parses a string to produce a {@link Vector} object.
* @param source the string to parse
* @param pos input/ouput parsing parameter.
* @return the parsed {@link Vector} object.
*/
public abstract Vector<S> parse(String source, ParsePosition pos);
/**
* Parses a string to produce an array of coordinates.
* @param dimension dimension of the space
* @param source the string to parse
* @param pos input/ouput parsing parameter.
* @return coordinates array.
*/
protected double[] parseCoordinates(int dimension, String source, ParsePosition pos) {
int initialIndex = pos.getIndex();
double[] coordinates = new double[dimension];
// parse prefix
CompositeFormat.parseAndIgnoreWhitespace(source, pos);
if (!CompositeFormat.parseFixedstring(source, trimmedPrefix, pos)) {
return null;
}
for (int i = 0; i < dimension; ++i) {
// skip whitespace
CompositeFormat.parseAndIgnoreWhitespace(source, pos);
// parse separator
if (i > 0) {
if (!CompositeFormat.parseFixedstring(source, trimmedSeparator, pos)) {
return null;
}
}
// skip whitespace
CompositeFormat.parseAndIgnoreWhitespace(source, pos);
// parse coordinate
Number c = CompositeFormat.parseNumber(source, format, pos);
if (c == null) {
// invalid coordinate
// set index back to initial, error index should already be set
pos.setIndex(initialIndex);
return null;
}
// store coordinate
coordinates[i] = c.doubleValue();
}
// parse suffix
CompositeFormat.parseAndIgnoreWhitespace(source, pos);
if (!CompositeFormat.parseFixedstring(source, trimmedSuffix, pos)) {
return null;
}
return coordinates;
}
}
| 33.302405
| 90
| 0.630276
|
56ac0c490f73d56c256efea5c407266cd3e7faeb
| 3,158
|
package com.ruoyi.project.production.filesource.controller;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.framework.jwt.JwtUtil;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.production.filesource.domain.FileSourceInfo;
import com.ruoyi.project.production.filesource.service.IFileSourceInfoService;
import com.ruoyi.project.system.user.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
/**
* 文件素材管理
*
* @author zqm
* @date 2019-05-09
*/
@Controller
@RequestMapping("/iso/fileSource")
public class FileSourceInfoController extends BaseController {
private String prefix = "production/fileSourceInfo";
@Autowired
private IFileSourceInfoService fileSourceService;
/**
* 查看文件列表
*/
@PostMapping("/list")
@ResponseBody
public TableDataInfo list(FileSourceInfo fileSourceInfo) {
startPage();
List<FileSourceInfo> list = fileSourceService.selectFileSourceInfoList(fileSourceInfo);
return getDataTable(list);
}
/**
* 新增文件管理
*/
@PostMapping("/add")
@ResponseBody
public AjaxResult addSave(@RequestParam("avatarfile") MultipartFile file,
@RequestParam("saveType") int saveType) {
try {
return toAjax(fileSourceService.saveFileInfo(file,saveType));
} catch (BusinessException e) {
return error(e.getMessage());
} catch (Exception e){
return error("上传失败");
}
}
/**
* 修改文件名
*/
@GetMapping("/editFileName")
public String editFileName(Integer id, String fileName, ModelMap map){
map.put("id",id);
map.put("fileName",fileName.substring(0,fileName.lastIndexOf(".")));
User user = JwtUtil.getUser();
if (UserConstants.LANGUAGE_EN.equals(user.getLangVersion())) {
return prefix + "/editFileNameEn";
}
return prefix + "/editFileName";
}
/**
* 修改保存文件名
*/
@PostMapping("/saveFileName")
@ResponseBody
public AjaxResult saveFileName(FileSourceInfo fileSourceInfo){
try {
return toAjax(fileSourceService.saveFileName(fileSourceInfo));
} catch (IOException e) {
return error();
}
}
/**
* 检验文件名是否重复
*/
@PostMapping("/checkFileNameNameUnique")
@ResponseBody
public String checkFileNameNameUnique(FileSourceInfo fileSourceInfo) {
return fileSourceService.checkFileNameNameUnique(fileSourceInfo);
}
/**
* 删除文件
*/
@PostMapping("/remove")
@ResponseBody
public AjaxResult remove(String ids) {
return toAjax(fileSourceService.deleteFileInfoByIds(ids));
}
}
| 28.709091
| 95
| 0.682077
|
5ae012afc9d2126f563be451b5efb9e3c0808827
| 1,213
|
package de.hsh.drangmeister.sepgp.gp.operator.crossover;
import de.hsh.drangmeister.sepgp.gp.Gene;
import de.hsh.drangmeister.sepgp.gp.Genome;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class SinglePointCrossover implements ICrossover {
private int maxGenomeSize;
private Random random;
public SinglePointCrossover(int maxGenomeSize) {
this.maxGenomeSize = maxGenomeSize;
this.random = new Random();
}
@Override
public Genome crossover(Genome g1, Genome g2) {
boolean successful = false;
List<Gene> genes = new ArrayList<>();
while (!successful) {
int point1 = random.nextInt(g1.getGenes().size());
int point2 = random.nextInt(g2.getGenes().size());
if (point1 + (g2.getGenes().size() - point2) > maxGenomeSize) {
continue;
}
for (int i = 0; i < point1; i++)
genes.add(g1.getGenes().get(i));
for (int i = point2; i < g2.getGenes().size(); i++)
genes.add(g2.getGenes().get(i));
successful = true;
}
return new Genome(genes, List.of(g1, g2));
}
}
| 26.955556
| 75
| 0.596867
|
242cb76e9c596b9649d2889b5dbfe186beb626a2
| 8,084
|
/*
* Copyright 2017-2020 Rudy De Busscher (https://www.atbash.be)
*
* 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.atbash.ee.security.octopus.keys.writer.encoder;
import be.atbash.ee.security.octopus.config.JwtSupportConfiguration;
import be.atbash.ee.security.octopus.keys.AtbashKey;
import be.atbash.ee.security.octopus.keys.generator.ECGenerationParameters;
import be.atbash.ee.security.octopus.keys.generator.KeyGenerator;
import be.atbash.ee.security.octopus.keys.generator.RSAGenerationParameters;
import be.atbash.ee.security.octopus.keys.selector.AsymmetricPart;
import be.atbash.ee.security.octopus.keys.selector.filter.AsymmetricPartKeyFilter;
import be.atbash.ee.security.octopus.keys.writer.KeyEncoderParameters;
import be.atbash.ee.security.octopus.nimbus.jwk.KeyType;
import be.atbash.ee.security.octopus.nimbus.util.KeyUtils;
import be.atbash.util.exception.AtbashUnexpectedException;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import javax.crypto.SecretKey;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Calendar;
import java.util.List;
/**
*
*/
public class KeyStoreEncoder implements KeyEncoder {
private JwtSupportConfiguration configuration;
public KeyStoreEncoder() {
configuration = JwtSupportConfiguration.getInstance();
}
@Override
public byte[] encodeKey(AtbashKey atbashKey, KeyEncoderParameters parameters) throws IOException {
KeyStore keyStore = parameters.getKeyStore();
try {
if (atbashKey.getSecretKeyType().getAsymmetricPart() == AsymmetricPart.PRIVATE) {
PrivateKey key = (PrivateKey) atbashKey.getKey();
X509Certificate certificate = generateCertificate(KeyUtils.getPublicKey(atbashKey), key, atbashKey.getSecretKeyType().getKeyType());
KeyStore.Entry entry = new KeyStore.PrivateKeyEntry(key, new X509Certificate[]{certificate});
keyStore.setEntry(atbashKey.getKeyId(), entry, new KeyStore.PasswordProtection(parameters.getKeyPassword()));
}
if (atbashKey.getSecretKeyType().getAsymmetricPart() == AsymmetricPart.PUBLIC) {
PublicKey key = (PublicKey) atbashKey.getKey();
X509Certificate certificate = generateCertificate(key, null, atbashKey.getSecretKeyType().getKeyType());
KeyStore.Entry entry = new KeyStore.TrustedCertificateEntry(certificate);
keyStore.setEntry(atbashKey.getKeyId(), entry, null);
}
if (atbashKey.getSecretKeyType().getAsymmetricPart() == AsymmetricPart.SYMMETRIC) {
SecretKey key = (SecretKey) atbashKey.getKey();
keyStore.setKeyEntry(atbashKey.getKeyId(), key, parameters.getKeyPassword(), null);
}
} catch (KeyStoreException e) {
throw new AtbashUnexpectedException(e);
}
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try {
keyStore.store(stream, parameters.getFilePassword());
} catch (KeyStoreException | NoSuchAlgorithmException | CertificateException e) {
throw new AtbashUnexpectedException(e);
}
return stream.toByteArray();
}
private X509Certificate generateCertificate(PublicKey publicKey, PrivateKey privateKey, KeyType keyType) {
try {
Calendar start = Calendar.getInstance();
Calendar expiry = Calendar.getInstance();
expiry.add(Calendar.YEAR, 1);
X500Name name = new X500Name(configuration.getNameCertificateKeyStore());
X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(name, BigInteger.ONE,
start.getTime(), expiry.getTime(), name, SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()));
if (privateKey == null) {
privateKey = createSigningKey(keyType); // this is the private key to sign the certificate. Has nothing to do with the Certificate and the public key.
}
ContentSigner signer = new JcaContentSignerBuilder(getCertificateSignatureAlgorithm(keyType)).setProvider(new BouncyCastleProvider()).build(privateKey);
X509CertificateHolder holder = certificateBuilder.build(signer);
return new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider()).getCertificate(holder);
} catch (GeneralSecurityException | OperatorCreationException ex) {
throw new AtbashUnexpectedException(ex);
}
}
private String getCertificateSignatureAlgorithm(KeyType keyType) {
String result;
switch (keyType.getValue()) {
case "RSA":
result = configuration.getCertificateSignatureAlgorithmRSA();
break;
case "EC":
result = configuration.getCertificateSignatureAlgorithmEC();
break;
default:
throw new IllegalStateException("Unexpected value: " + keyType.getValue());
}
return result;
}
private PrivateKey createSigningKey(KeyType keyType) {
PrivateKey result;
switch (keyType.getValue()) {
case "RSA":
result = createSigningKeyRSA();
break;
case "EC":
result = createSigningKeyEC();
break;
default:
throw new IllegalStateException("Unexpected value: " + keyType.getValue());
}
return result;
}
private PrivateKey createSigningKeyRSA() {
RSAGenerationParameters generationParameters = new RSAGenerationParameters.RSAGenerationParametersBuilder()
.withKeyId("cert-signing")
.build();
KeyGenerator generator = new KeyGenerator();
List<AtbashKey> atbashKeys = generator.generateKeys(generationParameters);
AsymmetricPartKeyFilter keyFilter = new AsymmetricPartKeyFilter(AsymmetricPart.PRIVATE);
List<AtbashKey> privateKeys = keyFilter.filter(atbashKeys);
// TODO should we be on the safe side and check we have just 1 private key.
return (PrivateKey) privateKeys.get(0).getKey();
}
private PrivateKey createSigningKeyEC() {
ECGenerationParameters generationParameters = new ECGenerationParameters.ECGenerationParametersBuilder()
.withKeyId("cert-signing")
.withCurveName("P-256")
.build();
KeyGenerator generator = new KeyGenerator();
List<AtbashKey> atbashKeys = generator.generateKeys(generationParameters);
AsymmetricPartKeyFilter keyFilter = new AsymmetricPartKeyFilter(AsymmetricPart.PRIVATE);
List<AtbashKey> privateKeys = keyFilter.filter(atbashKeys);
// TODO should we be on the safe side and check we have just 1 private key.
return (PrivateKey) privateKeys.get(0).getKey();
}
}
| 44.174863
| 166
| 0.701014
|
47fc7a9c5354cb78aa4541a305dd294ad2d807ce
| 11,985
|
package eu.fbk.knowledgestore.datastore;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import com.google.common.base.Function;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.openrdf.model.URI;
import org.openrdf.rio.RDFFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import eu.fbk.knowledgestore.data.Data;
import eu.fbk.knowledgestore.data.Record;
import eu.fbk.knowledgestore.data.Stream;
import eu.fbk.knowledgestore.data.XPath;
import eu.fbk.knowledgestore.internal.Util;
import eu.fbk.knowledgestore.internal.rdf.RDFUtil;
import eu.fbk.knowledgestore.runtime.Files;
import eu.fbk.knowledgestore.vocabulary.KS;
/**
* A {@code DataStore} implementations that keeps all data in memory, with persistence provided by
* loading / saving data to file.
* <p>
* This class realizes a low-performance, functional implementation of the {@code DataStore}
* component. Record data is loaded at startup from a configurable file and then indexed in
* memory; data is written back at shutdown. Each (read-write) transaction works on its copy of
* data, and changes are merged back in the component upon successful commit, although data is
* written back to disk only at shutdown.
* </p>
*/
public class MemoryDataStore implements DataStore {
private static final Logger LOGGER = LoggerFactory.getLogger(MemoryDataStore.class);
private static final String PATH_DEFAULT = "datastore.ttl";
private Map<URI, Map<URI, Record>> tables;
private int revision;
private boolean initialized;
private boolean closed;
private final FileSystem fileSystem;
private final Path filePath;
/**
* Creates a new {@code MemoryDataStore} instance loading/storing data in the file at the path
* and file system specified.
*
* @param fileSystem
* the filesystem containing the file where to read/write data
* @param path
* the path of the file where to read/write data, possibly relative to the file
* system working directory; if null defaults to {@code datastore.ttl}
*/
public MemoryDataStore(final FileSystem fileSystem, @Nullable final String path) {
this.fileSystem = Preconditions.checkNotNull(fileSystem);
this.filePath = new Path(MoreObjects.firstNonNull(path, MemoryDataStore.PATH_DEFAULT))
.makeQualified(this.fileSystem); // resolve against working directory
this.tables = Maps.newHashMap();
this.revision = 1;
this.initialized = false;
this.closed = false;
for (final URI supportedType : DataStore.SUPPORTED_TYPES) {
this.tables.put(supportedType, Maps.<URI, Record>newLinkedHashMap());
}
MemoryDataStore.LOGGER.info("{} configured, path={}", this.getClass().getSimpleName(),
this.filePath);
}
@Override
public synchronized void init() throws IOException, IllegalStateException {
Preconditions.checkState(!this.initialized && !this.closed);
this.initialized = true;
InputStream stream = null;
try {
if (this.fileSystem.exists(this.filePath)) {
stream = Files.readWithBackup(this.fileSystem, this.filePath);
final RDFFormat format = RDFFormat.forFileName(this.filePath.getName());
final List<Record> records = Record.decode(
RDFUtil.readRDF(stream, format, null, null, false),
ImmutableSet.of(KS.RESOURCE, KS.MENTION, KS.ENTITY, KS.CONTEXT), false)
.toList();
for (final Record record : records) {
final URI id = Preconditions.checkNotNull(record.getID());
final URI type = Preconditions.checkNotNull(record.getSystemType());
MemoryDataStore.this.tables.get(type).put(id, record);
}
MemoryDataStore.LOGGER.info("{} initialized, {} records loaded", this.getClass()
.getSimpleName(), records.size());
} else {
MemoryDataStore.LOGGER.info("{} initialized, no record loaded", this.getClass()
.getSimpleName());
}
} finally {
Util.closeQuietly(stream);
}
}
@Override
public synchronized DataTransaction begin(final boolean readOnly) throws IOException,
IllegalStateException {
Preconditions.checkState(this.initialized && !this.closed);
return new MemoryDataTransaction(readOnly);
}
@Override
public synchronized void close() {
if (this.closed) {
return;
}
this.closed = true;
}
@Override
public String toString() {
return this.getClass().getSimpleName();
}
private synchronized void update(final Map<URI, Map<URI, Record>> tables, final int revision)
throws IOException {
if (this.revision != revision) {
throw new IOException("Commit failed due to concurrent modifications " + this.revision
+ ", " + revision);
}
OutputStream stream = null;
try {
stream = Files.writeWithBackup(this.fileSystem, this.filePath);
final List<Record> records = Lists.newArrayList();
for (final URI type : tables.keySet()) {
records.addAll(tables.get(type).values());
}
final RDFFormat format = RDFFormat.forFileName(this.filePath.getName());
RDFUtil.writeRDF(stream, format, Data.getNamespaceMap(), null,
Record.encode(Stream.create(records), ImmutableSet.<URI>of()));
++this.revision;
this.tables = tables;
MemoryDataStore.LOGGER.info("MemoryDataStore updated, {} records persisted",
records.size());
} catch (final Throwable ex) {
MemoryDataStore.LOGGER.error("MemoryDataStore update failed", ex);
} finally {
Util.closeQuietly(stream);
}
}
private class MemoryDataTransaction implements DataTransaction {
private final Map<URI, Map<URI, Record>> tables;
private final int revision;
private final boolean readOnly;
private boolean ended;
MemoryDataTransaction(final boolean readOnly) {
Map<URI, Map<URI, Record>> tables = MemoryDataStore.this.tables;
if (!readOnly) {
tables = Maps.newHashMap();
for (final Map.Entry<URI, Map<URI, Record>> entry : MemoryDataStore.this.tables
.entrySet()) {
tables.put(entry.getKey(), Maps.newLinkedHashMap(entry.getValue()));
}
}
this.tables = tables;
this.revision = MemoryDataStore.this.revision;
this.readOnly = readOnly;
this.ended = false;
}
private Map<URI, Record> getTable(final URI type) {
final Map<URI, Record> table = this.tables.get(type);
if (table != null) {
return table;
}
throw new IllegalArgumentException("Unsupported type " + type);
}
private Stream<Record> select(final Map<URI, Record> table,
final Stream<? extends URI> stream) {
return stream.transform(new Function<URI, Record>() {
@Override
public Record apply(final URI id) {
return table.get(id);
}
}, 0);
}
private Stream<Record> filter(final Stream<Record> stream, @Nullable final XPath xpath) {
if (xpath == null) {
return stream;
}
return stream.filter(xpath.asPredicate(), 0);
}
private Stream<Record> project(final Stream<Record> stream,
@Nullable final Iterable<? extends URI> properties) {
final URI[] array = properties == null ? null : Iterables.toArray(properties,
URI.class);
return stream.transform(new Function<Record, Record>() {
@Override
public final Record apply(final Record input) {
final Record result = Record.create(input, true);
if (array != null) {
result.retain(array);
}
return result;
}
}, 0);
}
@Override
public synchronized Stream<Record> lookup(final URI type, final Set<? extends URI> ids,
@Nullable final Set<? extends URI> properties) throws IOException,
IllegalArgumentException, IllegalStateException {
Preconditions.checkState(!this.ended);
final Map<URI, Record> table = this.getTable(type);
return this.project(this.select(table, Stream.create(ids)), properties);
}
@Override
public synchronized Stream<Record> retrieve(final URI type,
@Nullable final XPath condition, @Nullable final Set<? extends URI> properties)
throws IOException, IllegalArgumentException, IllegalStateException {
Preconditions.checkState(!this.ended);
final Map<URI, Record> table = this.getTable(type);
return this.project(this.filter(Stream.create(table.values()), condition), properties);
}
@Override
public synchronized long count(final URI type, @Nullable final XPath condition)
throws IOException, IllegalArgumentException, IllegalStateException {
Preconditions.checkState(!this.ended);
final Map<URI, Record> table = this.getTable(type);
return this.filter(Stream.create(table.values()), condition).count();
}
@Override
public Stream<Record> match(final Map<URI, XPath> conditions,
final Map<URI, Set<URI>> ids, final Map<URI, Set<URI>> properties)
throws IOException, IllegalStateException {
throw new UnsupportedOperationException(); // TODO
}
@Override
public void store(final URI type, final Record record) throws IOException,
IllegalStateException {
Preconditions.checkState(!this.ended);
Preconditions.checkState(!this.readOnly);
Preconditions.checkArgument(record.getID() != null);
final Map<URI, Record> table = this.getTable(type);
table.put(record.getID(), Record.create(record, true));
}
@Override
public void delete(final URI type, final URI id) throws IOException, IllegalStateException {
Preconditions.checkState(!this.ended);
Preconditions.checkState(!this.readOnly);
Preconditions.checkArgument(id != null);
final Map<URI, Record> table = this.getTable(type);
table.remove(id);
}
@Override
public synchronized void end(final boolean commit) throws IOException,
IllegalStateException {
if (!this.ended) {
this.ended = true;
if (commit && !this.readOnly) {
MemoryDataStore.this.update(this.tables, this.revision);
}
}
}
@Override
public String toString() {
return this.getClass().getSimpleName();
}
}
}
| 38.047619
| 100
| 0.613016
|
5e345729620fba83ef78d478c9a04eacd47bb240
| 3,189
|
package org.hypergraphdb.app.owl.model.axioms;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.hypergraphdb.HGHandle;
import org.semanticweb.owlapi.model.AxiomType;
import org.semanticweb.owlapi.model.OWLAnnotation;
import org.semanticweb.owlapi.model.OWLAxiomVisitor;
import org.semanticweb.owlapi.model.OWLAxiomVisitorEx;
import org.semanticweb.owlapi.model.OWLDataPropertyExpression;
import org.semanticweb.owlapi.model.OWLEquivalentDataPropertiesAxiom;
import org.semanticweb.owlapi.model.OWLObjectVisitor;
import org.semanticweb.owlapi.model.OWLObjectVisitorEx;
import org.semanticweb.owlapi.model.OWLSubDataPropertyOfAxiom;
/**
* OWLEquivalentDataPropertiesAxiomHGDB.
*
* @author Thomas Hilpold (CIAO/Miami-Dade County)
* @created Nov 7, 2011
*/
public class OWLEquivalentDataPropertiesAxiomHGDB extends OWLNaryPropertyAxiomHGDB<OWLDataPropertyExpression> implements
OWLEquivalentDataPropertiesAxiom
{
public OWLEquivalentDataPropertiesAxiomHGDB(HGHandle... args)
{
this(new HashSet<HGHandle>(Arrays.asList(args)), Collections.<OWLAnnotation> emptySet());
if (new HashSet<HGHandle>(Arrays.asList(args)).size() != args.length)
throw new IllegalArgumentException();
}
public OWLEquivalentDataPropertiesAxiomHGDB(Set<? extends HGHandle> properties, Collection<? extends OWLAnnotation> annotations)
{
// Set<? extends OWLDataPropertyExpression> properties, Collection<?
// extends OWLAnnotation> annotations
super(properties, annotations);
}
public OWLEquivalentDataPropertiesAxiom getAxiomWithoutAnnotations()
{
if (!isAnnotated())
{
return this;
}
return getOWLDataFactory().getOWLEquivalentDataPropertiesAxiom(getProperties());
}
public OWLEquivalentDataPropertiesAxiom getAnnotatedAxiom(Set<OWLAnnotation> annotations)
{
return getOWLDataFactory().getOWLEquivalentDataPropertiesAxiom(getProperties(), mergeAnnos(annotations));
}
@Override
public boolean equals(Object obj)
{
if (super.equals(obj))
{
return obj instanceof OWLEquivalentDataPropertiesAxiom;
}
return false;
}
public void accept(OWLAxiomVisitor visitor)
{
visitor.visit(this);
}
public void accept(OWLObjectVisitor visitor)
{
visitor.visit(this);
}
public <O> O accept(OWLAxiomVisitorEx<O> visitor)
{
return visitor.visit(this);
}
public <O> O accept(OWLObjectVisitorEx<O> visitor)
{
return visitor.visit(this);
}
public AxiomType<?> getAxiomType()
{
return AxiomType.EQUIVALENT_DATA_PROPERTIES;
}
public Set<OWLSubDataPropertyOfAxiom> asSubDataPropertyOfAxioms()
{
List<OWLDataPropertyExpression> props = new ArrayList<OWLDataPropertyExpression>(getProperties());
Set<OWLSubDataPropertyOfAxiom> axs = new HashSet<OWLSubDataPropertyOfAxiom>();
for (int i = 0; i < props.size() - 1; i++)
{
for (int j = i + 1; j < props.size(); j++)
{
axs.add(getOWLDataFactory().getOWLSubDataPropertyOfAxiom(props.get(i), props.get(j)));
}
}
return axs;
}
}
| 29.803738
| 130
| 0.752901
|
2a0269fc77b5b022f034f4f6e4f1a2d3486c31dd
| 7,284
|
package org.d3ifcool.finpro.core.presenters;
import android.content.Context;
import android.widget.Toast;
import org.d3ifcool.finpro.R;
import org.d3ifcool.finpro.core.helpers.ConnectionHelper;
import org.d3ifcool.finpro.core.interfaces.lists.KoorListView;
import org.d3ifcool.finpro.core.interfaces.objects.KoorView;
import org.d3ifcool.finpro.core.interfaces.works.KoorWorkView;
import org.d3ifcool.finpro.core.models.KoordinatorPa;
import org.d3ifcool.finpro.core.api.ApiClient;
import org.d3ifcool.finpro.core.api.ApiService;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Created by ikhsan ramadhan
* =========================================
* Finpro
* Copyright (C) 3/2/2019.
* All rights reserved
* -----------------------------------------
* Name : Muhamad Ikhsan Ramadhan
* E-mail : ikhsanramadhan28@gmail.com
* Majors : D3 Teknik Informatika 2016
* Campus : Telkom University
* -----------------------------------------
*/
public class KoorPresenter {
private KoorView viewObject;
private KoorListView viewResult;
private KoorWorkView viewEditor;
private ConnectionHelper connectionHelper = new ConnectionHelper();
private Context context;
public void initContext(Context context){
this.context = context;
}
public KoorPresenter(KoorView viewObject) {
this.viewObject = viewObject;
}
public KoorPresenter(KoorListView viewResult) {
this.viewResult = viewResult;
}
public KoorPresenter(KoorWorkView viewEditor) {
this.viewEditor = viewEditor;
}
public void createKoor(String koor_nip , String koor_nama , String koor_kontak, String koor_foto, String koor_email){
if (connectionHelper.isConnected(context)){
viewEditor.showProgress();
ApiService interfaceAdmin = ApiClient.getApiClient().create(ApiService.class);
Call<KoordinatorPa>call = interfaceAdmin.createKoor(koor_nip,koor_nama,koor_kontak,koor_foto,koor_email);
call.enqueue(new Callback<KoordinatorPa>() {
@Override
public void onResponse(Call<KoordinatorPa> call, Response<KoordinatorPa> response) {
viewEditor.hideProgress();
viewEditor.onSucces();
}
@Override
public void onFailure(Call<KoordinatorPa> call, Throwable t) {
viewEditor.hideProgress();
viewEditor.onFailed(t.getMessage());
}
});
} else {
Toast.makeText(context, context.getString(R.string.validate_no_connection), Toast.LENGTH_SHORT).show();
}
}
public void updateKoor(String username, String koor_nip, String koor_nama, String koor_kode, String koor_kontak, String koor_email){
if (connectionHelper.isConnected(context)){
viewEditor.showProgress();
ApiService interfaceAdmin = ApiClient.getApiClient().create(ApiService.class);
Call<KoordinatorPa>call = interfaceAdmin.updateKoor(username, koor_nip, koor_nama, koor_kode, koor_kontak,koor_email);
call.enqueue(new Callback<KoordinatorPa>() {
@Override
public void onResponse(Call<KoordinatorPa> call, Response<KoordinatorPa> response) {
viewEditor.hideProgress();
viewEditor.onSucces();
}
@Override
public void onFailure(Call<KoordinatorPa> call, Throwable t) {
viewEditor.hideProgress();
viewEditor.onFailed(t.getMessage());
}
});
} else {
Toast.makeText(context, context.getString(R.string.validate_no_connection), Toast.LENGTH_SHORT).show();
}
}
public void getKoor(){
if (connectionHelper.isConnected(context)){
viewResult.showProgress();
ApiService interfaceAdmin = ApiClient.getApiClient().create(ApiService.class);
Call<List<KoordinatorPa>> call = interfaceAdmin.getKoor();
call.enqueue(new Callback<List<KoordinatorPa>>() {
@Override
public void onResponse(Call<List<KoordinatorPa>> call, Response<List<KoordinatorPa>> response) {
viewResult.hideProgress();
if (response.body() != null && response.isSuccessful()) {
viewResult.onGetListKoor(response.body());
} else {
viewResult.isEmptyListKoor();
}
}
@Override
public void onFailure(Call<List<KoordinatorPa>> call, Throwable t) {
viewResult.hideProgress();
viewResult.onFailed(t.getMessage());
}
});
} else {
Toast.makeText(context, context.getString(R.string.validate_no_connection), Toast.LENGTH_SHORT).show();
}
}
public void deleteKoor(String koor_nip){
if (connectionHelper.isConnected(context)){
viewEditor.showProgress();
ApiService apiInterfaceKoorPa = ApiClient.getApiClient().create(ApiService.class);
Call<KoordinatorPa>call = apiInterfaceKoorPa.deleteKoor(koor_nip);
call.enqueue(new Callback<KoordinatorPa>() {
@Override
public void onResponse(Call<KoordinatorPa> call, Response<KoordinatorPa> response) {
viewEditor.hideProgress();
viewEditor.onSucces();
}
@Override
public void onFailure(Call<KoordinatorPa> call, Throwable t) {
viewEditor.hideProgress();
viewEditor.onFailed(t.getMessage());
}
});
} else {
Toast.makeText(context, context.getString(R.string.validate_no_connection), Toast.LENGTH_SHORT).show();
}
}
public void getKoorByParameter(String koor_nip){
if (connectionHelper.isConnected(context)){
ApiService apiInterfaceKoorPa = ApiClient.getApiClient().create(ApiService.class);
Call<KoordinatorPa> call = apiInterfaceKoorPa.getKoorByParameter(koor_nip);
call.enqueue(new Callback<KoordinatorPa>() {
@Override
public void onResponse(Call<KoordinatorPa> call, Response<KoordinatorPa> response) {
viewObject.hideProgress();
if (response.body() != null && response.isSuccessful()) {
viewObject.onGetObjectKoor(response.body());
} else {
viewObject.isEmptyObjectKoor();
}
}
@Override
public void onFailure(Call<KoordinatorPa> call, Throwable t) {
viewObject.hideProgress();
viewObject.onFailed(t.getLocalizedMessage());
}
});
} else {
Toast.makeText(context, context.getString(R.string.validate_no_connection), Toast.LENGTH_SHORT).show();
}
}
}
| 36.238806
| 136
| 0.597474
|
daf5bee8bc992778d1637b5a80a30bdfd8cf945d
| 548
|
package Interpolator;
public class ImageBSplineInterpolator extends ImageBicubicInterpolator {
public ImageBSplineInterpolator(int targetWidth, int targetHeight) {
super(targetWidth, targetHeight);
}
@Override
protected double getYByFunction(double x) {
// B样条函数的基函数计算过程。
double absoluteX = Math.abs(x);
if (absoluteX <= 1) {
return 2.0 / 3 + 0.5 * Math.pow(absoluteX, 3) - Math.pow(x, 2);
} else if (absoluteX <= 2) {
return 1.0 / 6 * Math.pow(2 - absoluteX, 3);
} else {
return 0;
}
}
}
| 24.909091
| 72
| 0.64781
|
f6dd6bbc7d4da22975fee9594067160f6604b8e8
| 10,298
|
/*
* Copyright (c) 2011-2019, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package boofcv.app;
import boofcv.abst.fiducial.calib.ConfigGridDimen;
import boofcv.app.calib.CalibrationModelPanel;
import boofcv.app.calib.CalibrationTargetPanel;
import boofcv.app.mjpeg.OpenMjpegCamDialog;
import boofcv.factory.fiducial.FactoryFiducialCalibration;
import boofcv.gui.BoofSwingUtil;
import boofcv.gui.RenderCalibrationTargetsGraphics2D;
import boofcv.gui.image.ImagePanel;
import boofcv.gui.image.ScaleOptions;
import boofcv.gui.image.ShowImages;
import boofcv.io.webcamcapture.OpenWebcamDialog;
import javax.swing.*;
import javax.swing.border.EtchedBorder;
import javax.swing.filechooser.FileSystemView;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.prefs.Preferences;
import static boofcv.gui.BoofSwingUtil.KEY_PREVIOUS_SELECTION;
import static boofcv.gui.StandardAlgConfigPanel.addLabeled;
/**
* GUI which let's you configure the camera calibration process
*
* @author Peter Abeles
*/
// TODO specify output file name
// TODO output format
public class CameraCalibrationGui extends JPanel
implements CalibrationTargetPanel.Listener, ActionListener
{
CameraCalibration app;
JComboBox<CameraCalibration.FormatType> comboOutputFormat;
CameraCalibration.FormatType outputFormat = CameraCalibration.FormatType.BOOFCV;
JTextField textOutput;
CalibrationTargetPanel controlsTarget = new CalibrationTargetPanel(this);
CalibrationModelPanel controlsModel = new CalibrationModelPanel();
ImagePanel renderingPanel = new ImagePanel();
JFrame frame;
public CameraCalibrationGui() {
setLayout(new BorderLayout());
this.app = new CameraCalibration();
this.app.visualize = true;
final File outputFile = new File(FileSystemView.getFileSystemView().getHomeDirectory(),"camera_calibration.yaml");
textOutput = new JTextField();
textOutput.setColumns(20);
textOutput.setText(outputFile.getAbsolutePath());
textOutput.setMaximumSize(new Dimension(textOutput.getPreferredSize().width,30));
JButton bOutput = new JButton(UIManager.getIcon("FileView.fileIcon"));
bOutput.setPreferredSize(new Dimension(30,30));
bOutput.setMaximumSize(bOutput.getPreferredSize());
bOutput.addActionListener(a->{
File f = BoofSwingUtil.fileChooser(this,false,textOutput.getText());
if( f != null ) {
textOutput.setText(f.getAbsolutePath());
}
});
JPanel panelOutput = new JPanel();
panelOutput.setLayout(new BoxLayout(panelOutput,BoxLayout.X_AXIS));
panelOutput.add(textOutput);
panelOutput.add(bOutput);
comboOutputFormat = new JComboBox<>(CameraCalibration.FormatType.values());
comboOutputFormat.setSelectedIndex(outputFormat.ordinal());
comboOutputFormat.addActionListener(this);
comboOutputFormat.setMaximumSize(comboOutputFormat.getPreferredSize());
JPanel controlsPanel = new JPanel();
controlsPanel.setLayout(new BoxLayout(controlsPanel,BoxLayout.Y_AXIS) );
controlsPanel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
addLabeled(panelOutput,"Output",controlsPanel);
addLabeled(comboOutputFormat,"Format",controlsPanel);
controlsPanel.add(Box.createRigidArea(new Dimension(5,5)));
controlsPanel.add(controlsTarget);
controlsPanel.add(controlsModel);
renderingPanel.setScaling(ScaleOptions.DOWN);
renderingPanel.setCentering(true);
renderingPanel.setPreferredSize(new Dimension(400,400));
add(BorderLayout.WEST, controlsPanel);
add(BorderLayout.CENTER,renderingPanel);
createMenuBar();
// trigger an event which will cause the target to be rendered
controlsTarget.updateParameters();
frame = ShowImages.showWindow(this,"BoofCV Camera Calibration",true);
}
void createMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
menu.setMnemonic(KeyEvent.VK_F);
menuBar.add(menu);
JMenuItem menuOpenDirectory = new JMenuItem("Input Directory");
BoofSwingUtil.setMenuItemKeys(menuOpenDirectory,KeyEvent.VK_D,KeyEvent.VK_D);
menuOpenDirectory.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
processDirectory();
}
});
JMenuItem menuWebcam = new JMenuItem("Input Webcam");
BoofSwingUtil.setMenuItemKeys(menuWebcam,KeyEvent.VK_W,KeyEvent.VK_W);
menuWebcam.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openWebcam();
}
});
JMenuItem menuMjpegCam = new JMenuItem("Input MJPEG stream");
BoofSwingUtil.setMenuItemKeys(menuMjpegCam,KeyEvent.VK_M,KeyEvent.VK_M);
menuMjpegCam.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openMjpegCam();
}
});
JMenuItem menuHelp = new JMenuItem("Help", KeyEvent.VK_H);
menuHelp.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
showHelp();
}
});
JMenuItem menuQuit = new JMenuItem("Quit");
BoofSwingUtil.setMenuItemKeys(menuQuit,KeyEvent.VK_Q,KeyEvent.VK_Q);
menuQuit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
menu.addSeparator();
menu.add(menuOpenDirectory);
menu.add(menuWebcam);
menu.add(menuMjpegCam);
menu.add(menuHelp);
menu.add(menuQuit);
add(BorderLayout.NORTH,menuBar);
}
private void showHelp() {
JOptionPane.showMessageDialog(this,"Many more options and better documentation available through commandline");
}
private void openWebcam() {
OpenWebcamDialog.Selection s = OpenWebcamDialog.showDialog(null);
if(s != null ) {
app.inputType = BaseStandardInputApp.InputType.WEBCAM;
app.cameraName = s.camera.getName();
app.desiredWidth = s.width;
app.desiredHeight = s.height;
createDetector();
frame.setVisible(false);
new Thread() {
public void run() {
app.process();
}
}.start();
}
}
private void openMjpegCam() {
OpenMjpegCamDialog.Selection s = OpenMjpegCamDialog.showDialog(null);
if(s != null ) {
app.inputType = BaseStandardInputApp.InputType.MJPEG;
app.camUrl = s.url;
app.desiredWidth = s.width;
app.desiredHeight = s.height;
createDetector();
frame.setVisible(false);
new Thread() {
public void run() {
app.process();
}
}.start();
}
}
private void processDirectory() {
Preferences prefs;
prefs = Preferences.userRoot().node(this.getClass().getSimpleName());
String previousPath=prefs.get(KEY_PREVIOUS_SELECTION, ".");
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File(previousPath));
chooser.setDialogTitle("Directory Input");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
prefs.put(KEY_PREVIOUS_SELECTION, chooser.getSelectedFile().getAbsolutePath());
app.inputType = BaseStandardInputApp.InputType.IMAGE;
app.inputDirectory = chooser.getSelectedFile().getAbsolutePath();
createDetector();
frame.setVisible(false);
new Thread() {
public void run() {
try {
app.process();
} catch( RuntimeException e ) {
BoofSwingUtil.warningDialog(frame,e);
}
}
}.start();
}
}
private void createDetector() {
switch( controlsTarget.selected ) {
case CHESSBOARD: app.detector = FactoryFiducialCalibration.chessboard(null,controlsTarget.configChessboard);break;
case SQUARE_GRID: app.detector = FactoryFiducialCalibration.squareGrid(null,controlsTarget.configSquare);break;
case CIRCLE_GRID: app.detector = FactoryFiducialCalibration.circleRegularGrid(null,controlsTarget.configCircle);break;
case CIRCLE_HEX: app.detector = FactoryFiducialCalibration.circleHexagonalGrid(null,controlsTarget.configCircleHex);break;
}
app.modeType = controlsModel.selected;
if( app.modeType == CameraCalibration.ModelType.PINHOLE ) {
app.numRadial = controlsModel.pinholeRadial;
app.tangential = controlsModel.pinholeTangential;
app.zeroSkew = controlsModel.pinholeSkew;
} else if( app.modeType == CameraCalibration.ModelType.UNIVERSAL ) {
app.numRadial = controlsModel.universalRadial;
app.tangential = controlsModel.universalTangential;
app.zeroSkew = controlsModel.universalSkew;
}
app.formatType = outputFormat;
app.outputFileName = textOutput.getText();
}
@Override
public void calibrationParametersChanged(CalibrationTargetPanel.TargetType type, ConfigGridDimen config) {
final RenderCalibrationTargetsGraphics2D renderer = new RenderCalibrationTargetsGraphics2D(20,1);
if( type == CalibrationTargetPanel.TargetType.CHESSBOARD ) {
renderer.chessboard(config.numRows,config.numCols,20);
} else if( type == CalibrationTargetPanel.TargetType.SQUARE_GRID ) {
double space = 20*config.shapeDistance/config.shapeSize;
renderer.squareGrid(config.numRows,config.numCols,20,space);
} else if( type == CalibrationTargetPanel.TargetType.CIRCLE_GRID ) {
double space = 10*config.shapeDistance/config.shapeSize;
renderer.circleRegular(config.numRows,config.numCols,10,space);
} else if( type == CalibrationTargetPanel.TargetType.CIRCLE_HEX ) {
double space = 10*config.shapeDistance/config.shapeSize;
renderer.circleHex(config.numRows,config.numCols,10,space);
}
renderingPanel.setImageUI(renderer.getBufferred());
}
@Override
public void actionPerformed(ActionEvent e) {
if( e.getSource() == comboOutputFormat ) {
outputFormat = (CameraCalibration.FormatType)comboOutputFormat.getSelectedItem();
}
}
}
| 33.326861
| 125
| 0.763158
|
dc45242b259e9d62180bd8ca7df26227afd399a4
| 2,887
|
/**
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig 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.jasig.portal.io.xml;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.jasig.portal.io.xml.eventaggr.ExternalEventAggregationConfiguration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.core.io.ClassPathResource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.google.common.base.Function;
/**
* @author Eric Dalquist
* @version $Revision$
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/org/jasig/portal/io/xml/aggrImportExportTestContext.xml")
public class AggrIdentityImportExportTest extends AbstractIdentityImportExportTest {
@javax.annotation.Resource(name="eventAggregationConfigurationImporterExporter")
private IDataImporter<ExternalEventAggregationConfiguration> eventAggregationConfigurationImporter;
@javax.annotation.Resource(name="eventAggregationConfigurationImporterExporter")
private IDataExporter<ExternalEventAggregationConfiguration> eventAggregationConfigurationExporter;
@PersistenceContext(unitName = "uPortalAggrEventsPersistence")
private EntityManager entityManager;
@Override
protected EntityManager getEntityManager() {
return this.entityManager;
}
@Test
public void testEventAggregationConfiguration40ImportExport() throws Exception {
final ClassPathResource stylesheetDescriptorResource = new ClassPathResource("/org/jasig/portal/io/xml/eventaggr/test_4-0.event-aggregation.xml");
this.testIdentityImportExport(
this.eventAggregationConfigurationImporter, this.eventAggregationConfigurationExporter,
stylesheetDescriptorResource,
new Function<ExternalEventAggregationConfiguration, String>() {
@Override
public String apply(ExternalEventAggregationConfiguration input) {
return "DEFAULT";
}
});
}
}
| 40.661972
| 154
| 0.758573
|
0a2b919db647e539ee4e8d135e0faee6b3a81847
| 4,814
|
/*
* Copyright 2012 Jim Guistwite
*
* 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.jgui.ttscrape.webclient;
import java.util.ArrayList;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.velocity.VelocityContext;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import com.jgui.ttscrape.IgnoreListFilter;
import com.jgui.ttscrape.Show;
import com.jgui.ttscrape.htmlunit.FetchController;
/**
* The <code>TTScrapeController</code> handles requests
* from the web client.
*
* @author jguistwite
*/
public class TTScrapeController {
Logger logger = LoggerFactory.getLogger(TTScrapeController.class);
@Resource
private WebShowWriter writer;
@Resource
private IgnoreListFilter ignoreListFilter;
@Resource
private FetchController fetchController;
private int port;
/**
* Handle the status page. Populate the velocity context and dispatch
* to the "status.vhtml" page.
* @param req http request
* @param rsp http response
* @param ctx velocity context to populate.
* @return what velocity file to dispatch to.
*/
@RequestMapping("status")
public String status(HttpServletRequest req, HttpServletResponse rsp, VelocityContext ctx) {
Map<String,ArrayList<Show>> map = writer.getShowListMap();
ctx.put("showListMap", map);
ctx.put("port", port);
ctx.put("controller", fetchController);
/*
for (String beanName : beans) {
Object bean = beanFactory.getBean(beanName);
ctx.put(beanName, bean);
}
*/
return "status.vhtml";
}
/**
* Handle an http request to ignore a particular title in the future.
* @param req request containing the id of the show to ignore.
* @param rsp http servlet response to write JSON response to.
* @return JSON data to send
* @throws JSONException thrown in the event creation of the json response fails.
*/
@RequestMapping("ignore")
public JSONObject ignore(HttpServletRequest req, HttpServletResponse rsp) throws JSONException {
JSONObject rv = null;
logger.debug("ignore request received");
String showId = req.getParameter("id");
Show s = writer.getShowMap().get(Integer.parseInt(showId));
if (s == null) {
logger.error("failed to find show with id {}", showId);
rv = createJsonResponse(rsp, "error", "Show not found.");
}
else {
ignoreListFilter.addTitleToIgnore(s.getTitle());
rv = createJsonResponse(rsp, "success", "");
}
return rv;
}
/**
* Handle an http request to read the previous collection of shows.
* @param req HTTP request
* @param rsp HTTP response to write JSON response to.
* @return JSON data to send
* @throws JSONException thrown in the event creation of the json response fails.
*/
@RequestMapping("runRead")
public JSONObject runread(HttpServletRequest req, HttpServletResponse rsp) throws JSONException {
Thread t = new Thread(new Runnable() {
public void run() {
fetchController.read();
}
});
t.start();
return createJsonResponse(rsp, "success", "");
}
/**
* Handle an HTTP request to fetch shows.
* @param req request containing the id of the show to ignore.
* @param rsp response to write json response to.
* @return JSON data to send
* @throws JSONException thrown in the event creation of the json response fails.
*/
@RequestMapping("runFetch")
public JSONObject runfetch(HttpServletRequest req, HttpServletResponse rsp) throws JSONException {
Thread t = new Thread(new Runnable() {
public void run() {
fetchController.fetch();
}
});
t.start();
return createJsonResponse(rsp, "success", "");
}
private JSONObject createJsonResponse(HttpServletResponse rsp, String status, String error) throws JSONException {
JSONObject jsonRsp = new JSONObject();
jsonRsp.put("status", status);
jsonRsp.put("error", error);
return jsonRsp;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
}
| 30.0875
| 116
| 0.703988
|
4eefd78fbc3bfbe685c67c5a525d34b47fd5aa8c
| 2,489
|
package com.mgilangjanuar.dev.goscele.modules.forum.list.provider;
import com.mgilangjanuar.dev.goscele.base.BaseProvider;
import com.mgilangjanuar.dev.goscele.modules.common.model.CookieModel;
import com.mgilangjanuar.dev.goscele.modules.forum.list.adapter.ForumListRecyclerViewAdapter;
import com.mgilangjanuar.dev.goscele.modules.forum.list.listener.ForumListListener;
import com.mgilangjanuar.dev.goscele.modules.forum.list.model.ForumModel;
import com.mgilangjanuar.dev.goscele.utils.Constant;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by mgilangjanuar (mgilangjanuar@gmail.com)
*
* @since 2017
*/
public class ForumSearchProvider extends BaseProvider {
private ForumListListener listener;
private String query;
public ForumSearchProvider(ForumListListener listener, String query) {
this.listener = listener;
this.query = query;
}
@Override
public Map<String, String> cookies() {
return CookieModel.getCookiesMap();
}
@Override
public void run() {
execute("#region-main");
}
@Override
public String url() {
try {
return Constant.BASE_URL + "mod/forum/search.php?id=1&perpage=50&search=" + URLEncoder.encode(query, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(List<Elements> elementses) {
super.onPostExecute(elementses);
try {
Elements elements = elementses.get(0);
List<ForumModel> results = new ArrayList<>();
for (Element e: elements.select("div > .forumpost")) {
ForumModel model = new ForumModel();
model.url = Constant.BASE_URL + "/mod/forum/" + e.select(".subject a").get(1).attr("href");
model.title = e.select(".subject a").get(1).text();
model.author = e.select(".author a").text();
model.lastUpdate = e.select(".author").text().replace("by " + e.select(".author a").text() + " - ", "");
results.add(model);
}
listener.onRetrieve(new ForumListRecyclerViewAdapter(results));
} catch (Exception e) {
listener.onError(e.getMessage());
}
}
}
| 33.186667
| 122
| 0.654881
|
6989d9ad8b515455a709c8cfce8442a99ffdaeda
| 3,575
|
package uk.co.automatictester.arrayqueue.test;
import org.testng.annotations.Test;
import uk.co.automatictester.arrayqueue.ArrayQueue;
import static org.testng.Assert.*;
public class ArrayQueueTest {
@Test
public void testOffer() {
ArrayQueue<Integer> queue = new ArrayQueue<>();
boolean added = queue.offer(1);
assertTrue(added);
queue.offer(1);
queue.offer(3);
assertEquals(queue.size(), 3);
}
@Test
public void testExpand() {
ArrayQueue<Integer> queue = new ArrayQueue<>();
queue.offer(1);
queue.offer(2);
queue.offer(3);
assertEquals(queue.size(), 3);
queue.offer(4);
assertEquals(queue.size(), 4);
}
@Test
public void testShrink() {
ArrayQueue<Integer> queue = new ArrayQueue<>();
queue.offer(1);
queue.offer(2);
queue.offer(3);
queue.offer(4);
queue.offer(5);
queue.offer(6);
queue.offer(7);
queue.offer(8);
queue.offer(9);
assertEquals((int) queue.poll(), 1);
assertEquals((int) queue.poll(), 2);
assertEquals((int) queue.poll(), 3);
assertEquals((int) queue.poll(), 4);
assertEquals((int) queue.poll(), 5);
assertEquals((int) queue.poll(), 6);
assertEquals((int) queue.poll(), 7);
queue.offer(10);
assertEquals((int) queue.poll(), 8);
assertEquals((int) queue.poll(), 9);
assertEquals((int) queue.poll(), 10);
assertNull(queue.poll());
}
@Test
public void testPeek() {
ArrayQueue<Integer> queue = new ArrayQueue<>();
assertNull(queue.peek());
queue.offer(1);
assertEquals((int) queue.peek(), 1);
assertEquals((int) queue.peek(), 1);
}
@Test
public void testPoll() {
ArrayQueue<Integer> queue = new ArrayQueue<>();
queue.offer(1);
queue.offer(2);
queue.offer(3);
assertEquals((int) queue.poll(), 1);
assertEquals((int) queue.poll(), 2);
assertEquals((int) queue.poll(), 3);
assertNull(queue.poll());
}
@Test
public void testOfferAndPoll() {
ArrayQueue<Integer> queue = new ArrayQueue<>();
queue.offer(1);
queue.offer(2);
queue.offer(3);
assertEquals((int) queue.poll(), 1);
queue.offer(4);
queue.offer(5);
queue.offer(6);
assertEquals((int) queue.poll(), 2);
queue.offer(7);
queue.offer(8);
queue.offer(9);
assertEquals((int) queue.poll(), 3);
}
@Test
public void testPollAll() {
ArrayQueue<Integer> queue = new ArrayQueue<>();
queue.offer(1);
queue.offer(2);
queue.offer(3);
queue.offer(4);
assertEquals((int) queue.poll(), 1);
assertEquals((int) queue.poll(), 2);
assertEquals((int) queue.poll(), 3);
assertEquals((int) queue.poll(), 4);
queue.offer(5);
assertEquals((int) queue.poll(), 5);
assertNull(queue.poll());
}
@Test
public void testClear() {
ArrayQueue<Integer> queue = new ArrayQueue<>();
queue.offer(1);
queue.offer(2);
queue.offer(3);
assertEquals((int) queue.poll(), 1);
queue.offer(4);
queue.offer(5);
queue.offer(6);
assertEquals((int) queue.poll(), 2);
queue.offer(7);
queue.offer(8);
queue.offer(9);
queue.clear();
assertNull(queue.peek());
}
}
| 27.5
| 55
| 0.545175
|
599a31d1e1fe329ac1c8a5d02288adbdc0e52b64
| 651
|
import java.util.Scanner;
public class PatternMaking {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a number you rows you want");
int rows = in.nextInt();
PatternRecursion(rows, 0);
}
public static void PatternRecursion(int rows, int columns) {
if(rows == columns & rows != 0) {
System.out.println();
PatternRecursion(rows -1, 0);
}
if(rows > columns) {
System.out.print("* ");
PatternRecursion(rows, columns + 1);
}
else return;
}
}
| 29.590909
| 65
| 0.539171
|
20ab048f01f251ab7f490799d65af255665caf2e
| 623
|
public class main {
public static void main(String[] args) {
System.out.println("Serializing...");
LogFile ob = new LogFile();
ob.filename = "User_Nytro.log";
ob.filecontent = "No actoins logged";
String file = "log.ser";
Utils.SerializeToFile(ob,file);
System.out.println("Deserializing...");
LogFile obd = new LogFile();
String filed = "log.ser";
obd=(LogFile)Utils.DeserializeFromFile(filed);
System.out.println("Desrializing vuln exp...");
LogFile obv = new LogFile();
String filev = "Exp.ser";
obv = (LogFile)Utils.DeserializeFromFile(filev);
}
}
| 23.961538
| 52
| 0.642055
|
3719b7be7c2ea6a8b522059db58f208bceb9e55b
| 3,117
|
package io.sada.lmsalestaxes;
import io.sada.lmsalestaxes.receipt.ReceiptPrinter;
import io.sada.lmsalestaxes.receipt.ReceiptTextFormatter;
import io.sada.lmsalestaxes.store.ProductStore;
import io.sada.lmsalestaxes.store.ProductStoreInMemory;
import io.sada.lmsalestaxes.tax.BasicSalesTax;
import io.sada.lmsalestaxes.tax.ITaxRatesForProduct;
import io.sada.lmsalestaxes.tax.ImportDutySalesTax;
import io.sada.lmsalestaxes.tax.TaxCalculator;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
public class AcceptanceTest {
private CashRegister createApp(CashRegisterScreen screen) {
ITaxRatesForProduct basicTaxes = new BasicSalesTax(BasicSalesTax.BASIC_TAX, BasicSalesTax.EXEMPTED_CATEGORIES);
ITaxRatesForProduct importDuty = new ImportDutySalesTax(ImportDutySalesTax.IMPORT_DUTY);
ProductStore productStore = new ProductStoreInMemory(new TestDataProductCategories().create());
return new CashRegister(new TaxCalculator(basicTaxes, importDuty), productStore, new ReceiptPrinter(), screen);
}
private TextScreen createScreen() {
return new TextScreen(new ReceiptTextFormatter());
}
@Test
public void scenario1() {
TextScreen screen = createScreen();
CashRegister app = createApp(screen);
app.include(1, "book", "12.49");
app.include(1, "music CD", "14.99");
app.include(1, "chocolate bar", "0.85");
app.purchase();
String[] receipt = screen.getLines();
assertArrayEquals(new String[]{
"1 book: 12.49",
"1 music CD: 16.49",
"1 chocolate bar: 0.85",
"Sales Taxes: 1.50",
"Total: 29.83"
}, receipt);
}
@Test
public void scenario2() {
TextScreen screen = createScreen();
CashRegister app = createApp(screen);
app.include(1, "imported box of chocolates", "10.00");
app.include(1, "imported bottle of perfume", "47.50");
app.purchase();
String[] receipt = screen.getLines();
assertArrayEquals(new String[]{
"1 imported box of chocolates: 10.50",
"1 imported bottle of perfume: 54.65",
"Sales Taxes: 7.65",
"Total: 65.15"
}, receipt);
}
@Test
public void scenario3() {
TextScreen screen = createScreen();
CashRegister app = createApp(screen);
app.include(1, "imported bottle of perfume", "27.99");
app.include(1, "bottle of perfume", "18.99");
app.include(1, "packet of headache pills", "9.75");
app.include(1, "box of imported chocolates", "11.25");
app.purchase();
String[] receipt = screen.getLines();
assertArrayEquals(new String[]{
"1 imported bottle of perfume: 32.19",
"1 bottle of perfume: 20.89",
"1 packet of headache pills: 9.75",
"1 imported box of chocolates: 11.85",
"Sales Taxes: 6.70",
"Total: 74.68"
}, receipt);
}
}
| 33.880435
| 119
| 0.623035
|
1a913fc9462bab433c1b6437b4370cfa7eaedb9a
| 526
|
package org.nextime.ion.admin.form;
import org.apache.struts.action.ActionForm;
public class SectionForm extends ActionForm {
private String _id;
private String _parent;
public String getId() {
return _id;
}
public String getParent() {
return _parent;
}
public void setId(String value) {
_id = value.trim();
}
public void setParent(String value) {
_parent = value;
}
public void reset() {
_id = null;
_parent = null;
}
}
| 16.4375
| 45
| 0.596958
|
989c37f89249885d45ca57853141cd35cf2742c8
| 982
|
package com.animationtransmog.config;
import java.util.HashMap;
import java.util.function.Supplier;
public class AnimationTransmogConfigManager
{
HashMap<String, Supplier<String>> configGetters;
public AnimationTransmogConfigManager(AnimationTransmogConfig config)
{
configGetters = new HashMap<>();
configGetters.put("Woodcut", () -> config.swapWoodcutAnimation().getOption());
configGetters.put("Mine", () -> config.swapMineAnimation().getOption());
configGetters.put("StandardSpell", () -> config.swapStandardSpellAnimation().getOption());
configGetters.put("Teleport", () -> config.swapTeleportAnimation().getOption());
configGetters.put("AshScatter", () -> config.swapAshScatterAnimation().getOption());
configGetters.put("Movement", () -> config.swapMovementMode().getOption());
}
public String getConfigOption(String configType)
{
return configGetters.get(configType).get();
}
}
| 37.769231
| 98
| 0.702648
|
748ff70505304fd9208c1d1cc3d154bedf1acf37
| 2,526
|
/*
* IntPTI: integer error fixing by proper-type inference
* Copyright (c) 2017.
*
* Open-source component:
*
* CPAchecker
* Copyright (C) 2007-2014 Dirk Beyer
*
* Guava: Google Core Libraries for Java
* Copyright (C) 2010-2006 Google
*
*
*/
package org.sosy_lab.cpachecker.cpa.smg.checker;
import org.sosy_lab.common.configuration.Configuration;
import org.sosy_lab.cpachecker.cfa.ast.c.CExpression;
import org.sosy_lab.cpachecker.cfa.model.CFAEdge;
import org.sosy_lab.cpachecker.core.interfaces.AbstractState;
import org.sosy_lab.cpachecker.core.interfaces.checker.CheckerWithInstantErrorReport;
import org.sosy_lab.cpachecker.core.interfaces.checker.ErrorReport;
import org.sosy_lab.cpachecker.core.interfaces.checker.ErrorSpot;
import org.sosy_lab.cpachecker.core.interfaces.checker.PL;
import org.sosy_lab.cpachecker.core.interfaces.checker.StateChecker;
import org.sosy_lab.cpachecker.cpa.arg.ARGPath;
import org.sosy_lab.cpachecker.cpa.arg.ARGState;
import org.sosy_lab.cpachecker.cpa.smg.SMGState;
import org.sosy_lab.cpachecker.cpa.smg.errorReport.NPDErrorReport;
import org.sosy_lab.cpachecker.exceptions.CPATransferException;
import org.sosy_lab.cpachecker.weakness.Weakness;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class DoubleFreeChecker implements StateChecker<SMGState>, CheckerWithInstantErrorReport {
List<ErrorReport> DFs;
public DoubleFreeChecker(Configuration pConfig) {
DFs = new ArrayList<>();
}
@Override
public PL forLanguage() {
return PL.C;
}
@Override
public Weakness getOrientedWeakness() {
return Weakness.INVALID_FREE;
}
@Override
public Class<? extends AbstractState> getServedStateType() {
return SMGState.class;
}
@Override
public Collection<ErrorReport> getErrorReport() {
return DFs;
}
@Override
public void resetErrorReport() {
DFs.clear();
}
@Override
public List<ARGState> getInverseCriticalStates(ARGPath pPath, ErrorSpot pNodeInError) {
return pPath.asStatesList();
}
@Override
public void checkAndRefine(
SMGState pPostState, Collection<AbstractState> pPostOtherStates,
CFAEdge pCfaEdge, Collection<SMGState> pNewPostStates) throws CPATransferException {
if (pPostState.checkProperty(SMGState.HAS_INVALID_FREES)) {
for (CExpression exp : pPostState.getInvalidReadExpression()) {
DFs.add(NPDErrorReport.create(exp, pCfaEdge, this));
}
}
pNewPostStates.add(pPostState.cleanProperty());
}
}
| 28.382022
| 97
| 0.768409
|
2a3fcc47288e1292c89091160f8ae7a95fcad47e
| 9,726
|
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
/**
* @authorFelipe Custódio, Gabriel Scalici
*/
public class Chain {
// image properties
int h; // height
int w; // width
// shape properties
int height;
int width;
// bitmaps
int pixels[][]; // image with treshold 1 or 0
int visited[][]; // stores visited pixels
// initial coordinates of the shape
int begin[];
// final coordinates of the shape
int end[];
// perimeter
int points;
double perimeter;
// matriks flag
char flagpixel[][];
public Chain() throws IOException {
// read input file
System.out.print("Filename: ");
String filename = new String();
filename = Input.readString();
File shape = new File(filename);
BufferedImage image = ImageIO.read(shape);
// setar propriedades da image para uso posterior
h = image.getHeight(); // height
w = image.getWidth(); // width
// initialize coordinates vectors
begin = new int[2];
end = new int[2];
points = 0;
perimeter = 0;
//write output file
PrintWriter pw = new PrintWriter(new File("redrawnpic.txt"));
StringBuilder sb = new StringBuilder();
// treshold image
pixels = new int[h][w];
flagpixel = new char[h][w];
visited = new int [h][w];
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
flagpixel[i][j]=' ';
pixels[i][j] = image.getRGB(j, i);
if (pixels[i][j] <= -10197916) {
// shades of gray -> black
pixels[i][j] = 1;
sb.append("X");
} else {
// background -> white
pixels[i][j] = 0;
sb.append(" ");
}
// set pixel as unvisited
visited[i][j] = 0;
}
sb.append("\r\n");
}
//dump ke txt
pw.write(sb.toString());
pw.close();
}
public void firstPixel() {
boolean flag = false;
// locate first black pixel
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
if (pixels[i][j] == 1 && !(flag)) {
// get coordinates
begin[0] = i;
begin[1] = j;
flag = true;
}
}
}
}
public void lastPixel() {
boolean flag = false;
// find first pixel from down-up
for (int i = h - 1; i >= 0; i--) {
for (int j = w - 1; j >= 0; j--) {
if (pixels[i][j] == 1 && !(flag)) {
// get coordinates
end[0] = i;
end[1] = j;
flag = true;
}
}
}
}
public void setHeight() {
// y of last pixel - y of first pixel
height = (end[0] - begin[0] + 1);
}
public void setWidth() {
// get x coordinates of first and final pixels
int aux[] = new int[2];
boolean flag = false;
// find first pixel to the left
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
if (pixels[j][i] == 1 && !(flag)) {
// get x coordinate
aux[0] = i;
flag = true;
}
}
}
flag = false;
// find first pixel to the right
for (int i = w - 1; i >= 0; i--) {
for (int j = h - 1; j >= 0; j--) {
if (pixels[j][i] == 1 && !(flag)) {
// get x coordinate
aux[1] = i;
flag = true;
}
}
}
// x of last pixel - x of first pixel
width = (aux[1] - aux[0] + 1);
}
public void border() {
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
if (pixels[i][j] == 1) {
// if a neighbor of a pixel is empty, that pixel
// is on the border of the shape
if (borderPixel(i, j)) points++;
}
}
}
}
public boolean borderPixel(int i, int j) {
// only check black pixels
if (pixels[i][j] == 0) return false;
// check left
if (j == 0) return true; // image border = shape border
if (j > 0) {
if (pixels[i][j - 1] == 0) {
return true;
}
}
// check up
if (i == 0) return true;
if (i > 0) {
if (pixels[i - 1][j] == 0) {
return true;
}
}
// check right
if (j == w) return true;
if (j < w) {
if (pixels[i][j + 1] == 0) {
return true;
}
}
// check down
if (i == h) return true;
if (i < h-1) {
if (pixels[i + 1][j] == 0) {
return true;
}
}
// no empty pixel around = not border pixel
return false;
}
public int[] borderNeighbors(int i, int j) {
int index[] = new int[2];
boolean flag = false;
// check around pixel for unvisited border pixels
// calculates chain codes distance
// check east
if (borderPixel(i, j+1) && !flag && !flag && visited[i][j+1] == 0) {
j = j + 1;
flagpixel[i][j]='X';
System.out.print("0 ");
perimeter += 1;
flag = true;
index[0] = i;
index[1] = j;
return index;
}
// check southeast
if (borderPixel(i+1, j+1) && !flag && visited[i+1][j+1] == 0) {
i = i + 1;
j = j + 1;
flagpixel[i][j]='X';
System.out.print("1 ");
perimeter += Math.sqrt(2);
flag = true;
index[0] = i;
index[1] = j;
return index;
}
// check south
if (borderPixel(i+1, j) && !flag && visited[i+1][j] == 0) {
i = i + 1;
flagpixel[i][j]='X';
System.out.print("2 ");
perimeter += 1;
flag = true;
index[0] = i;
index[1] = j;
return index;
}
// check southwest
if (borderPixel(i+1, j-1) && !flag && visited[i+1][j-1] == 0) {
i = i + 1;
j = j - 1;
flagpixel[i][j]='X';
System.out.print("3 ");
perimeter += Math.sqrt(2);
flag = true;
index[0] = i;
index[1] = j;
return index;
}
// check west
if (borderPixel(i, j-1) && !flag && visited[i][j-1] == 0) {
j = j - 1;
flagpixel[i][j]='X';
System.out.print("4 ");
perimeter += 1;
flag = true;
index[0] = i;
index[1] = j;
return index;
}
// check northwest
if (borderPixel(i-1, j-1) && !flag && visited[i-1][j-1] == 0) {
i = i - 1;
j = j - 1;
flagpixel[i][j]='X';
System.out.print("5 ");
perimeter += Math.sqrt(2);
flag = true;
index[0] = i;
index[1] = j;
return index;
}
// check north
if (borderPixel(i-1, j) && !flag && visited[i-1][j] == 0) {
i = i - 1;
flagpixel[i][j]='X';
System.out.print("6 ");
perimeter += 1;
flag = true;
index[0] = i;
index[1] = j;
return index;
}
// check northeast
if (borderPixel(i-1, j+1) && !flag && visited[i-1][j+1] == 0) {
i = i - 1;
j = j + 1;
flagpixel[i][j]='X';
System.out.print("7 ");
perimeter += Math.sqrt(2);
flag = true;
index[0] = i;
index[1] = j;
return index;
}
// no neighbor border pixels
index[0] = i;
index[1] = j;
return index;
}
public void chainCodes(int i, int j) {
/*
i e j = index of current pixel
index[0], index[1] = next border pixel (if exists)
*/
// coordinates of current pixel
int[] index = new int[2];
// check for border pixels around
index = borderNeighbors(i, j);
// set pixel as visited
visited[i][j] = 1;
// if next border pixel is visited, we're back to the first pixel
if (visited[index[0]][index[1]] == 0) {
chainCodes(index[0], index[1]);
} else {
System.out.println();
}
}
public static void main(String[] args) throws IOException {
Chain c = new Chain();
// get key coordinates
c.firstPixel();
c.lastPixel();
// calculate shape properties
c.setHeight();
c.setWidth();
System.out.println("Shape width: " + c.width);
System.out.println("Shape height: " + c.height);
// generate chain codes
// print first coordinate
System.out.println("Begin Coordinate: " + c.begin[0] + " " + c.begin[1]);
// get coordinates of first border pixel after initial
int[] index = new int[2];
System.out.print("Chain Codes: ");
index = c.borderNeighbors(c.begin[0], c.begin[1]);
c.chainCodes(index[0], index[1]);
// print last coordinate
System.out.println("End Coordinate: " + c.end[0] + " " + c.end[1]);
// get perimeter size
c.border();
System.out.println("Border pixels: " + c.points + " pixels");
System.out.println("Shape perimeter: " + c.perimeter);
//write output file
PrintWriter pw = new PrintWriter(new File("border.txt"));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < c.h; i++) {
for (int j = 0; j < c.w; j++) {
sb.append(c.flagpixel[i][j]);
}
sb.append("\r\n");
}
//dump ke txt
pw.write(sb.toString());
pw.close();
}
}
| 25.002571
| 75
| 0.460107
|
f5adca33533968b8aec4e9c628987288248d9c1b
| 1,501
|
package uk.nhs.nhsx.testkitorder;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class TestOrderResponseFactory {
public enum TestKitRequestType { ORDER, REGISTER }
private final Map<TestKitRequestType, String> forwardingUrl;
public TestOrderResponseFactory(String orderWebsite, String registerWebsite) {
Map<TestKitRequestType, String> forwardingUrl = new HashMap<>();
forwardingUrl.put(TestKitRequestType.ORDER, orderWebsite);
forwardingUrl.put(TestKitRequestType.REGISTER, registerWebsite);
this.forwardingUrl = Collections.unmodifiableMap(forwardingUrl);
}
public TestOrderResponse createTestOrderResponse(TokensGenerator.TestOrderTokens tokens,
TestKitRequestType testKitRequestType) {
return new TestOrderResponse(
forwardingUrl(tokens, testKitRequestType),
tokens.ctaToken,
tokens.testResultPollingToken,
tokens.diagnosisKeySubmissionToken
);
}
private String forwardingUrl(TokensGenerator.TestOrderTokens tokens,
TestKitRequestType testKitRequestType) {
return Optional.ofNullable(this.forwardingUrl.get(testKitRequestType))
.map(url -> url + "?ctaToken=" + tokens.ctaToken)
.orElseThrow(() -> new RuntimeException("Did not specify a test kit request type"));
}
}
| 36.609756
| 100
| 0.688208
|
c60e3eb0a92d55d24d0fff1039dcc5a512ae164f
| 387
|
package eu.xenit.alfred.initializr.start.extensions.alfred.telemetry.grafana.provisioning;
import java.util.ArrayList;
import java.util.List;
import lombok.Getter;
public class GrafanaProvisioning {
@Getter
private final List<GrafanaDataSource> dataSources = new ArrayList<>();
@Getter
private final List<GrafanaDashboardProvider> dashboards = new ArrayList<>();
}
| 22.764706
| 90
| 0.770026
|
de1742ad56165ba3a01a13c2f16d0bbcf81279d6
| 864
|
package com.gmail.chickenpowerrr.ranksync.api.data;
import com.gmail.chickenpowerrr.ranksync.api.bot.Bot;
/**
* This interface manages all of the possible databases
*
* @author Chickenpowerrr
* @since 1.0.0
*/
public interface DatabaseFactory {
/**
* Returns a new database if the requested database doesn't exist, otherwise it will give the cached
* database instance
*
* @param name the name of the database
* @param credentials the information that is needed to establish a connection with the database
* @return a new database if the requested database doesn't exist, otherwise it will give the
* cached database instance
*/
Database getDatabase(String name, Properties credentials);
/**
* Returns the {@code Bot} that uses this factory
*
* @return the {@code Bot} that uses this factory
*/
Bot getBot();
}
| 27.870968
| 102
| 0.71875
|
91a1cf9d82abb4e2aea741c6a8697ec61db883de
| 161
|
package ioc.test.usecodebean;
/**
* @author Zexho
* @date 2021/7/31 10:47 上午
*/
public interface BeanTest {
/**
* print
*/
void print();
}
| 12.384615
| 29
| 0.559006
|
d63836e1bea1a82c0263a2051fb2ddd739defb75
| 13,512
|
package com.joker17.small.tools;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ConsoleTable {
/**
* 空格
*/
private static final char SPACE_CHAR = ' ';
/**
* 空元素的默认字符
*/
private static final String NULL_ELEMENT_STR = "NULL";
/**
* 换行符
*/
private static final String LINE_BREAK_STR = "\r\n";
/**
* 列数
*/
private int columns;
/**
* 标题数组
*/
private String[] titles;
/**
* 内容列表
*/
private List<String[]> elementsList;
/**
* 列宽数组
*/
private int[] tableColumnWidths;
/**
* 文本对齐数组
*/
private TextAlign[] textAligns;
/**
* 左边距
*/
private int leftMargin;
/**
* 右边距
*/
private int rightMargin;
public enum TextAlign {
LEFT,
CENTER,
RIGHT
}
public ConsoleTable(String... titles) {
this.titles = titles;
this.columns = this.titles.length;
this.tableColumnWidths = new int[this.columns];
this.elementsList = new ArrayList<>(64);
updateTableWidths(this.titles);
//设置默认文本对齐值
textAligns(TextAlign.CENTER);
}
public static ConsoleTable of(String... titles) {
return new ConsoleTable(titles);
}
/**
* 设置对齐方式
*
* @param textAligns
* @return
*/
public ConsoleTable textAligns(TextAlign... textAligns) {
if (textAligns.length == 1 || textAligns.length == this.columns) {
this.textAligns = textAligns;
} else {
throw new IllegalArgumentException(String.format("textAligns length should one or eq titles length"));
}
return this;
}
/**
* 设置左边距
*
* @param leftMargin
* @return
*/
public ConsoleTable leftMargin(int leftMargin) {
this.leftMargin = leftMargin;
return this;
}
/**
* 设置右边距
*
* @param rightMargin
* @return
*/
public ConsoleTable rightMargin(int rightMargin) {
this.rightMargin = rightMargin;
return this;
}
/**
* 添加行元素数组
*
* @param elements
* @return
*/
public ConsoleTable addRowElements(String... elements) {
if (elements.length != this.columns) {
throw new IllegalArgumentException(String.format("elements length must be eq titles length"));
}
elements = convertElements(elements);
this.elementsList.add(elements);
updateTableWidths(elements);
return this;
}
/**
* 转换元素数组
*
* @param elements
* @return
*/
private String[] convertElements(String... elements) {
String[] results = new String[this.columns];
for (int i = 0; i < this.columns; i++) {
String element = elements[i];
if (element == null) {
results[i] = NULL_ELEMENT_STR;
} else {
results[i] = element;
}
}
return results;
}
/**
* 更新宽度
*
* @param contents
*/
private void updateTableWidths(String... contents) {
for (int i = 0; i < this.columns; i++) {
int tableWidth = tableColumnWidths[i];
int contentWidth = StringFormatUtil.strLength(contents[i]);
if (tableWidth < contentWidth) {
tableColumnWidths[i] = contentWidth;
}
}
}
/**
* 输出结果
*/
public void print() {
//获取修饰符内容
String tableModifierText = getTablePrintModifierText('-', "+");
//修饰符内容输出
toPrintConsole(tableModifierText);
//输出table标题内容
toPrintConsole(getTablePrintContents(this.titles, "|"));
//修饰符内容输出
toPrintConsole(tableModifierText);
//输出table行元素内容
int elementsSize = elementsList.size();
for (int i = 0; i < elementsSize; i++) {
String[] elements = elementsList.get(i);
toPrintConsole(getTablePrintContents(elements, "|"));
}
if (elementsSize > 0) {
//修饰符内容输出
toPrintConsole(tableModifierText);
}
}
/**
* 获取输出内容
*
* @return
*/
public String getAsString() {
StringBuilder sb = new StringBuilder();
//修饰符内容
String tableModifierText = getTablePrintModifierText('-', "+");
sb.append(tableModifierText);
//table标题内容
sb.append(getTablePrintContents(this.titles, "|"));
//修饰符内容
sb.append(tableModifierText);
//输出table行元素内容
int elementsSize = elementsList.size();
for (int i = 0; i < elementsSize; i++) {
String[] elements = elementsList.get(i);
sb.append(getTablePrintContents(elements, "|"));
}
if (elementsSize > 0) {
//修饰符内容
sb.append(tableModifierText);
}
return sb.toString();
}
/**
* 获取table要输出的内容
*
* @param contents
* @param separator
* @return
*/
private String getTablePrintContents(String[] contents, String separator) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < this.columns; i++) {
String content = contents[i];
if (i == 0) {
sb.append(separator);
}
sb.append(getFormatContent(content, SPACE_CHAR, i));
sb.append(separator);
}
sb.append(LINE_BREAK_STR);
return sb.toString();
}
/**
* 输出字符内容到控制台
*
* @param text
*/
private void toPrintConsole(String text) {
System.out.print(text);
}
/**
* 获取要输出的修饰符内容
*
* @param connectorChar
* @param separator
*/
private String getTablePrintModifierText(char connectorChar, String separator) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < this.columns; i++) {
if (i == 0) {
sb.append(separator);
}
String charString = StringFormatUtil.getFillString(connectorChar, tableColumnWidths[i]);
sb.append(getFormatContent(charString, connectorChar, i));
sb.append(separator);
}
sb.append(LINE_BREAK_STR);
return sb.toString();
}
/**
* 获取格式化后的内容
*
* @param content 字符内容
* @param fillChar 填充char
* @param index 索引位置
* @return
*/
private String getFormatContent(String content, char fillChar, int index) {
TextAlign textAlign;
if (textAligns.length == 1) {
textAlign = textAligns[0];
} else {
textAlign = textAligns[index];
}
switch (textAlign) {
case LEFT:
return StringFormatUtil.left(content, fillChar, tableColumnWidths[index], leftMargin, rightMargin);
case CENTER:
return StringFormatUtil.center(content, fillChar, tableColumnWidths[index], leftMargin, rightMargin);
case RIGHT:
return StringFormatUtil.right(content, fillChar, tableColumnWidths[index], leftMargin, rightMargin);
default:
throw new UnsupportedOperationException("NOT SUPPORT textAlign: " + textAlign.name());
}
}
static class StringFormatUtil {
final static char SPACE_CHAR = ' ';
/**
* 获取填充新字符
*
* @param c
* @param size
* @return
*/
public static String getFillString(char c, int size) {
char[] chars = new char[size];
Arrays.fill(chars, c);
return new String(chars);
}
public static int strLength(String str) {
return StringPadUtil.strLength(str, "UTF-8");
}
public static String center(String str, int size, int leftSize, int rightSize) {
return center(str, SPACE_CHAR, size, leftSize, rightSize);
}
public static String center(String str, char c, int size, int leftSize, int rightSize) {
if (str == null) {
return null;
}
size = size + leftSize + rightSize;
int strLength = StringPadUtil.strLength(str);
/* if (size <= 0 || size <= strLength) {
return str;
}*/
str = StringPadUtil.leftPad(str, strLength + (size - strLength) / 2, c);
str = StringPadUtil.rightPad(str, size, c);
return str;
}
public static String left(String str, int size, int leftSize, int rightSize) {
return left(str, SPACE_CHAR, size, leftSize, rightSize);
}
public static String left(String str, char c, int size, int leftSize, int rightSize) {
if (str == null) {
return null;
}
size += rightSize;
str = StringPadUtil.rightPad(str, size, c);
if (leftSize != 0) {
str = StringPadUtil.leftPad(str, size + leftSize, c);
}
return str;
}
public static String right(String str, int size, int leftSize, int rightSize) {
return right(str, SPACE_CHAR, size, leftSize, rightSize);
}
public static String right(String str, char c, int size, int leftSize, int rightSize) {
if (str == null) {
return null;
}
size += leftSize;
str = StringPadUtil.leftPad(str, size, c);
if (rightSize != 0) {
str = StringPadUtil.rightPad(str, size + rightSize, c);
}
return str;
}
}
/**
* Created by IntelliJ IDEA
* <p>
* <p>
* https://blog.csdn.net/CL_YD/article/details/85006808
* <p>
* 源地址:
* https://github.com/clyoudu/clyoudu-util/blob/master/src/main/java/github/clyoudu/consoletable/util/StringPadUtil.java
*
* @author chenlei
* @date 2019/4/16
* @time 21:04
* @desc StringPadUtil
*/
static class StringPadUtil {
public static String leftPad(String str, int size, char c) {
if (str == null) {
return null;
}
int strLength = strLength(str);
if (size <= 0 || size <= strLength) {
return str;
}
return repeat(size - strLength, c).concat(str);
}
public static String rightPad(String str, int size, char c) {
if (str == null) {
return null;
}
int strLength = strLength(str);
if (size <= 0 || size <= strLength) {
return str;
}
return str.concat(repeat(size - strLength, c));
}
public static String center(String str, int size, char c) {
if (str == null) {
return null;
}
int strLength = strLength(str);
if (size <= 0 || size <= strLength) {
return str;
}
str = leftPad(str, strLength + (size - strLength) / 2, c);
str = rightPad(str, size, c);
return str;
}
public static String leftPad(String str, int size) {
return leftPad(str, size, ' ');
}
public static String rightPad(String str, int size) {
return rightPad(str, size, ' ');
}
public static String center(String str, int size) {
return center(str, size, ' ');
}
private static String repeat(int size, char c) {
StringBuilder s = new StringBuilder();
for (int index = 0; index < size; index++) {
s.append(c);
}
return s.toString();
}
public static int strLength(String str) {
return strLength(str, "UTF-8");
}
public static int strLength(String str, String charset) {
int len = 0;
int j = 0;
byte[] bytes = str.getBytes(Charset.forName(charset));
while (bytes.length > 0) {
short tmpst = (short) (bytes[j] & 0xF0);
if (tmpst >= 0xB0) {
if (tmpst < 0xC0) {
j += 2;
len += 2;
} else if ((tmpst == 0xC0) || (tmpst == 0xD0)) {
j += 2;
len += 2;
} else if (tmpst == 0xE0) {
j += 3;
len += 2;
} else if (tmpst == 0xF0) {
short tmpst0 = (short) (((short) bytes[j]) & 0x0F);
if (tmpst0 == 0) {
j += 4;
len += 2;
} else if ((tmpst0 > 0) && (tmpst0 < 12)) {
j += 5;
len += 2;
} else if (tmpst0 > 11) {
j += 6;
len += 2;
}
}
} else {
j += 1;
len += 1;
}
if (j > bytes.length - 1) {
break;
}
}
return len;
}
}
}
| 26.44227
| 124
| 0.496004
|
c58101a86e2470a7a1fdecc92474bb1cca620e89
| 2,356
|
/******************************************************************************
* Copyright (c) 2015 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*****************************************************************************/
package com.ibm.research.sparql.rewriter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.openrdf.query.algebra.Var;
/**
* @author Mariano Rodriguez <mrodrig@us.ibm.com>
*
*/
public class SubstitutionImpl implements Substitution {
Map<Var, Var> map = new HashMap<Var, Var>();
/*
* (non-Javadoc)
*
* @see
* com.ibm.research.sparql.rewriter.StatementUnifier.Substitution#compose
* (org.openrdf.query.algebra.Var, org.openrdf.query.algebra.Var)
*/
@Override
public boolean compose(Var original, Var substitution) {
Substitution unifier = StatementUnifier.getUnifier(original, substitution);
Set<Var> trivialRemove = new HashSet<Var>();
if (unifier == null)
return false;
if (unifier instanceof NeutralSubstitution)
return true;
for (Var key : map.keySet()) {
Var value = map.get(key);
if (value.equals(original))
if (key.equals(substitution)) {
// existing substitition now trivial, remove it.
trivialRemove.add(key);
} else {
map.put(key, substitution);
}
}
map.put(original, substitution);
map.keySet().removeAll(trivialRemove);
return true;
}
/*
* (non-Javadoc)
*
* @see
* com.ibm.research.sparql.rewriter.StatementUnifier.Substitution#get
* (org.openrdf.query.algebra.Var)
*/
@Override
public Var get(Var var) {
return map.get(var);
}
/*
* (non-Javadoc)
*
* @see
* com.ibm.research.sparql.rewriter.StatementUnifier.Substitution#getMap
* ()
*/
@Override
public Map<Var, Var> getMap() {
return map;
}
/*
* (non-Javadoc)
*
* @see
* com.ibm.research.sparql.rewriter.StatementUnifier.Substitution#isEmpty
* ()
*/
@Override
public boolean isEmpty() {
return map.isEmpty();
}
public String toString() {
return map.toString();
}
}
| 23.56
| 79
| 0.642615
|
302691787c21b60e5f9bcf669512baa1f3f713c7
| 712
|
package uk.gov.justice.digital.delius.data.api;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class EnforcementAction {
@ApiModelProperty(required = true)
private String code;
@ApiModelProperty(required = true)
private String description;
@ApiModelProperty("Contact will be added to the enforcement diary")
private Boolean outstandingContactAction;
@ApiModelProperty("Enforcement response date on the contact will be populated as this many days from the outcome date")
private Long responseByPeriod;
}
| 27.384615
| 123
| 0.792135
|
2e177519fa140224439002498552c948b323208f
| 6,423
|
package com.oxygenxml.cmis.ui;
import java.awt.Rectangle;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.SwingUtilities;
import com.oxygenxml.cmis.core.ResourceController;
import com.oxygenxml.cmis.core.model.IResource;
import com.oxygenxml.cmis.core.model.impl.DocumentImpl;
import com.oxygenxml.cmis.core.model.impl.FolderImpl;
import com.oxygenxml.cmis.plugin.Tags;
import com.oxygenxml.cmis.plugin.TranslationResourceController;
/**
* Class thats gets the line asynchronously and then repainting the component of
* the JLlist
*
* @author bluecc
*
*/
public class CacheSearchProvider implements ContentSearcher {
private final String timeCreated;
private final String emptyResult;
private final ContentSearcher searchProvider;
private final JList<IResource> list;
private final HashMap<String, String> cacheLine;
private final HashMap<String, String> cachePath;
private final HashMap<String, String> cacheProperties;
private final HashMap<String, String> cacheName;
private final Timer timer = new Timer(false);
/**
* Initialize the data
*
* @param searchProvider
* @param list
*/
CacheSearchProvider(ContentSearcher searchProvider, JList<IResource> list) {
timeCreated = TranslationResourceController.getMessage(Tags.TIME_CREATED);
emptyResult = TranslationResourceController.getMessage(Tags.EMPTY_RESULT);
cacheLine = new HashMap<>();
cachePath = new HashMap<>();
cacheProperties = new HashMap<>();
cacheName = new HashMap<>();
this.searchProvider = searchProvider;
this.list = list;
}
@Override
public String getLineDoc(IResource doc, String matchPattern) {
// Get the line found by ID
String lineDoc = cacheLine.get(doc.getId());
if (lineDoc == null && doc.getId() != null) {
TimerTask task = new TimerTask() {
@Override
public void run() {
if (doc != null && doc.getId() != null) {
// Get the line
String line = searchProvider.getLineDoc(doc, matchPattern);
// Put it in the hashmap or put 'Empty'
cacheLine.put(doc.getId(), line != null ? line : null);
// Repaint later the component
SwingUtilities.invokeLater(() -> {
int index = ((DefaultListModel<IResource>) list.getModel()).indexOf(doc);
Rectangle cellBounds = list.getCellBounds(index, index);
if (cellBounds != null) {
list.repaint(cellBounds);
}
});
}
}
};
timer.schedule(task, 0);
}
return lineDoc;
}
@Override
public String getPath(IResource resource, ResourceController ctrl) {
// Get the line found by ID
String pathDoc = cachePath.get(resource.getId());
if (pathDoc == null) {
TimerTask task = new TimerTask() {
@Override
public void run() {
// Get the line
String path = null;
if (resource instanceof DocumentImpl) {
path = ((DocumentImpl) resource).getDocumentPath(ctrl);
} else if (resource instanceof FolderImpl) {
path = ((FolderImpl) resource).getFolderPath();
}
// Put it in the hashmap or put 'Empty'
cachePath.put(resource.getId(), path != null ? path : emptyResult);
// Repaint later the component
SwingUtilities.invokeLater(() -> {
int index = ((DefaultListModel<IResource>) list.getModel()).indexOf(resource);
Rectangle cellBounds = list.getCellBounds(index, index);
if (cellBounds != null) {
list.repaint(cellBounds);
}
});
}
};
timer.schedule(task, 0);
}
return pathDoc;
}
@Override
public void addSearchListener(SearchListener searchListener) {
searchProvider.addSearchListener(searchListener);
}
@Override
public void doSearch(String searchText, boolean searchFolders) {
searchProvider.doSearch(searchText, searchFolders);
}
@Override
public String getProperties(IResource resource) {
// Get the line found by ID
String propertiesToShow = cacheProperties.get(resource.getId());
if (propertiesToShow == null) {
TimerTask task = new TimerTask() {
@Override
public void run() {
// Get the line
String properties = null;
if (resource instanceof DocumentImpl) {
DocumentImpl doc = (DocumentImpl) resource;
properties = doc.getModifiedBy();
} else if (resource instanceof FolderImpl) {
FolderImpl folder = (FolderImpl) resource;
properties = timeCreated + folder.getTimeCreated();
}
// Put it in the hashmap or put 'Empty'
cacheProperties.put(resource.getId(), properties != null ? properties : emptyResult);
// Repaint later the component
SwingUtilities.invokeLater(() -> {
int index = ((DefaultListModel<IResource>) list.getModel()).indexOf(resource);
Rectangle cellBounds = list.getCellBounds(index, index);
if (cellBounds != null) {
list.repaint(cellBounds);
}
});
}
};
timer.schedule(task, 0);
}
return propertiesToShow;
}
@Override
public String getName(IResource resource) {
// Get the line found by ID
String id = resource.getId();
String name = cacheName.get(id);
if (name == null) {
TimerTask task = new TimerTask() {
@Override
public void run() {
// Get the name
String name = null;
name = resource.getDisplayName().replace(" (Working Copy)", "").trim();
// Put it in the hashmap or put 'Empty'
cacheName.put(resource.getId(), name != null ? name : emptyResult);
// Repaint later the component
SwingUtilities.invokeLater(() -> {
int index = ((DefaultListModel<IResource>) list.getModel()).indexOf(resource);
Rectangle cellBounds = list.getCellBounds(index, index);
if (cellBounds != null) {
list.repaint(cellBounds);
}
});
}
};
timer.schedule(task, 0);
}
return name;
}
}
| 27.566524
| 95
| 0.620271
|
afa1d5b6db70aacd6027c53894619252e6a79eef
| 121
|
@ParametersAreNonnullByDefault package com.hjwylde.qbs.compiler;
import javax.annotation.ParametersAreNonnullByDefault;
| 30.25
| 64
| 0.884298
|
be32633603ccd0ee3553aecbd9df4e5f1a06bd5d
| 1,221
|
package com.appspot.hildy.modules;
import static com.google.appengine.api.datastore.DatastoreServiceConfig.Builder.withReadPolicy;
import com.google.api.client.extensions.appengine.http.UrlFetchTransport;
import com.google.api.client.http.HttpTransport;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.ImplicitTransactionManagementPolicy;
import com.google.appengine.api.datastore.ReadPolicy;
import com.google.appengine.api.datastore.ReadPolicy.Consistency;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.google.inject.AbstractModule;
public class AppEngineModule extends AbstractModule {
@Override
protected void configure() {
bind(MemcacheService.class).toInstance(MemcacheServiceFactory.getMemcacheService());
bind(DatastoreService.class).toInstance(DatastoreServiceFactory.getDatastoreService(
withReadPolicy(new ReadPolicy(Consistency.EVENTUAL))
.implicitTransactionManagementPolicy(ImplicitTransactionManagementPolicy.NONE)));
bind(HttpTransport.class).to(UrlFetchTransport.class);
}
}
| 46.961538
| 95
| 0.851761
|
1f553ea271b75a3a4564f63d0f1c4027a9d44e98
| 1,442
|
package room.entidades;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.ForeignKey;
import android.arch.persistence.room.PrimaryKey;
import static android.arch.persistence.room.ForeignKey.CASCADE;
@Entity(tableName = "GI_COMPRA",
foreignKeys = @ForeignKey(entity = Cliente.class,
parentColumns = "c_cedula",
childColumns = "c_cedula",
onDelete = ForeignKey.CASCADE))
public class Compra {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "c_codigo")
private int codigo;
@ColumnInfo(name = "c_cedula")
private int cedulaCliente;
@ColumnInfo(name = "f_fecha")
private String fecha;
public Compra(int codigo, int cedulaCliente, String fecha) {
this.codigo = codigo;
this.cedulaCliente = cedulaCliente;
this.fecha = fecha;
}
public int getCodigo() {
return codigo;
}
public void setCodigo(int codigo) {
this.codigo = codigo;
}
public int getCedulaCliente() {
return cedulaCliente;
}
public void setCedulaCliente(int cedulaCliente) {
this.cedulaCliente = cedulaCliente;
}
public String getFecha() {
return fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
}
| 25.298246
| 67
| 0.627601
|
2b08dcc65c9062d7177b3ddb147aa7313a214af1
| 3,206
|
/*
* 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 com.hortonworks.iotas.streams.runtime.storm.bolt.rules;
import com.hortonworks.iotas.streams.IotasEvent;
import com.hortonworks.iotas.streams.common.IotasEventImpl;
import com.hortonworks.iotas.streams.runtime.rule.RulesDependenciesFactory;
import mockit.Expectations;
import mockit.VerificationsInOrder;
import mockit.integration.junit4.JMockit;
import org.apache.storm.tuple.Values;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.HashMap;
@RunWith(JMockit.class)
public class RulesBoltSqlTest extends RulesBoltTest {
private static final IotasEvent IOTAS_EVENT = new IotasEventImpl(new HashMap<String, Object>() {{
put("humidity", 51);
put("temperature", 101);
put("field3", 23);
put("devicename", "nestdevice");
}}, "dataSrcId_3", "3");
private static final IotasEvent PROJECTED_IOTAS_EVENT = new IotasEventImpl(new HashMap<String, Object>() {{
put("humidity", 51);
put("INCR(humidity, 10)", 61);
put("UPPER(devicename)", "NESTDEVICE");
}}, "dataSrcId_3", "3");
private static final Values IOTAS_EVENT_VALUES = new Values(IOTAS_EVENT);
protected RulesDependenciesFactory.ScriptType getScriptType() {
return RulesDependenciesFactory.ScriptType.SQL;
}
@Test
public void test_ProjectedValues() throws Exception {
new Expectations() {{
mockTuple.getValueByField(IotasEvent.IOTAS_EVENT);
result = IOTAS_EVENT;
mockTuple.getSourceStreamId();
result = "default";
}};
rulesBolt.execute(mockTuple);
new VerificationsInOrder() {{
mockOutputCollector.emit(ruleProcessorRuntime.getRulesRuntime().get(0).getStreams().iterator().next(),
mockTuple, IOTAS_EVENT_VALUES);
times = 0; // rule 1 does not trigger
Values actualValues;
mockOutputCollector.emit(ruleProcessorRuntime.getRulesRuntime().get(1).getStreams().iterator().next(),
mockTuple, actualValues = withCapture());
times = 1; // rule 2 triggers
Assert.assertEquals(PROJECTED_IOTAS_EVENT.getFieldsAndValues(), ((IotasEvent)actualValues.get(0)).getFieldsAndValues());
mockOutputCollector.ack(mockTuple);
times = 1;
}};
}
}
| 39.097561
| 132
| 0.689956
|
99c9a0b5006cda42685a379bf4633a315a797f3c
| 146
|
import me.tatarka.autodata.base.AutoData;
@AutoData(defaults = false)
public abstract class ErrorGetNoReturn {
public abstract void test();
}
| 24.333333
| 41
| 0.773973
|
fee89492e005da8f6d0fcd16e8d641aa3b375ea7
| 108
|
package org.paulobichara.springbootapi.dto.keycloak;
public record RoleMapping(String id, String name) {
}
| 21.6
| 52
| 0.805556
|
2ad0c11e310c8ce208535ef918204b5a4d63e7fa
| 5,861
|
// Copyright 2019 Google LLC
//
// 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
//
// 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 com.google.sps;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public final class FindMeetingQuery {
/**
* Return a collection of TimeRanges that attendees can meet for a requested
* meeting. If there are no TimeRanges that works for both required and optional
* attendees, find TimeRanges that just work for required attendees. If there
* are no required attendees, find the TimeRanges for just the optional attendees.
*/
public Collection<TimeRange> query(Collection<Event> events, MeetingRequest request) {
long meetingDuration = request.getDuration();
Collection<String> requiredAttendees = request.getAttendees();
Collection<String> allAttendees = new ArrayList<>(requiredAttendees);
allAttendees.addAll(request.getOptionalAttendees());
if (meetingDuration > TimeRange.WHOLE_DAY.duration() || meetingDuration <= 0) {
// The meeting duation is invalid.
return Arrays.asList();
}
// Find TimeRanges when both required and optional attendees are available.
Collection<TimeRange> allMeetingTimes =
findMeetingTimes(events, allAttendees, meetingDuration);
if (!allMeetingTimes.isEmpty()) {
return allMeetingTimes;
}
if (requiredAttendees.isEmpty()) {
// There were no required attendees (all were optional), and we failed
// to find an avaiable meeting time. Thus we return an empty result,
// as there is nothing else we can do.
return Arrays.asList();
}
// We failed to find an available meeting time that accommodates both the
// required and optional attendees, so now we are ignoring all the optional
// attendees.
return findMeetingTimes(
events, requiredAttendees, meetingDuration);
}
/**
* Find all times that the meeting could happen for given attendees.
* Loop through the given events by start time in ascending order
* and update the rangeStart pointer, so that when events overlap,
* the pointer always pointing to the start of the current available
* TimeRange. If the current available TimeRange has longer duration
* than the requested meeting duration, we add it to available meetingTimes.
* Then update the pointer to the end of the current event.
*/
private static Collection<TimeRange> findMeetingTimes(
Collection<Event> events, Collection<String> attendees, long duration) {
Collection<TimeRange> meetingTimes = new ArrayList<TimeRange>();
// Sort the events by the start time in acsending order.
List<Event> eventsSorted = new ArrayList<Event>(events);
Collections.sort(eventsSorted, Event.SORT_BY_START_ASCENDING);
// Candidate for the start of the current available TimeRange.
// It will always pointing to the end of the previous event that
// contains any of the given attendees.
int rangeStart = TimeRange.START_OF_DAY;
// Loop through the sorted events and add new TimeRange to
// meetingTimes.
for (Event event : eventsSorted) {
Collection<String> eventAttendees = event.getAttendees();
TimeRange eventWhen = event.getWhen();
int eventStart = eventWhen.start();
int eventEnd = eventWhen.end();
// Check if given attendees shows up in the event.
if (isAttending(attendees, eventAttendees)) {
if (rangeStart >= eventStart) {
// There is overlap or no gap between the current and the
// previous event.
if (eventEnd > rangeStart) {
// Update the pointer so that it is pointing to the start
// of the new available TimeRange.
rangeStart = eventEnd;
}
} else {
// If the current and the previous events are separate,
// initialize the current available TimeRange.
TimeRange newRange = TimeRange.fromStartEnd(
rangeStart, eventStart, false);
if (newRange.duration() >= duration) {
meetingTimes.add(newRange);
}
rangeStart = eventEnd;
}
}
}
TimeRange finalRange = TimeRange.fromStartEnd(rangeStart, TimeRange.END_OF_DAY, true);
if (finalRange.duration() >= duration) {
meetingTimes.add(finalRange);
}
return meetingTimes;
}
/**
* Check and return true if any given attendees are present in the
* eventAttendees. Return false otherwise.
*/
private static boolean isAttending(
Collection<String> attendees, Collection<String> eventAttendees) {
for (String eventAttendee : eventAttendees) {
if (attendees.contains(eventAttendee)) {
return true;
}
}
return false;
}
}
| 42.165468
| 94
| 0.632145
|
9dc31bfdf45f07640402a3a1a96142bd93f42ec9
| 1,084
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: POGOProtos.Rpc.proto
package POGOProtos.Rpc;
public interface GetNotificationInboxOutProtoOrBuilder extends
// @@protoc_insertion_point(interface_extends:POGOProtos.Rpc.GetNotificationInboxOutProto)
com.google.protobuf.MessageOrBuilder {
/**
* <code>.POGOProtos.Rpc.GetNotificationInboxOutProto.Result result = 1;</code>
* @return The enum numeric value on the wire for result.
*/
int getResultValue();
/**
* <code>.POGOProtos.Rpc.GetNotificationInboxOutProto.Result result = 1;</code>
* @return The result.
*/
POGOProtos.Rpc.GetNotificationInboxOutProto.Result getResult();
/**
* <code>.POGOProtos.Rpc.ClientInbox inbox = 2;</code>
* @return Whether the inbox field is set.
*/
boolean hasInbox();
/**
* <code>.POGOProtos.Rpc.ClientInbox inbox = 2;</code>
* @return The inbox.
*/
POGOProtos.Rpc.ClientInbox getInbox();
/**
* <code>.POGOProtos.Rpc.ClientInbox inbox = 2;</code>
*/
POGOProtos.Rpc.ClientInboxOrBuilder getInboxOrBuilder();
}
| 30.111111
| 94
| 0.712177
|
dd5524823cd90f2c41480a51151d2a039113b7bd
| 3,400
|
package demo;
import org.simplejavamail.converter.EmailConverter;
import org.simplejavamail.email.CalendarMethod;
import org.simplejavamail.email.Email;
import org.simplejavamail.email.EmailBuilder;
import org.simplejavamail.email.EmailPopulatingBuilder;
import testutil.CalendarHelper;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;
import java.io.IOException;
import java.nio.charset.Charset;
/**
* Demonstration program for the Simple Java Mail framework. Just fill your gmail, password and press GO.
*/
@SuppressWarnings({"WeakerAccess", "UnusedAssignment"})
public class FullEmailDemoApp extends DemoAppBase {
public static void main(final String[] args) throws IOException {
testMixedRelatedAlternativeIncludingCalendarAndMessageParsingUsingVariousMailers();
}
private static void testMixedRelatedAlternativeIncludingCalendarAndMessageParsingUsingVariousMailers() throws IOException {
final EmailPopulatingBuilder emailPopulatingBuilderNormal = EmailBuilder.startingBlank();
emailPopulatingBuilderNormal.from("Simple Java Mail demo", "simplejavamail@demo.app");
// don't forget to add your own address here ->
emailPopulatingBuilderNormal.to("C.Cane", YOUR_GMAIL_ADDRESS);
emailPopulatingBuilderNormal.withPlainText("Plain text content (ignored in favor of HTML by modern browsers)");
emailPopulatingBuilderNormal.withHTMLText("<p>This is an email with \"mixed\", \"related\" and \"alternative\" content: it contains a plain " +
"text part (ignored in favor of HTML by modern clients), an HTML content part (this HTML text) which references a related " +
"content part (the embedded image) and a iCalendar content part. In addition this email contains a separate attachment as " +
"well.</p><img src='cid:thumbsup'>" +
"<p><b>Formal structure:</b><br>" +
"<ul>" +
" <li>mixed (root)<ul>" +
" <li>related<ul>" +
" <li>alternative<ul>" +
" <li>plain text</li>" +
" <li>HTML text</li>" +
" </ul></li>" +
" <li>embeddable image (cid:thumbsup) </li>" +
" </ul></li>" +
" <li>attachment</li>" +
" </ul></li>" +
"</ul></p>"); // makes it alternative
emailPopulatingBuilderNormal.withSubject("Email with mixed + related + alternative content (including iCalendar event)");
// add two text files in different ways and a black thumbs up embedded image ->
emailPopulatingBuilderNormal.withAttachment("dresscode.txt", new ByteArrayDataSource("Black Tie Optional", "text/plain"));
emailPopulatingBuilderNormal.withAttachment("location.txt", "On the moon!".getBytes(Charset.defaultCharset()), "text/plain");
emailPopulatingBuilderNormal.withEmbeddedImage("thumbsup", produceThumbsUpImage(), "image/png");
emailPopulatingBuilderNormal.withCalendarText(CalendarMethod.REQUEST, CalendarHelper.createCalendarEvent());
// let's try producing and then consuming a MimeMessage ->
Email emailNormal = emailPopulatingBuilderNormal.buildEmail();
final MimeMessage mimeMessage = EmailConverter.emailToMimeMessage(emailNormal);
final Email emailFromMimeMessage = EmailConverter.mimeMessageToEmail(mimeMessage);
mailerSMTP.sendMail(emailNormal);
mailerTLS.sendMail(emailNormal);
mailerSSL.sendMail(emailNormal);
mailerTLS.sendMail(emailFromMimeMessage); // should produce the exact same result as emailPopulatingBuilderNormal!
}
}
| 50.746269
| 145
| 0.756471
|
ff03c22a66616a17af124b6e3d9e0419662384ea
| 1,576
|
package util;
/**
* Created by Nick on 1/2/2015.
* <p>
* This class was created because a lot of the Utils classes need to be
* a bit more in depth on the results of their methods than just returning "true"
*/
public class Response {
private boolean isSuccessful = false; //defaults to failed
private boolean isWhisperable = false;
private String responseText = "";
private boolean allowWhispers = true;
public Response() {
//default, blank response
}
public Response(String responseText){
// new Response with text and default false
this.responseText = responseText;
}
public Response(String responseText, boolean isSuccessful){
this.responseText = responseText;
this.isSuccessful = isSuccessful;
}
public void wasSuccessful() {
this.isSuccessful = true;
}
public void canWhisper(){
if (allowWhispers)
this.isWhisperable = true;
}
public void setResponseText(String responseText) {
this.responseText = responseText;
}
public String getResponseText() {
return responseText;
}
/**
* @return If the method was successfully completed or not.
*/
public boolean isSuccessful() {
return isSuccessful;
}
public boolean isWhisperable(){
return isWhisperable;
}
public void addSenderToResponseText(String sender){
if (!sender.contains("@")) sender = "@" + sender;
this.setResponseText(sender + ", " + getResponseText());
allowWhispers = false;
}
}
| 25.015873
| 81
| 0.646574
|
9c39498231cb549246f44fea6da3520172bceca2
| 1,629
|
/*
* Copyright (C) 2015 Mobile Jazz
*
* 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.mobilejazz.vastra.strategies.timestamp;
import com.mobilejazz.vastra.ValidationStrategyDataSource;
import com.mobilejazz.vastra.strategies.ValidationStrategy;
import com.mobilejazz.vastra.strategies.ValidationStrategyResult;
public class TimestampValidationStrategy implements ValidationStrategy {
@Override
public <T extends ValidationStrategyDataSource> ValidationStrategyResult isValid(T object) {
TimestampValidationStrategyDataSource dataSource;
if (object instanceof TimestampValidationStrategyDataSource) {
dataSource = (TimestampValidationStrategyDataSource) object;
} else {
throw new IllegalArgumentException("object != TimestampValidationStrategyDataSource");
}
if (dataSource.lastUpdate() == null) {
return ValidationStrategyResult.UNKNOWN;
}
long diff = System.currentTimeMillis() - dataSource.lastUpdate().getTime();
return diff > dataSource.expiryTime() ? ValidationStrategyResult.INVALID
: ValidationStrategyResult.VALID;
}
}
| 37.022727
| 94
| 0.766728
|
cd6b503bc1149afb12f2abe9c2121de671b2c559
| 280
|
package com.atguigu.gmall.auth.feign;
import com.atguigu.gmall.ums.api.GmallUmsApi;
import org.springframework.cloud.openfeign.FeignClient;
/**
* @author lzzzzz
* @create 2020-01-15 21:07
*/
@FeignClient("ums-service")
public interface UmsFeignClient extends GmallUmsApi {
}
| 21.538462
| 55
| 0.771429
|
cb60c11ac42593151308e5ebbac3951e5710d2bf
| 2,964
|
package cc.zip.charon.mixin.mixins;
import cc.zip.charon.Charon;
import cc.zip.charon.event.events.BlockEvent;
import cc.zip.charon.event.events.ProcessRightClickBlockEvent;
import cc.zip.charon.features.modules.player.TpsSync;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.multiplayer.PlayerControllerMP;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin({PlayerControllerMP.class})
public class MixinPlayerControllerMP {
@Redirect(
method = {"onPlayerDamageBlock"},
at = @At(
value = "INVOKE",
target = "Lnet/minecraft/block/state/IBlockState;getPlayerRelativeBlockHardness(Lnet/minecraft/entity/player/EntityPlayer;Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;)F"
)
)
public float getPlayerRelativeBlockHardnessHook(IBlockState state, EntityPlayer player, World worldIn, BlockPos pos) {
return state.getPlayerRelativeBlockHardness(player, worldIn, pos) * (TpsSync.getInstance().isOn() && (Boolean)TpsSync.getInstance().mining.getValue() ? 1.0F / Charon.serverManager.getTpsFactor() : 1.0F);
}
@Inject(
method = {"clickBlock"},
at = {@At("HEAD")},
cancellable = true
)
private void clickBlockHook(BlockPos pos, EnumFacing face, CallbackInfoReturnable<Boolean> info) {
BlockEvent event = new BlockEvent(3, pos, face);
MinecraftForge.EVENT_BUS.post(event);
}
@Inject(
method = {"onPlayerDamageBlock"},
at = {@At("HEAD")},
cancellable = true
)
private void onPlayerDamageBlockHook(BlockPos pos, EnumFacing face, CallbackInfoReturnable<Boolean> info) {
BlockEvent event = new BlockEvent(4, pos, face);
MinecraftForge.EVENT_BUS.post(event);
}
@Inject(
method = {"processRightClickBlock"},
at = {@At("HEAD")},
cancellable = true
)
public void processRightClickBlock(EntityPlayerSP player, WorldClient worldIn, BlockPos pos, EnumFacing direction, Vec3d vec, EnumHand hand, CallbackInfoReturnable<EnumActionResult> cir) {
ProcessRightClickBlockEvent event = new ProcessRightClickBlockEvent(pos, hand, Minecraft.instance.player.getHeldItem(hand));
MinecraftForge.EVENT_BUS.post(event);
if (event.isCanceled()) {
cir.cancel();
}
}
}
| 40.60274
| 209
| 0.755735
|
2e97d4ffe52fddd165ab8665f3e363a7333ccb89
| 581
|
package hu.unideb.rft.parkingmanagement.entity;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.time.LocalDateTime;
@Entity
@Table(name = "PARKING_PASS")
@Getter
@Setter
public class ParkingPass extends BaseEntity {
@ManyToOne
@JoinColumn(name = "CAR_ID", nullable = false)
Car car;
@ManyToOne
@JoinColumn(name = "PARKING_ZONE_ID", nullable = false)
ParkingZone parkingZone;
@Column(name = "VALIDITY_START")
LocalDateTime validityStart;
@Column(name = "VALIDITY_END")
LocalDateTime validityEnd;
}
| 19.366667
| 59
| 0.724613
|
1f22d20cc8c43cacbda7975bb35aa694ae92ed3b
| 6,038
|
package org.openkilda.integration.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.json.simple.JSONObject;
import org.openkilda.helper.RestClientManager;
import org.openkilda.integration.converter.IslLinkConverter;
import org.openkilda.integration.converter.PortConverter;
import org.openkilda.integration.exception.ContentNotFoundException;
import org.openkilda.integration.exception.IntegrationException;
import org.openkilda.integration.model.response.IslLink;
import org.openkilda.model.IslLinkInfo;
import org.openkilda.model.PortInfo;
import org.openkilda.model.SwitchInfo;
import org.openkilda.service.ApplicationService;
import org.openkilda.utility.ApplicationProperties;
import org.openkilda.utility.CollectionUtil;
import org.openkilda.utility.IoUtil;
import org.openkilda.utility.JsonUtil;
/**
* The Class SwitchIntegrationService.
*
* @author Gaurav Chugh
*/
@Service
public class SwitchIntegrationService {
private static final Logger LOGGER = LoggerFactory.getLogger(SwitchIntegrationService.class);
@Autowired
private RestClientManager restClientManager;
@Autowired
private ApplicationProperties applicationProperties;
@Autowired
private ApplicationService applicationService;
/**
* Gets the switches.
*
* @return the switches
* @throws IntegrationException
*/
public List<SwitchInfo> getSwitches() {
HttpResponse response = restClientManager.invoke(applicationProperties.getSwitches(),
HttpMethod.GET, "", "", applicationService.getAuthHeader());
if (RestClientManager.isValidResponse(response)) {
List<SwitchInfo> switchesResponse =
restClientManager.getResponseList(response, SwitchInfo.class);
return getSwitchInfoSetName(switchesResponse);
}
return null;
}
/**
* Gets the SwitchInfoSetName.
*
* @return the switches
* @throws IntegrationException
*/
private List<SwitchInfo> getSwitchInfoSetName(List<SwitchInfo> switches) {
LOGGER.info("Inside getSwitchInfoSetName : Start");
if (switches != null && !StringUtils.isEmpty(switches)) {
Map<String, String> csNames = getCustomSwitchNameFromFile();
for (SwitchInfo switchInfo : switches) {
switchInfo.setName(customSwitchName(csNames, switchInfo.getSwitchId()));
}
}
return switches;
}
/**
* This Method is used to set custom Switch name.
*
* @param csNames
* @param switchId
* @return
*/
public String customSwitchName(Map<String, String> csNames, String switchId) {
if (csNames != null && !StringUtils.isEmpty(csNames) && csNames.size() > 0) {
if (csNames.containsKey(switchId.toLowerCase())
|| csNames.containsKey(switchId.toUpperCase())) {
if (!IoUtil.chkStringIsNotEmpty(csNames.get(switchId))) {
return switchId;
} else {
return csNames.get(switchId);
}
} else {
return switchId;
}
} else
return switchId;
}
/**
* Gets the isl links.
*
* @return the isl links
*/
public List<IslLinkInfo> getIslLinks() {
HttpResponse response = restClientManager.invoke(applicationProperties.getLinks(),
HttpMethod.GET, "", "", applicationService.getAuthHeader());
if (RestClientManager.isValidResponse(response)) {
List<IslLink> links = restClientManager.getResponseList(response, IslLink.class);
if (CollectionUtil.isEmpty(links)) {
throw new ContentNotFoundException();
}
return IslLinkConverter.toIslLinksInfo(links);
}
return null;
}
/**
* Gets the switch ports.
*
* @return the switch ports
* @throws IntegrationException
*/
public List<PortInfo> getSwitchPorts(final String switchId) throws IntegrationException {
try {
HttpResponse response = restClientManager.invoke(applicationProperties.getSwitchPorts(),
HttpMethod.GET, "", "", "");
if (RestClientManager.isValidResponse(response)) {
String responseEntity = IoUtil.toString(response.getEntity().getContent());
JSONObject jsonObject = JsonUtil.toObject(responseEntity, JSONObject.class);
return PortConverter.toPortsInfo(jsonObject, switchId);
}
} catch (IOException exception) {
LOGGER.error("Exception in getSwitchPorts " + exception.getMessage(), exception);
throw new IntegrationException(exception);
}
return null;
}
@SuppressWarnings("unchecked")
public Map<String, String> getCustomSwitchNameFromFile() {
Map<String, String> csNames = new HashMap<String, String>();
InputStream inputStream = null;
String data = null;
try {
inputStream = new URL(applicationProperties.getSwitchDataFilePath()).openStream();
if (inputStream != null) {
data = IoUtil.toString(inputStream);
if (data != null && !StringUtils.isEmpty(data)) {
csNames = JsonUtil.toObject(data, HashMap.class);
}
}
} catch (Exception ex) {
LOGGER.error("Inside getCustomSwitchNameFromFile unable to find switch file path Exception :",
ex);
}
return csNames;
}
}
| 34.112994
| 106
| 0.65419
|
16a1b271d456100990657da7a3ebd0b4a625446e
| 4,270
|
/*-
* ========================LICENSE_START=================================
* EWeather
* ======================================================================
* Copyright (C) 2018 - 2019 Erwan Le Tutour
* ======================================================================
* 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.
* =========================LICENSE_END==================================
*/
package com.myApp.weather.controller;
import com.myApp.weather.form.CoordinateForm;
import com.myApp.weather.form.Forecast;
import com.myApp.weather.service.ResponseToFormService;
import com.myApp.weather.service.WeatherService;
import com.myApp.weather.utils.MessageHelper;
import com.myApp.weather.weatherModel.toparse.ForecastResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.thymeleaf.util.StringUtils;
@Controller
/**
* Main controller for the {@link com.myApp.weather.WeatherApplication} web page
*
* @author eletutour
* @since 1.0.0
*/
public class WeatherController {
private final WeatherService weatherService;
private final ResponseToFormService responseToForm;
@Autowired
public WeatherController(WeatherService weatherService, ResponseToFormService responseToForm){
this.weatherService = weatherService;
this.responseToForm = responseToForm;
}
@GetMapping("/")
public String index(Model model) {
CoordinateForm coordinateForm = new CoordinateForm();
model.addAttribute(coordinateForm);
return "help";
}
@GetMapping("/home")
public String home(Model model){
CoordinateForm coordinateForm = new CoordinateForm();
model.addAttribute(coordinateForm);
return "home";
}
@GetMapping("/history")
public String history(Model model){
CoordinateForm coordinateForm = new CoordinateForm();
model.addAttribute(coordinateForm);
return "history";
}
@GetMapping("/help")
public String help(Model model){
return index(model);
}
@PostMapping("/getWeather")
public String getWeather(@ModelAttribute("coordinateForm")CoordinateForm coordinateForm, Model model){
CoordinateForm form = new CoordinateForm();
model.addAttribute(form);
if(StringUtils.isEmpty(coordinateForm.getLocation())){
//should never happened because it's a required field
MessageHelper.addDangerAttribute(model, "The location field is null or Empty");
} else {
ForecastResponse forecast = weatherService.getForecast(coordinateForm.getLocation());
if ("Fake forecast".equals(forecast.getLocation())){
MessageHelper.addWarningAttribute(model, "This is a fake response because something bad happened.");
}
Forecast f = responseToForm.darkskyResponseToForm(forecast);
model.addAttribute("forecast", f);
}
return "home";
}
}
| 36.810345
| 116
| 0.683138
|
9d7cb547410bc1e702c600d6a13ccabc2ba888f3
| 1,112
|
package problems.easy;
/**
* Problem: https://leetcode.com/problems/reverse-words-in-a-string-iii/
* Time Complexity: O(N)
* Space Complexity: O(N)
*/
class Solution557 {
public String reverseWords(String s) {
int start = 0, end = 0;
boolean isSubstring = false;
StringBuilder result = new StringBuilder(s);
for (int i = 0; i < s.length(); i++) {
if (!isSubstring && s.charAt(i) != ' ') {
start = i;
isSubstring = true;
} else if (isSubstring && s.charAt(i) != ' ') {
end = i;
} else if (isSubstring && s.charAt(i) == ' ') {
swap(result, start, end);
isSubstring = false;
}
}
if (isSubstring) {
swap(result, start, end);
}
return result.toString();
}
private void swap(StringBuilder s, int start, int end) {
char t;
while (start < end) {
t = s.charAt(start);
s.setCharAt(start++, s.charAt(end));
s.setCharAt(end--, t);
}
}
}
| 27.8
| 72
| 0.482914
|
8be99c329bb63efa3de278251067f2700176f07e
| 8,021
|
/***********************************************************************
* Copyright (c) 2013-2019 Commonwealth Computer Research, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License, Version 2.0
* which accompanies this distribution and is available at
* http://www.opensource.org/licenses/apache2.0.php.
***********************************************************************/
package org.locationtech.geomesa.accumulo.nativeapi;
import org.geotools.factory.CommonFactoryFinder;
import org.junit.Assert;
import org.junit.Test;
import org.locationtech.geomesa.api.GeoMesaQuery;
import org.opengis.filter.Filter;
import org.opengis.filter.FilterFactory2;
import org.opengis.filter.expression.PropertyName;
import java.util.Date;
public class GeoMesaQueryTest {
private static final Date DTG_0 = new Date(116, 0, 1);
private static final Date DTG_0_POST = new Date(DTG_0.getTime() + 1L);
private static final Date DTG_1 = new Date(116, 2, 1);
private static final Date DTG_1_PRE = new Date(DTG_1.getTime() - 1L);
private static final Date NO_DTG = null;
private static final FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2();
private static PropertyName DTGProperty = ff.property("dtg");
private GeoMesaQuery.GeoMesaQueryBuilder getQueryBuilder() {
return GeoMesaQuery.GeoMesaQueryBuilder.builder()
.within(-79.0, 37.0, -77.0, 39.0);
}
private Filter getDuringFilter(Date start, boolean includeStart, Date end, boolean includeEnd) {
// create a query from these temporal parameters
return getQueryBuilder()
.during(start, includeStart, end, includeEnd)
.getTemporalFilter();
}
private Filter getBeforeAfterFilter(Date start, Date end) {
// create a query from these temporal parameters
return getQueryBuilder()
.before(end)
.after(start)
.getTemporalFilter();
}
private Filter getAfterFilter(Date date) {
// create a query from these temporal parameters
return getQueryBuilder()
.after(date)
.getTemporalFilter();
}
private Filter getBeforeFilter(Date date) {
// create a query from these temporal parameters
return getQueryBuilder()
.before(date)
.getTemporalFilter();
}
private Filter after(Date date) {
return ff.after(DTGProperty, ff.literal(date));
}
private Filter before(Date date) {
return ff.before(DTGProperty, ff.literal(date));
}
private Filter between(Date start, Date end) {
return ff.between(DTGProperty, ff.literal(start), ff.literal(end));
}
@Test
public void testNoTimeRange() {
Assert.assertEquals(Filter.INCLUDE, getDuringFilter(NO_DTG, false, NO_DTG, false));
Assert.assertEquals(Filter.INCLUDE, getDuringFilter(NO_DTG, false, NO_DTG, true));
Assert.assertEquals(Filter.INCLUDE, getDuringFilter(NO_DTG, true, NO_DTG, false));
Assert.assertEquals(Filter.INCLUDE, getDuringFilter(NO_DTG, true, NO_DTG, true));
}
@Test
public void testAfter() {
Assert.assertEquals(after(DTG_0_POST), getDuringFilter(DTG_0, false, NO_DTG, false));
Assert.assertEquals(after(DTG_0_POST), getDuringFilter(DTG_0, false, NO_DTG, true));
Assert.assertEquals(after(DTG_0), getDuringFilter(DTG_0, true, NO_DTG, false));
Assert.assertEquals(after(DTG_0), getDuringFilter(DTG_0, true, NO_DTG, true));
Assert.assertEquals(after(DTG_0_POST), getAfterFilter(DTG_0));
}
@Test
public void testBefore() {
Assert.assertEquals(before(DTG_1_PRE), getDuringFilter(NO_DTG, false, DTG_1, false));
Assert.assertEquals(before(DTG_1), getDuringFilter(NO_DTG, false, DTG_1, true));
Assert.assertEquals(before(DTG_1_PRE), getDuringFilter(NO_DTG, true, DTG_1, false));
Assert.assertEquals(before(DTG_1), getDuringFilter(NO_DTG, true, DTG_1, true));
Assert.assertEquals(before(DTG_0), getBeforeFilter(DTG_0_POST));
}
@Test
public void testBetween() {
Assert.assertEquals(between(DTG_0_POST, DTG_1_PRE), getDuringFilter(DTG_0, false, DTG_1, false));
Assert.assertEquals(between(DTG_0_POST, DTG_1), getDuringFilter(DTG_0, false, DTG_1, true));
Assert.assertEquals(between(DTG_0, DTG_1_PRE), getDuringFilter(DTG_0, true, DTG_1, false));
Assert.assertEquals(between(DTG_0, DTG_1), getDuringFilter(DTG_0, true, DTG_1, true));
Assert.assertEquals(between(DTG_0_POST, DTG_1_PRE), getBeforeAfterFilter(DTG_0, DTG_1));
}
@Test
public void testInvalidTimeRange() {
Assert.assertEquals(Filter.INCLUDE, getDuringFilter(DTG_0, false, DTG_0, false));
Assert.assertEquals(Filter.INCLUDE, getDuringFilter(DTG_0, false, DTG_0, true));
Assert.assertEquals(Filter.INCLUDE, getDuringFilter(DTG_0, true, DTG_0, false));
Assert.assertNotEquals(Filter.INCLUDE, getDuringFilter(DTG_0, true, DTG_0, true));
Assert.assertEquals(Filter.INCLUDE, getDuringFilter(DTG_1, false, DTG_1, false));
Assert.assertEquals(Filter.INCLUDE, getDuringFilter(DTG_1, false, DTG_1, true));
Assert.assertEquals(Filter.INCLUDE, getDuringFilter(DTG_1, true, DTG_1, false));
Assert.assertNotEquals(Filter.INCLUDE, getDuringFilter(DTG_1, true, DTG_1, true));
}
@Test
public void testAllTime() {
Assert.assertEquals(Filter.INCLUDE,
getQueryBuilder().during(DTG_0, false, DTG_1, false).allTime().getTemporalFilter());
Assert.assertEquals(Filter.INCLUDE,
getQueryBuilder().during(DTG_0, false, DTG_1, true).allTime().getTemporalFilter());
Assert.assertEquals(Filter.INCLUDE,
getQueryBuilder().during(DTG_0, true, DTG_1, false).allTime().getTemporalFilter());
Assert.assertEquals(Filter.INCLUDE,
getQueryBuilder().during(DTG_0, true, DTG_1, true).allTime().getTemporalFilter());
Assert.assertEquals(Filter.INCLUDE, getQueryBuilder().after(DTG_0).allTime().getTemporalFilter());
Assert.assertEquals(Filter.INCLUDE, getQueryBuilder().before(DTG_0).allTime().getTemporalFilter());
}
@Test
public void testCompositionOverwrites() {
// before(a).during(b,c) -> during(b,c)
Assert.assertEquals(
getQueryBuilder().before(DTG_1_PRE).during(DTG_0, true, DTG_1, true).getTemporalFilter(),
getQueryBuilder().during(DTG_0, true, DTG_1, true).getTemporalFilter()
);
// during(a,b).before(c) -> during(a,c)
Assert.assertEquals(
getQueryBuilder().during(DTG_0, true, DTG_1, true).before(DTG_1).getTemporalFilter(),
getQueryBuilder().during(DTG_0, true, DTG_1_PRE, true).getTemporalFilter()
);
// after(a).during(b,c) -> during(b,c)
Assert.assertEquals(
getQueryBuilder().after(DTG_1_PRE).during(DTG_0, true, DTG_1, true).getTemporalFilter(),
getQueryBuilder().during(DTG_0, true, DTG_1, true).getTemporalFilter()
);
// during(a,b).after(c) -> during(a,c)
Assert.assertEquals(
getQueryBuilder().during(DTG_0, true, DTG_1, true).after(DTG_0).getTemporalFilter(),
getQueryBuilder().during(DTG_0_POST, true, DTG_1, true).getTemporalFilter()
);
// before(a).before(b) -> before(b)
Assert.assertEquals(
getQueryBuilder().before(DTG_0).before(DTG_1).getTemporalFilter(),
getQueryBuilder().before(DTG_1).getTemporalFilter()
);
// after(a).after(b) -> after(b)
Assert.assertEquals(
getQueryBuilder().after(DTG_0).after(DTG_1).getTemporalFilter(),
getQueryBuilder().after(DTG_1).getTemporalFilter()
);
}
}
| 43.830601
| 107
| 0.65902
|
7641339c2261d379a015502a562ca316cfdfe2de
| 1,096
|
package net.minecraft.network.play.client;
import java.io.IOException;
import net.minecraft.item.ItemStack;
import net.minecraft.network.Packet;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.play.INetHandlerPlayServer;
public class C10PacketCreativeInventoryAction implements Packet {
private int slotId;
private ItemStack stack;
public C10PacketCreativeInventoryAction() {
}
public C10PacketCreativeInventoryAction(int var1, ItemStack var2) {
this.slotId = var1;
this.stack = var2.copy();
}
public void processPacket(INetHandlerPlayServer var1) {
var1.processCreativeInventoryAction(this);
}
public void readPacketData(PacketBuffer var1) throws IOException {
this.slotId = var1.readShort();
this.stack = var1.readItemStackFromBuffer();
}
public void writePacketData(PacketBuffer var1) throws IOException {
var1.writeShort(this.slotId);
var1.a(this.stack);
}
public int getSlotId() {
return this.slotId;
}
public ItemStack getStack() {
return this.stack;
}
}
| 25.488372
| 70
| 0.730839
|
6a2c1cd79f134ccd92ce90fc243066075816ee2c
| 1,421
|
package com.twu.biblioteca.router;
import com.twu.biblioteca.Service.BibliotecaService;
import com.twu.biblioteca.router.handler.*;
public class BibliotecaRouter {
private RouterContext routerContext;
private final BibliotecaService bibliotecaService;
public BibliotecaRouter(RouterState routerState, BibliotecaService bibliotecaService) {
this.routerContext = new RouterContext(routerState);
this.bibliotecaService = bibliotecaService;
}
public RouterMessage getRouterMessage(String userInput) throws Exception {
return getActionHandler().handle(userInput);
}
private IActionHandler getActionHandler() throws Exception {
switch (routerContext.getCurrentState()) {
case Initialize:
return new InitialHandler(routerContext);
case MainMenu:
return new MainMenuHandler(routerContext, bibliotecaService);
case CheckBook:
return new CheckBookHandler(routerContext, bibliotecaService);
case ReturnBook:
return new ReturnBookHandler(routerContext, bibliotecaService);
case CheckMovie:
return new CheckMovieHandler(routerContext, bibliotecaService);
case Login:
return new LoginHandler(routerContext, bibliotecaService);
}
throw new Exception("Invalid router state!");
}
}
| 35.525
| 91
| 0.691766
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.