repo_name stringlengths 7 70 | file_path stringlengths 9 215 | context list | import_statement stringlengths 47 10.3k | token_num int64 643 100k | cropped_code stringlengths 62 180k | all_code stringlengths 62 224k | next_line stringlengths 9 1.07k | gold_snippet_index int64 0 117 | created_at stringlengths 25 25 | level stringclasses 9
values |
|---|---|---|---|---|---|---|---|---|---|---|
kash-developer/HomeDeviceEmulator | app/src/main/java/kr/or/kashi/hde/widget/DeviceTestPartView.java | [
{
"identifier": "HomeDevice",
"path": "app/src/main/java/kr/or/kashi/hde/HomeDevice.java",
"snippet": "public class HomeDevice {\n private static final String TAG = HomeDevice.class.getSimpleName();\n private static final String PROP_PREFIX = \"0.\";\n\n /**\n * Application registers {@link... | import java.util.List;
import kr.or.kashi.hde.HomeDevice;
import kr.or.kashi.hde.R;
import kr.or.kashi.hde.test.DeviceTestCallback;
import kr.or.kashi.hde.test.DeviceTestRunner;
import kr.or.kashi.hde.util.DebugLog;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import junit.framework.TestCase;
import junit.framework.TestResult; | 5,855 | /*
* Copyright (C) 2023 Korea Association of AI Smart Home.
* Copyright (C) 2023 KyungDong Navien 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 kr.or.kashi.hde.widget;
public class DeviceTestPartView extends LinearLayout implements DeviceTestCallback {
private static final String TAG = DeviceTestPartView.class.getSimpleName();
private final Context mContext;
private final Handler mHandler;
private final DeviceTestRunner mDeviceTestRunner;
private final DeviceTestReportDialog mReportDialog;
private TextView mTestStateText;
private TextView mTestProgressText;
private Button mReportButton;
private TestResultView mTestResultView;
public DeviceTestPartView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
mContext = context;
mHandler = new Handler(Looper.getMainLooper());
mDeviceTestRunner = new DeviceTestRunner(mHandler);
mReportDialog = new DeviceTestReportDialog(context);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mTestStateText = findViewById(R.id.test_state_text);
mTestProgressText = findViewById(R.id.test_progress_text);
mReportButton = findViewById(R.id.report_button);
mReportButton.setOnClickListener(view -> onReportClicked());
mTestResultView = findViewById(R.id.test_result_view);
mDeviceTestRunner.addCallback(this);
mDeviceTestRunner.addCallback(mTestResultView);
mDeviceTestRunner.addCallback(mReportDialog);
}
public DeviceTestRunner getTestRunner() {
return mDeviceTestRunner;
}
| /*
* Copyright (C) 2023 Korea Association of AI Smart Home.
* Copyright (C) 2023 KyungDong Navien 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 kr.or.kashi.hde.widget;
public class DeviceTestPartView extends LinearLayout implements DeviceTestCallback {
private static final String TAG = DeviceTestPartView.class.getSimpleName();
private final Context mContext;
private final Handler mHandler;
private final DeviceTestRunner mDeviceTestRunner;
private final DeviceTestReportDialog mReportDialog;
private TextView mTestStateText;
private TextView mTestProgressText;
private Button mReportButton;
private TestResultView mTestResultView;
public DeviceTestPartView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
mContext = context;
mHandler = new Handler(Looper.getMainLooper());
mDeviceTestRunner = new DeviceTestRunner(mHandler);
mReportDialog = new DeviceTestReportDialog(context);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mTestStateText = findViewById(R.id.test_state_text);
mTestProgressText = findViewById(R.id.test_progress_text);
mReportButton = findViewById(R.id.report_button);
mReportButton.setOnClickListener(view -> onReportClicked());
mTestResultView = findViewById(R.id.test_result_view);
mDeviceTestRunner.addCallback(this);
mDeviceTestRunner.addCallback(mTestResultView);
mDeviceTestRunner.addCallback(mReportDialog);
}
public DeviceTestRunner getTestRunner() {
return mDeviceTestRunner;
}
| public boolean startTest(List<HomeDevice> devices) { | 0 | 2023-11-10 01:19:44+00:00 | 8k |
Bug1312/dm_locator | src/main/java/com/bug1312/dm_locator/mixins/FlightPanelBlockMixin.java | [
{
"identifier": "Register",
"path": "src/main/java/com/bug1312/dm_locator/Register.java",
"snippet": "public class Register {\n\t// Items\n\tpublic static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, ModMain.MOD_ID);\n\tpublic static final RegistryObject<Item> WRIT... | import java.util.UUID;
import java.util.function.Supplier;
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.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import com.bug1312.dm_locator.Register;
import com.bug1312.dm_locator.StructureHelper;
import com.bug1312.dm_locator.tiles.FlightPanelTileEntity;
import com.swdteam.common.block.AbstractRotateableWaterLoggableBlock;
import com.swdteam.common.block.IBlockTooltip;
import com.swdteam.common.block.tardis.DataWriterBlock;
import com.swdteam.common.block.tardis.FlightPanelBlock;
import com.swdteam.common.init.DMFlightMode;
import com.swdteam.common.init.DMItems;
import com.swdteam.common.init.DMSoundEvents;
import com.swdteam.common.item.DataModuleItem;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.item.ItemEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.InventoryHelper;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.state.BooleanProperty;
import net.minecraft.state.IntegerProperty;
import net.minecraft.state.StateContainer;
import net.minecraft.state.properties.BlockStateProperties;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.SoundEvents;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.math.shapes.ISelectionContext;
import net.minecraft.util.math.shapes.VoxelShape;
import net.minecraft.util.math.shapes.VoxelShapes;
import net.minecraft.util.math.vector.Vector3d;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.World; | 3,741 | // Copyright 2023 Bug1312 (bug@bug1312.com)
package com.bug1312.dm_locator.mixins;
@Mixin(FlightPanelBlock.class)
public abstract class FlightPanelBlockMixin extends AbstractRotateableWaterLoggableBlock implements IBlockTooltip {
public FlightPanelBlockMixin(Properties properties) { super(properties); }
private static final BooleanProperty HAS_LOCATOR = BooleanProperty.create("has_locator");
private static final IntegerProperty CARTRIDGE = DataWriterBlock.CARTRIDGE_TYPE;
private static final VoxelShape N_ADDON_SHAPE = VoxelShapes.box(6/16D, 2/16D, 8/16D, 1, 8/16D, 1);
private static final VoxelShape E_ADDON_SHAPE = VoxelShapes.box(0, 2/16D, 6/16D, 8/16D, 8/16D, 1);
private static final VoxelShape S_ADDON_SHAPE = VoxelShapes.box(0, 2/16D, 0, 10/16D, 8/16D, 8/16D);
private static final VoxelShape W_ADDON_SHAPE = VoxelShapes.box(8/16D, 2/16D, 0, 1, 8/16D, 10/16D);
private static VoxelShape getAddonShape(BlockState state) {
switch (state.getValue(BlockStateProperties.HORIZONTAL_FACING)) {
default:
case NORTH: return N_ADDON_SHAPE;
case EAST: return E_ADDON_SHAPE;
case SOUTH: return S_ADDON_SHAPE;
case WEST: return W_ADDON_SHAPE;
}
}
private static boolean isMouseOnLocator(BlockState state, BlockPos pos, Vector3d mouse, IBlockReader world) {
return state.getValue(HAS_LOCATOR) && getAddonShape(state).bounds().inflate(0.5/16D).contains(mouse.subtract(pos.getX(), pos.getY(), pos.getZ()));
}
private static void eject(BlockState state, World world, BlockPos pos, FlightPanelTileEntity tile) {
if (tile.cartridge != null && tile.cartridge.getItem() instanceof DataModuleItem) {
Direction direction = state.getValue(BlockStateProperties.HORIZONTAL_FACING);
ItemEntity itemEntity = new ItemEntity(EntityType.ITEM, world);
itemEntity.absMoveTo((pos.getX() + 0.5 + direction.getStepX()), pos.getY(), (pos.getZ() + 0.5 + direction.getStepZ()), 0, 0);
itemEntity.setDeltaMovement((direction.getStepX() / 10D), 0, (direction.getStepZ() / 10D));
itemEntity.setItem(tile.cartridge);
world.addFreshEntity(itemEntity);
tile.cartridge = ItemStack.EMPTY;
}
world.setBlockAndUpdate(pos, state.setValue(CARTRIDGE, 0));
}
@Inject(at = @At("RETURN"), method = "<init>*", remap = false)
public void constructor(final CallbackInfo ci) {
this.registerDefaultState(this.defaultBlockState().setValue(HAS_LOCATOR, Boolean.valueOf(false)).setValue(CARTRIDGE, 0));
}
@Override
public void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder) {
super.createBlockStateDefinition(builder);
builder.add(HAS_LOCATOR, CARTRIDGE);
}
@Inject(at = @At("RETURN"), method = "getShape", cancellable = true, remap = false)
public void getShape(final BlockState state, final IBlockReader world, final BlockPos pos, final ISelectionContext context, final CallbackInfoReturnable<VoxelShape> ci) {
if (state.getValue(HAS_LOCATOR)) ci.setReturnValue(VoxelShapes.or(ci.getReturnValue(), getAddonShape(state)));
}
@Inject(at = @At("HEAD"), method = "use", cancellable = true, remap = false)
public void use(final BlockState state, final World world, final BlockPos pos, final PlayerEntity player, final Hand handIn, final BlockRayTraceResult result, final CallbackInfoReturnable<ActionResultType> ci) {
if (isMouseOnLocator(state, pos, result.getLocation(), world)) {
if (!world.isClientSide()) {
TileEntity tile = world.getBlockEntity(pos);
if (tile != null && tile instanceof FlightPanelTileEntity) {
FlightPanelTileEntity panel = (FlightPanelTileEntity) tile;
ItemStack slotStack = panel.cartridge;
if (slotStack != null && !slotStack.isEmpty()) {
if (player.isShiftKeyDown()) {
eject(state, world, pos, panel);
ci.setReturnValue(ActionResultType.CONSUME);
}
} else {
ItemStack heldStack = player.getItemInHand(handIn);
if (heldStack != null && !heldStack.isEmpty()) {
Item item = heldStack.getItem();
if ((slotStack == null || slotStack.isEmpty()) && item instanceof DataModuleItem) {
panel.cartridge = heldStack.split(1);
if (player.abilities.instabuild) heldStack.grow(1);
world.setBlockAndUpdate(pos, state.setValue(CARTRIDGE, heldStack.getItem() == DMItems.DATA_MODULE.get() ? 1 : 2));
world.playSound((PlayerEntity) null, pos.getX(), pos.getY(), pos.getZ(), DMSoundEvents.TARDIS_MODULE_INSERT.get(), SoundCategory.BLOCKS, 1, 1);
ci.setReturnValue(ActionResultType.CONSUME);
}
}
}
}
}
} else if (!state.getValue(HAS_LOCATOR)) {
ItemStack heldStack = player.getItemInHand(handIn);
if (heldStack != null && !heldStack.isEmpty()) {
Item item = heldStack.getItem(); | // Copyright 2023 Bug1312 (bug@bug1312.com)
package com.bug1312.dm_locator.mixins;
@Mixin(FlightPanelBlock.class)
public abstract class FlightPanelBlockMixin extends AbstractRotateableWaterLoggableBlock implements IBlockTooltip {
public FlightPanelBlockMixin(Properties properties) { super(properties); }
private static final BooleanProperty HAS_LOCATOR = BooleanProperty.create("has_locator");
private static final IntegerProperty CARTRIDGE = DataWriterBlock.CARTRIDGE_TYPE;
private static final VoxelShape N_ADDON_SHAPE = VoxelShapes.box(6/16D, 2/16D, 8/16D, 1, 8/16D, 1);
private static final VoxelShape E_ADDON_SHAPE = VoxelShapes.box(0, 2/16D, 6/16D, 8/16D, 8/16D, 1);
private static final VoxelShape S_ADDON_SHAPE = VoxelShapes.box(0, 2/16D, 0, 10/16D, 8/16D, 8/16D);
private static final VoxelShape W_ADDON_SHAPE = VoxelShapes.box(8/16D, 2/16D, 0, 1, 8/16D, 10/16D);
private static VoxelShape getAddonShape(BlockState state) {
switch (state.getValue(BlockStateProperties.HORIZONTAL_FACING)) {
default:
case NORTH: return N_ADDON_SHAPE;
case EAST: return E_ADDON_SHAPE;
case SOUTH: return S_ADDON_SHAPE;
case WEST: return W_ADDON_SHAPE;
}
}
private static boolean isMouseOnLocator(BlockState state, BlockPos pos, Vector3d mouse, IBlockReader world) {
return state.getValue(HAS_LOCATOR) && getAddonShape(state).bounds().inflate(0.5/16D).contains(mouse.subtract(pos.getX(), pos.getY(), pos.getZ()));
}
private static void eject(BlockState state, World world, BlockPos pos, FlightPanelTileEntity tile) {
if (tile.cartridge != null && tile.cartridge.getItem() instanceof DataModuleItem) {
Direction direction = state.getValue(BlockStateProperties.HORIZONTAL_FACING);
ItemEntity itemEntity = new ItemEntity(EntityType.ITEM, world);
itemEntity.absMoveTo((pos.getX() + 0.5 + direction.getStepX()), pos.getY(), (pos.getZ() + 0.5 + direction.getStepZ()), 0, 0);
itemEntity.setDeltaMovement((direction.getStepX() / 10D), 0, (direction.getStepZ() / 10D));
itemEntity.setItem(tile.cartridge);
world.addFreshEntity(itemEntity);
tile.cartridge = ItemStack.EMPTY;
}
world.setBlockAndUpdate(pos, state.setValue(CARTRIDGE, 0));
}
@Inject(at = @At("RETURN"), method = "<init>*", remap = false)
public void constructor(final CallbackInfo ci) {
this.registerDefaultState(this.defaultBlockState().setValue(HAS_LOCATOR, Boolean.valueOf(false)).setValue(CARTRIDGE, 0));
}
@Override
public void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder) {
super.createBlockStateDefinition(builder);
builder.add(HAS_LOCATOR, CARTRIDGE);
}
@Inject(at = @At("RETURN"), method = "getShape", cancellable = true, remap = false)
public void getShape(final BlockState state, final IBlockReader world, final BlockPos pos, final ISelectionContext context, final CallbackInfoReturnable<VoxelShape> ci) {
if (state.getValue(HAS_LOCATOR)) ci.setReturnValue(VoxelShapes.or(ci.getReturnValue(), getAddonShape(state)));
}
@Inject(at = @At("HEAD"), method = "use", cancellable = true, remap = false)
public void use(final BlockState state, final World world, final BlockPos pos, final PlayerEntity player, final Hand handIn, final BlockRayTraceResult result, final CallbackInfoReturnable<ActionResultType> ci) {
if (isMouseOnLocator(state, pos, result.getLocation(), world)) {
if (!world.isClientSide()) {
TileEntity tile = world.getBlockEntity(pos);
if (tile != null && tile instanceof FlightPanelTileEntity) {
FlightPanelTileEntity panel = (FlightPanelTileEntity) tile;
ItemStack slotStack = panel.cartridge;
if (slotStack != null && !slotStack.isEmpty()) {
if (player.isShiftKeyDown()) {
eject(state, world, pos, panel);
ci.setReturnValue(ActionResultType.CONSUME);
}
} else {
ItemStack heldStack = player.getItemInHand(handIn);
if (heldStack != null && !heldStack.isEmpty()) {
Item item = heldStack.getItem();
if ((slotStack == null || slotStack.isEmpty()) && item instanceof DataModuleItem) {
panel.cartridge = heldStack.split(1);
if (player.abilities.instabuild) heldStack.grow(1);
world.setBlockAndUpdate(pos, state.setValue(CARTRIDGE, heldStack.getItem() == DMItems.DATA_MODULE.get() ? 1 : 2));
world.playSound((PlayerEntity) null, pos.getX(), pos.getY(), pos.getZ(), DMSoundEvents.TARDIS_MODULE_INSERT.get(), SoundCategory.BLOCKS, 1, 1);
ci.setReturnValue(ActionResultType.CONSUME);
}
}
}
}
}
} else if (!state.getValue(HAS_LOCATOR)) {
ItemStack heldStack = player.getItemInHand(handIn);
if (heldStack != null && !heldStack.isEmpty()) {
Item item = heldStack.getItem(); | if (item == Register.LOCATOR_ATTACHMENT_ITEM.get()) { | 0 | 2023-11-13 03:42:37+00:00 | 8k |
zizai-Shen/young-im | young-im-spring-boot-starter/young-im-spring-boot-starter-adapter/young-im-spring-boot-starter-adapter-registry/src/main/java/cn/young/im/springboot/starter/adapter/registry/adapter/NacosInstanceRegistryService.java | [
{
"identifier": "YoungImException",
"path": "young-im-common/src/main/java/cn/young/im/common/exception/YoungImException.java",
"snippet": "public class YoungImException extends RuntimeException {\n public YoungImException(String errorMsg) {\n super(errorMsg);\n }\n\n public YoungImExcep... | import cn.young.im.common.exception.YoungImException;
import cn.young.im.common.util.IpUtils;
import cn.young.im.spi.Join;
import cn.young.im.springboot.starter.adapter.registry.InstanceEntity;
import cn.young.im.springboot.starter.adapter.registry.InstanceRegistryService;
import cn.young.im.springboot.starter.adapter.registry.Status;
import cn.young.im.springboot.starter.adapter.registry.annotation.AutomaticRegistry;
import cn.young.im.springboot.starter.adapter.registry.config.NacosConfig;
import cn.young.im.springboot.starter.adapter.registry.config.RegisterConfig;
import cn.young.im.springboot.starter.extension.util.AnnotationScanner;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import static cn.young.im.common.constants.Const.COLONS;
import static cn.young.im.common.constants.YoungConst.BASE_PACKAGE;
import static cn.young.im.common.constants.YoungConst.DEFAULT; | 3,941 | package cn.young.im.springboot.starter.adapter.registry.adapter;
/**
* 作者:沈自在 <a href="https://www.szz.tax">Blog</a>
*
* @description Nacos 实例注册服务
* @date 2023/12/10
*/
@Slf4j
@Join
public class NacosInstanceRegistryService implements | package cn.young.im.springboot.starter.adapter.registry.adapter;
/**
* 作者:沈自在 <a href="https://www.szz.tax">Blog</a>
*
* @description Nacos 实例注册服务
* @date 2023/12/10
*/
@Slf4j
@Join
public class NacosInstanceRegistryService implements | InstanceRegistryService, EnvironmentAware { | 3 | 2023-11-10 06:21:17+00:00 | 8k |
erhenjt/twoyi2 | app/src/main/java/io/twoyi/ui/SelectAppActivity.java | [
{
"identifier": "AppKV",
"path": "app/src/main/java/io/twoyi/utils/AppKV.java",
"snippet": "public class AppKV {\n\n\n private static final String PREF_NAME = \"app_kv\";\n\n public static final String ADD_APP_NOT_SHOW_SYSTEM= \"add_app_not_show_system\";\n public static final String ADD_APP_NO... | import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.core.view.MenuItemCompat;
import androidx.core.widget.CompoundButtonCompat;
import com.afollestad.materialdialogs.MaterialDialog;
import com.github.clans.fab.FloatingActionButton;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import io.twoyi.R;
import io.twoyi.utils.AppKV;
import io.twoyi.utils.CacheManager;
import io.twoyi.utils.IOUtils;
import io.twoyi.utils.Installer;
import io.twoyi.utils.UIHelper;
import io.twoyi.utils.image.GlideModule; | 6,575 | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.twoyi.ui;
/**
* @author weishu
* @date 2018/7/21.
*/
public class SelectAppActivity extends AppCompatActivity {
private static final String TAG = "SelectAppActivity";
private static final int REQUEST_GET_FILE = 1;
private static int TAG_KEY = R.id.create_app_list;
private ListAppAdapter mAdapter;
private final List<AppItem> mDisplayItems = new ArrayList<>();
private final List<AppItem> mAllApps = new ArrayList<>();
private AppItem mSelectItem;
private TextView mEmptyView;
private final Set<String> specifiedPackages = new HashSet<>();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_createapp);
ListView mListView = findViewById(R.id.create_app_list);
mAdapter = new ListAppAdapter();
mListView.setAdapter(mAdapter);
mEmptyView = findViewById(R.id.empty_view);
mListView.setEmptyView(mEmptyView);
FloatingActionButton mFloatButton = findViewById(R.id.create_app_from_external);
mFloatButton.setColorNormalResId(R.color.colorPrimary);
mFloatButton.setColorPressedResId(R.color.colorPrimaryOpacity);
mFloatButton.setOnClickListener((v) -> {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setType("application/vnd.android.package-archive"); // apk file
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(intent, REQUEST_GET_FILE);
} catch (Throwable ignored) {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
});
TextView createApp = findViewById(R.id.create_app_btn);
createApp.setBackgroundResource(R.color.colorPrimary);
createApp.setText(R.string.select_app_button);
createApp.setOnClickListener((v) -> {
Set<AppItem> selectedApps = new HashSet<>();
for (AppItem displayItem : mDisplayItems) {
if (displayItem.selected) {
selectedApps.add(displayItem);
}
}
if (selectedApps.isEmpty()) {
Toast.makeText(this, R.string.select_app_tips, Toast.LENGTH_SHORT).show();
return;
}
selectComplete(selectedApps);
});
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
// actionBar.setBackgroundDrawable(getResources().getDrawable(R.color.colorPrimary));
actionBar.setTitle(R.string.create_app_activity);
}
Intent intent = getIntent();
if (intent != null) {
Uri data = intent.getData();
if (data != null && TextUtils.equals(data.getScheme(), "package")) {
String schemeSpecificPart = data.getSchemeSpecificPart();
if (schemeSpecificPart != null) {
String[] split = schemeSpecificPart.split("\\|");
specifiedPackages.clear();
specifiedPackages.addAll(Arrays.asList(split));
}
}
}
if (true) {
int size = specifiedPackages.size();
if (size > 1) {
specifiedPackages.clear();
}
}
loadAsync();
}
private void selectComplete(Set<AppItem> pkgs) {
if (pkgs.size() != 1) {
// TODO: support install mutilpe apps together
Toast.makeText(getApplicationContext(), R.string.please_install_one_by_one, Toast.LENGTH_SHORT).show();
return;
}
| /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.twoyi.ui;
/**
* @author weishu
* @date 2018/7/21.
*/
public class SelectAppActivity extends AppCompatActivity {
private static final String TAG = "SelectAppActivity";
private static final int REQUEST_GET_FILE = 1;
private static int TAG_KEY = R.id.create_app_list;
private ListAppAdapter mAdapter;
private final List<AppItem> mDisplayItems = new ArrayList<>();
private final List<AppItem> mAllApps = new ArrayList<>();
private AppItem mSelectItem;
private TextView mEmptyView;
private final Set<String> specifiedPackages = new HashSet<>();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_createapp);
ListView mListView = findViewById(R.id.create_app_list);
mAdapter = new ListAppAdapter();
mListView.setAdapter(mAdapter);
mEmptyView = findViewById(R.id.empty_view);
mListView.setEmptyView(mEmptyView);
FloatingActionButton mFloatButton = findViewById(R.id.create_app_from_external);
mFloatButton.setColorNormalResId(R.color.colorPrimary);
mFloatButton.setColorPressedResId(R.color.colorPrimaryOpacity);
mFloatButton.setOnClickListener((v) -> {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setType("application/vnd.android.package-archive"); // apk file
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(intent, REQUEST_GET_FILE);
} catch (Throwable ignored) {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
});
TextView createApp = findViewById(R.id.create_app_btn);
createApp.setBackgroundResource(R.color.colorPrimary);
createApp.setText(R.string.select_app_button);
createApp.setOnClickListener((v) -> {
Set<AppItem> selectedApps = new HashSet<>();
for (AppItem displayItem : mDisplayItems) {
if (displayItem.selected) {
selectedApps.add(displayItem);
}
}
if (selectedApps.isEmpty()) {
Toast.makeText(this, R.string.select_app_tips, Toast.LENGTH_SHORT).show();
return;
}
selectComplete(selectedApps);
});
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
// actionBar.setBackgroundDrawable(getResources().getDrawable(R.color.colorPrimary));
actionBar.setTitle(R.string.create_app_activity);
}
Intent intent = getIntent();
if (intent != null) {
Uri data = intent.getData();
if (data != null && TextUtils.equals(data.getScheme(), "package")) {
String schemeSpecificPart = data.getSchemeSpecificPart();
if (schemeSpecificPart != null) {
String[] split = schemeSpecificPart.split("\\|");
specifiedPackages.clear();
specifiedPackages.addAll(Arrays.asList(split));
}
}
}
if (true) {
int size = specifiedPackages.size();
if (size > 1) {
specifiedPackages.clear();
}
}
loadAsync();
}
private void selectComplete(Set<AppItem> pkgs) {
if (pkgs.size() != 1) {
// TODO: support install mutilpe apps together
Toast.makeText(getApplicationContext(), R.string.please_install_one_by_one, Toast.LENGTH_SHORT).show();
return;
}
| ProgressDialog progressDialog = UIHelper.getProgressDialog(this); | 4 | 2023-11-11 22:08:20+00:00 | 8k |
xLorey/FluxLoader | src/main/java/io/xlorey/FluxLoader/server/core/Core.java | [
{
"identifier": "EventManager",
"path": "src/main/java/io/xlorey/FluxLoader/shared/EventManager.java",
"snippet": "@UtilityClass\npublic class EventManager {\n /**\n * Event Listeners\n */\n private static final ArrayList<Object> listeners = new ArrayList<>();\n\n /**\n * Subscribin... | import io.xlorey.FluxLoader.shared.EventManager;
import io.xlorey.FluxLoader.shared.PluginManager;
import io.xlorey.FluxLoader.utils.Logger; | 7,142 | package io.xlorey.FluxLoader.server.core;
/**
* FluxLoader Core
*/
public class Core {
/**
* Initializing the loader
* @param serverArgs server boot arguments
* @exception Exception in cases of unsuccessful core initialization
*/
public static void init(String[] serverArgs) throws Exception {
boolean isCoop = false;
for (String serverArg : serverArgs) {
if (serverArg != null) {
if (serverArg.equals("-coop")) {
Logger.printLog("Launching a co-op server...");
isCoop = true;
break;
}
}
}
if (!isCoop) Logger.printCredits();
Logger.printLog("FluxLoader Core initialization for the server..");
EventManager.subscribe(new EventsHandler());
| package io.xlorey.FluxLoader.server.core;
/**
* FluxLoader Core
*/
public class Core {
/**
* Initializing the loader
* @param serverArgs server boot arguments
* @exception Exception in cases of unsuccessful core initialization
*/
public static void init(String[] serverArgs) throws Exception {
boolean isCoop = false;
for (String serverArg : serverArgs) {
if (serverArg != null) {
if (serverArg.equals("-coop")) {
Logger.printLog("Launching a co-op server...");
isCoop = true;
break;
}
}
}
if (!isCoop) Logger.printCredits();
Logger.printLog("FluxLoader Core initialization for the server..");
EventManager.subscribe(new EventsHandler());
| PluginManager.loadPlugins(false); | 1 | 2023-11-16 09:05:44+00:00 | 8k |
EmonerRobotics/2023Robot | src/main/java/frc/robot/subsystems/drivetrain/Drivetrain.java | [
{
"identifier": "Constants",
"path": "src/main/java/frc/robot/Constants.java",
"snippet": "public final class Constants {\n\n public static class LimelightConstants{\n public static double goalHeightInches = 30.31496; //30.31496\n }\n\n public final class LiftMeasurements{\n public static final... | import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.math.geometry.Rotation3d;
import edu.wpi.first.math.kinematics.ChassisSpeeds;
import edu.wpi.first.math.kinematics.SwerveDriveKinematics;
import edu.wpi.first.math.kinematics.SwerveModulePosition;
import edu.wpi.first.math.kinematics.SwerveModuleState;
import edu.wpi.first.wpilibj.RobotBase;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import frc.robot.Constants;
import frc.robot.Constants.DriveConstants;
import frc.robot.RobotContainer;
import java.util.ArrayList;
import java.util.List; | 6,490 | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.subsystems.drivetrain;
public class Drivetrain extends SubsystemBase {
// Create MAXSwerveModules
private final SwerveModules swerveModules;
// The gyro sensor
private final Gyro gyro;
/**
* Creates a new DriveSubsystem.
*/
public Drivetrain() {
if (RobotBase.isSimulation()) {
this.swerveModules = new SwerveModules(
new SIMSwerveModule(DriveConstants.FRONT_LEFT_CHASSIS_ANGULAR_OFFSET),
new SIMSwerveModule(DriveConstants.FRONT_RIGHT_CHASSIS_ANGULAR_OFFSET),
new SIMSwerveModule(DriveConstants.REAR_LEFT_CHASSIS_ANGULAR_OFFSET),
new SIMSwerveModule(DriveConstants.REAR_RIGHT_CHASSIS_ANGULAR_OFFSET)
);
} else {
this.swerveModules = new SwerveModules(
new MAXSwerveModule(
DriveConstants.FRONT_LEFT_DRIVING_CAN_ID,
DriveConstants.FRONT_LEFT_TURNING_CAN_ID,
DriveConstants.FRONT_LEFT_CHASSIS_ANGULAR_OFFSET
),
new MAXSwerveModule(
DriveConstants.FRONT_RIGHT_DRIVING_CAN_ID,
DriveConstants.FRONT_RIGHT_TURNING_CAN_ID,
DriveConstants.FRONT_RIGHT_CHASSIS_ANGULAR_OFFSET
),
new MAXSwerveModule(
DriveConstants.REAR_LEFT_DRIVING_CAN_ID,
DriveConstants.REAR_LEFT_TURNING_CAN_ID,
DriveConstants.REAR_LEFT_CHASSIS_ANGULAR_OFFSET
),
new MAXSwerveModule(
DriveConstants.REAR_RIGHT_DRIVING_CAN_ID,
DriveConstants.REAR_RIGHT_TURNING_CAN_ID,
DriveConstants.REAR_RIGHT_CHASSIS_ANGULAR_OFFSET
)
);
}
gyro = (RobotBase.isReal() ? new NavXGyro() : new SIMGyro(swerveModules));
//RobotContainer.swerveTab.addNumber("Front Left", swerveModules.frontLeft::getSwerveEncoderPosition).withWidget(BuiltInWidgets.kGraph);
//RobotContainer.swerveTab.addNumber("Front Right", swerveModules.frontRight::getSwerveEncoderPosition).withWidget(BuiltInWidgets.kGraph);
//RobotContainer.swerveTab.addNumber("Back Left", swerveModules.rearLeft::getSwerveEncoderPosition).withWidget(BuiltInWidgets.kGraph);
//RobotContainer.swerveTab.addNumber("Back Right", swerveModules.rearRight::getSwerveEncoderPosition).withWidget(BuiltInWidgets.kGraph);
//RobotContainer.swerveTab.addNumber("Gyro", () -> gyro.getAngle().getRadians()).withWidget(BuiltInWidgets.kGraph);
}
@Override
public void periodic() {
RobotContainer.poseEstimation.updateOdometry(
getRotation(),
getModulePositions()
);
gyro.update();
swerveModules.update();
logModuleStates("Swerve State", swerveModules.getStates().asArray());
logModuleStates("Swerve Set State", new SwerveModuleState[]{
swerveModules.frontLeft.getSetState(),
swerveModules.frontRight.getSetState(),
swerveModules.rearLeft.getSetState(),
swerveModules.rearRight.getSetState()
});
SmartDashboard.putNumberArray("Swerve Module Distance", new double[] { | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.subsystems.drivetrain;
public class Drivetrain extends SubsystemBase {
// Create MAXSwerveModules
private final SwerveModules swerveModules;
// The gyro sensor
private final Gyro gyro;
/**
* Creates a new DriveSubsystem.
*/
public Drivetrain() {
if (RobotBase.isSimulation()) {
this.swerveModules = new SwerveModules(
new SIMSwerveModule(DriveConstants.FRONT_LEFT_CHASSIS_ANGULAR_OFFSET),
new SIMSwerveModule(DriveConstants.FRONT_RIGHT_CHASSIS_ANGULAR_OFFSET),
new SIMSwerveModule(DriveConstants.REAR_LEFT_CHASSIS_ANGULAR_OFFSET),
new SIMSwerveModule(DriveConstants.REAR_RIGHT_CHASSIS_ANGULAR_OFFSET)
);
} else {
this.swerveModules = new SwerveModules(
new MAXSwerveModule(
DriveConstants.FRONT_LEFT_DRIVING_CAN_ID,
DriveConstants.FRONT_LEFT_TURNING_CAN_ID,
DriveConstants.FRONT_LEFT_CHASSIS_ANGULAR_OFFSET
),
new MAXSwerveModule(
DriveConstants.FRONT_RIGHT_DRIVING_CAN_ID,
DriveConstants.FRONT_RIGHT_TURNING_CAN_ID,
DriveConstants.FRONT_RIGHT_CHASSIS_ANGULAR_OFFSET
),
new MAXSwerveModule(
DriveConstants.REAR_LEFT_DRIVING_CAN_ID,
DriveConstants.REAR_LEFT_TURNING_CAN_ID,
DriveConstants.REAR_LEFT_CHASSIS_ANGULAR_OFFSET
),
new MAXSwerveModule(
DriveConstants.REAR_RIGHT_DRIVING_CAN_ID,
DriveConstants.REAR_RIGHT_TURNING_CAN_ID,
DriveConstants.REAR_RIGHT_CHASSIS_ANGULAR_OFFSET
)
);
}
gyro = (RobotBase.isReal() ? new NavXGyro() : new SIMGyro(swerveModules));
//RobotContainer.swerveTab.addNumber("Front Left", swerveModules.frontLeft::getSwerveEncoderPosition).withWidget(BuiltInWidgets.kGraph);
//RobotContainer.swerveTab.addNumber("Front Right", swerveModules.frontRight::getSwerveEncoderPosition).withWidget(BuiltInWidgets.kGraph);
//RobotContainer.swerveTab.addNumber("Back Left", swerveModules.rearLeft::getSwerveEncoderPosition).withWidget(BuiltInWidgets.kGraph);
//RobotContainer.swerveTab.addNumber("Back Right", swerveModules.rearRight::getSwerveEncoderPosition).withWidget(BuiltInWidgets.kGraph);
//RobotContainer.swerveTab.addNumber("Gyro", () -> gyro.getAngle().getRadians()).withWidget(BuiltInWidgets.kGraph);
}
@Override
public void periodic() {
RobotContainer.poseEstimation.updateOdometry(
getRotation(),
getModulePositions()
);
gyro.update();
swerveModules.update();
logModuleStates("Swerve State", swerveModules.getStates().asArray());
logModuleStates("Swerve Set State", new SwerveModuleState[]{
swerveModules.frontLeft.getSetState(),
swerveModules.frontRight.getSetState(),
swerveModules.rearLeft.getSetState(),
swerveModules.rearRight.getSetState()
});
SmartDashboard.putNumberArray("Swerve Module Distance", new double[] { | swerveModules.frontLeft.getPosition().distanceMeters / Constants.ModuleConstants.WHEEL_CIRCUMFERENCE_METERS, | 0 | 2023-11-18 14:02:20+00:00 | 8k |
NewXdOnTop/skyblock-remake | src/main/java/com/sweattypalms/skyblock/core/mobs/builder/dragons/abilities/RushAbility.java | [
{
"identifier": "EntityHelper",
"path": "src/main/java/com/sweattypalms/skyblock/core/helpers/EntityHelper.java",
"snippet": "public class EntityHelper {\n\n public static void equipArmor(EntityLiving entityLiving, SkyblockItemType[] armorSlots, Material armor) {\n LivingEntity entity = (Livin... | import com.sweattypalms.skyblock.core.helpers.EntityHelper;
import com.sweattypalms.skyblock.core.helpers.MathHelper;
import com.sweattypalms.skyblock.core.helpers.PlaceholderFormatter;
import com.sweattypalms.skyblock.core.mobs.builder.dragons.DragonStage;
import com.sweattypalms.skyblock.core.mobs.builder.dragons.EnderDragon;
import com.sweattypalms.skyblock.core.player.SkyblockPlayer;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import java.util.List; | 5,303 | package com.sweattypalms.skyblock.core.mobs.builder.dragons.abilities;
public class RushAbility implements IDragonAbility{
private final EnderDragon dragon;
public RushAbility(EnderDragon dragon) {
this.dragon = dragon;
}
Player target = null;
@Override
public void start() {
this.dragon.setMoving(false);
this.target = EntityHelper.getClosestPlayer((LivingEntity) this.dragon.getBukkitEntity());
rushing = true;
startRushPosition = this.dragon.getBukkitEntity().getLocation().toVector();
rushProgress = 0.0d;
}
boolean rushing = false;
Vector startRushPosition = null;
double rushProgress = 0.0d;
@Override
public void stop() {
dragon.setAbility(null);
int tickCount = 0;
}
@Override
public void tick() {
if (this.target == null){
throw new NullPointerException("Target not found??? cancelling ability");
}
Vector nextPosition = MathHelper.linearInterpolation(startRushPosition, target.getLocation().toVector(), rushProgress);
this.dragon.setPositionRotation(nextPosition.getX(), nextPosition.getY(), nextPosition.getZ(), target.getLocation().getYaw(), target.getLocation().getPitch());
rushProgress += 0.025;
if(rushProgress >= 1 || this.dragon.getBukkitEntity().getLocation().distance(target.getLocation()) < 3){
String message = "$5☬ $c" + dragon.getDragonName() + " $dused $eRush $don you for $c" + PlaceholderFormatter.formatDecimalCSV(dragon.getDragonDamage()) + " damage!";
message = PlaceholderFormatter.format(message);
target.sendMessage(message);
SkyblockPlayer.getSkyblockPlayer(target).damageWithReduction(dragon.getDragonDamage());
computeReturnPath();
}
}
private void computeReturnPath(){
Vector endPosition = dragon.getCurrentStage().getPoint(1);
Vector currentDragonPosition = this.dragon.getBukkitEntity().getLocation().toVector();
| package com.sweattypalms.skyblock.core.mobs.builder.dragons.abilities;
public class RushAbility implements IDragonAbility{
private final EnderDragon dragon;
public RushAbility(EnderDragon dragon) {
this.dragon = dragon;
}
Player target = null;
@Override
public void start() {
this.dragon.setMoving(false);
this.target = EntityHelper.getClosestPlayer((LivingEntity) this.dragon.getBukkitEntity());
rushing = true;
startRushPosition = this.dragon.getBukkitEntity().getLocation().toVector();
rushProgress = 0.0d;
}
boolean rushing = false;
Vector startRushPosition = null;
double rushProgress = 0.0d;
@Override
public void stop() {
dragon.setAbility(null);
int tickCount = 0;
}
@Override
public void tick() {
if (this.target == null){
throw new NullPointerException("Target not found??? cancelling ability");
}
Vector nextPosition = MathHelper.linearInterpolation(startRushPosition, target.getLocation().toVector(), rushProgress);
this.dragon.setPositionRotation(nextPosition.getX(), nextPosition.getY(), nextPosition.getZ(), target.getLocation().getYaw(), target.getLocation().getPitch());
rushProgress += 0.025;
if(rushProgress >= 1 || this.dragon.getBukkitEntity().getLocation().distance(target.getLocation()) < 3){
String message = "$5☬ $c" + dragon.getDragonName() + " $dused $eRush $don you for $c" + PlaceholderFormatter.formatDecimalCSV(dragon.getDragonDamage()) + " damage!";
message = PlaceholderFormatter.format(message);
target.sendMessage(message);
SkyblockPlayer.getSkyblockPlayer(target).damageWithReduction(dragon.getDragonDamage());
computeReturnPath();
}
}
private void computeReturnPath(){
Vector endPosition = dragon.getCurrentStage().getPoint(1);
Vector currentDragonPosition = this.dragon.getBukkitEntity().getLocation().toVector();
| dragon.setCurrentStage(new DragonStage(List.of(currentDragonPosition, endPosition), 0.02)); | 3 | 2023-11-15 15:05:58+00:00 | 8k |
microsphere-projects/microsphere-i18n | microsphere-i18n-core/src/main/java/io/microsphere/i18n/spring/context/I18nConfiguration.java | [
{
"identifier": "CompositeServiceMessageSource",
"path": "microsphere-i18n-core/src/main/java/io/microsphere/i18n/CompositeServiceMessageSource.java",
"snippet": "public class CompositeServiceMessageSource extends AbstractServiceMessageSource implements SmartInitializingSingleton {\n\n private final ... | import io.microsphere.i18n.CompositeServiceMessageSource;
import io.microsphere.i18n.ServiceMessageSource;
import io.microsphere.i18n.constants.I18nConstants;
import io.microsphere.i18n.spring.beans.factory.ServiceMessageSourceFactoryBean;
import io.microsphere.i18n.util.I18nUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;
import java.util.List;
import java.util.Locale;
import static io.microsphere.i18n.constants.I18nConstants.COMMON_SERVICE_MESSAGE_SOURCE_BEAN_NAME;
import static io.microsphere.i18n.constants.I18nConstants.COMMON_SERVICE_MESSAGE_SOURCE_ORDER;
import static io.microsphere.i18n.constants.I18nConstants.DEFAULT_ENABLED;
import static io.microsphere.i18n.constants.I18nConstants.ENABLED_PROPERTY_NAME;
import static io.microsphere.i18n.constants.I18nConstants.SERVICE_MESSAGE_SOURCE_BEAN_NAME; | 3,804 | package io.microsphere.i18n.spring.context;
/**
* Internationalization Configuration class
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy<a/>
* @since 1.0.0
*/
public class I18nConfiguration implements DisposableBean {
private static final Logger logger = LoggerFactory.getLogger(I18nConfiguration.class);
@Autowired | package io.microsphere.i18n.spring.context;
/**
* Internationalization Configuration class
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy<a/>
* @since 1.0.0
*/
public class I18nConfiguration implements DisposableBean {
private static final Logger logger = LoggerFactory.getLogger(I18nConfiguration.class);
@Autowired | @Qualifier(I18nConstants.SERVICE_MESSAGE_SOURCE_BEAN_NAME) | 2 | 2023-11-17 11:35:59+00:00 | 8k |
pyzpre/Create-Bicycles-Bitterballen | src/main/java/createbicyclesbitterballen/ponder/FryerScenes.java | [
{
"identifier": "MechanicalFryerEntity",
"path": "src/main/java/createbicyclesbitterballen/block/mechanicalfryer/MechanicalFryerEntity.java",
"snippet": "public class MechanicalFryerEntity extends BasinOperatingBlockEntity {\n\n private static final Object DeepFryingRecipesKey = new Object();\n\n ... | import com.google.common.collect.ImmutableList;
import com.simibubi.create.AllBlocks;
import com.simibubi.create.content.processing.basin.BasinBlockEntity;
import com.simibubi.create.content.processing.burner.BlazeBurnerBlock;
import com.simibubi.create.foundation.ponder.SceneBuilder;
import com.simibubi.create.foundation.ponder.SceneBuildingUtil;
import com.simibubi.create.foundation.ponder.element.InputWindowElement;
import com.simibubi.create.foundation.utility.IntAttached;
import com.simibubi.create.foundation.utility.NBTHelper;
import com.simibubi.create.foundation.utility.Pointing;
import createbicyclesbitterballen.block.mechanicalfryer.MechanicalFryerEntity;
import createbicyclesbitterballen.index.CreateBicBitModItems;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.phys.Vec3;
import com.simibubi.create.content.processing.burner.BlazeBurnerBlock.HeatLevel; | 4,041 | package createbicyclesbitterballen.ponder;
public class FryerScenes {
public static void frying(SceneBuilder scene, SceneBuildingUtil util) {
scene.title("mechanical_fryer", "Processing Items with the Mechanical Fryer");
scene.configureBasePlate(0, 0, 5);
scene.world.setBlock(util.grid.at(1, 1, 2), AllBlocks.BLAZE_BURNER.getDefaultState().setValue(BlazeBurnerBlock.HEAT_LEVEL, HeatLevel.KINDLED), false);
scene.world.showSection(util.select.layer(0), Direction.UP);
scene.idle(5);
scene.world.showSection(util.select.fromTo(1, 4, 3, 1, 1, 5), Direction.DOWN);
scene.idle(5);
scene.world.showSection(util.select.position(1, 1, 2), Direction.DOWN);
scene.idle(5);
scene.world.showSection(util.select.position(1, 2, 2), Direction.DOWN);
scene.idle(5);
scene.world.showSection(util.select.position(1, 4, 2), Direction.SOUTH);
scene.idle(5);
scene.world.showSection(util.select.fromTo(3, 1, 1, 1, 1, 1), Direction.SOUTH);
scene.world.showSection(util.select.fromTo(3, 1, 5, 3, 1, 2), Direction.SOUTH);
scene.idle(20);
BlockPos basin = util.grid.at(1, 2, 2);
BlockPos pressPos = util.grid.at(1, 4, 2);
Vec3 basinSide = util.vector.blockSurface(basin, Direction.WEST);
| package createbicyclesbitterballen.ponder;
public class FryerScenes {
public static void frying(SceneBuilder scene, SceneBuildingUtil util) {
scene.title("mechanical_fryer", "Processing Items with the Mechanical Fryer");
scene.configureBasePlate(0, 0, 5);
scene.world.setBlock(util.grid.at(1, 1, 2), AllBlocks.BLAZE_BURNER.getDefaultState().setValue(BlazeBurnerBlock.HEAT_LEVEL, HeatLevel.KINDLED), false);
scene.world.showSection(util.select.layer(0), Direction.UP);
scene.idle(5);
scene.world.showSection(util.select.fromTo(1, 4, 3, 1, 1, 5), Direction.DOWN);
scene.idle(5);
scene.world.showSection(util.select.position(1, 1, 2), Direction.DOWN);
scene.idle(5);
scene.world.showSection(util.select.position(1, 2, 2), Direction.DOWN);
scene.idle(5);
scene.world.showSection(util.select.position(1, 4, 2), Direction.SOUTH);
scene.idle(5);
scene.world.showSection(util.select.fromTo(3, 1, 1, 1, 1, 1), Direction.SOUTH);
scene.world.showSection(util.select.fromTo(3, 1, 5, 3, 1, 2), Direction.SOUTH);
scene.idle(20);
BlockPos basin = util.grid.at(1, 2, 2);
BlockPos pressPos = util.grid.at(1, 4, 2);
Vec3 basinSide = util.vector.blockSurface(basin, Direction.WEST);
| ItemStack oil = new ItemStack(CreateBicBitModItems.FRYING_OIL_BUCKET); | 1 | 2023-11-12 13:05:18+00:00 | 8k |
HanGyeolee/AndroidPdfWriter | android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/components/PDFComponent.java | [
{
"identifier": "Anchor",
"path": "android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/utils/Anchor.java",
"snippet": "public class Anchor{\n @Retention(RetentionPolicy.SOURCE)\n @IntDef({Start, Center, End})\n public @interface AnchorInt {}\n public static final int Start = 0;\... | import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.text.TextPaint;
import androidx.annotation.ColorInt;
import com.hangyeolee.androidpdfwriter.utils.Anchor;
import com.hangyeolee.androidpdfwriter.utils.Border;
import com.hangyeolee.androidpdfwriter.listener.Action;
import com.hangyeolee.androidpdfwriter.utils.Zoomable; | 5,427 | Math.round(margin.top * Zoomable.getInstance().density),
Math.round(margin.right * Zoomable.getInstance().density),
Math.round(margin.bottom * Zoomable.getInstance().density))
);
return this;
}
/**
* 컴포넌트 밖의 여백 설정<br>
* Setting margins outside of components
* @param all 여백
* @return 컴포넌트 자기자신
*/
public PDFComponent setMargin(int all){
return setMargin(all, all, all, all);
}
/**
* 컴포넌트 밖의 여백 설정<br>
* Setting margins outside of components
* @param horizontal 가로 여백
* @param vertical 세로 여백
* @return 컴포넌트 자기자신
*/
public PDFComponent setMargin(int horizontal, int vertical){
return setMargin(horizontal, vertical, horizontal, vertical);
}
/**
* 컴포넌트 밖의 여백 설정<br>
* Setting margins outside of components
* @param left 왼쪽 여백
* @param top 위쪽 여백
* @param right 오른쪽 여백
* @param bottom 아래쪽 여백
* @return 컴포넌트 자기자신
*/
public PDFComponent setMargin(int left, int top, int right, int bottom){
this.margin.set(
Math.round(left * Zoomable.getInstance().density),
Math.round(top * Zoomable.getInstance().density),
Math.round(right * Zoomable.getInstance().density),
Math.round(bottom * Zoomable.getInstance().density)
);
return this;
}
/**
* 컴포넌트 내의 내용(content)과 테두리(border) 사이의 간격 설정<br>
* Setting the interval between content and border within a component
* @param padding 패딩
* @return 컴포넌트 자기자신
*/
public PDFComponent setPadding(Rect padding){
this.padding.set(new Rect(
Math.round(padding.left * Zoomable.getInstance().density),
Math.round(padding.top * Zoomable.getInstance().density),
Math.round(padding.right * Zoomable.getInstance().density),
Math.round(padding.bottom * Zoomable.getInstance().density))
);
return this;
}
/**
* 컴포넌트 내의 내용(content)과 테두리(border) 사이의 간격 설정<br>
* Setting the interval between content and border within a component
* @param all 패딩
* @return 컴포넌트 자기자신
*/
public PDFComponent setPadding(int all){
this.padding.set(
Math.round(all * Zoomable.getInstance().density),
Math.round(all * Zoomable.getInstance().density),
Math.round(all * Zoomable.getInstance().density),
Math.round(all * Zoomable.getInstance().density)
);
return this;
}
/**
* 컴포넌트 내의 내용(content)과 테두리(border) 사이의 간격 설정<br>
* Setting the interval between content and border within a component
* @param horizontal 가로 패딩
* @param vertical 세로 패딩
* @return 컴포넌트 자기자신
*/
public PDFComponent setPadding(int horizontal, int vertical){
this.padding.set(
Math.round(horizontal * Zoomable.getInstance().density),
Math.round(vertical * Zoomable.getInstance().density),
Math.round(horizontal * Zoomable.getInstance().density),
Math.round(vertical * Zoomable.getInstance().density)
);
return this;
}
/**
* 컴포넌트 내의 내용(content)과 테두리(border) 사이의 간격 설정<br>
* Setting the interval between content and border within a component
* @param left 왼쪽 패딩
* @param top 위쪽 패딩
* @param right 오른쪽 패딩
* @param bottom 아래쪽 패딩
* @return 컴포넌트 자기자신
*/
public PDFComponent setPadding(int left, int top, int right, int bottom){
this.padding.set(
Math.round(left * Zoomable.getInstance().density),
Math.round(top * Zoomable.getInstance().density),
Math.round(right * Zoomable.getInstance().density),
Math.round(bottom * Zoomable.getInstance().density)
);
return this;
}
/**
* 테두리 굵기 및 색상 지정<br>
* Specify border thickness and color
* @param action 테두리 변경 함수
*/ | package com.hangyeolee.androidpdfwriter.components;
public abstract class PDFComponent{
PDFComponent parent = null;
// margin을 뺀 나머지 길이
int width = 0;
int height = 0;
@ColorInt
int backgroundColor = Color.TRANSPARENT;
final Rect margin = new Rect(0,0,0,0);
final Rect padding = new Rect(0,0,0,0);
final Border border = new Border();
final Anchor anchor = new Anchor();
Bitmap buffer = null;
Paint bufferPaint = null;
float relativeX = 0;
float relativeY = 0;
// Absolute Position
protected float measureX = 0;
protected float measureY = 0;
// margin을 뺀 나머지 길이
protected int measureWidth = -1;
protected int measureHeight = -1;
public PDFComponent(){}
/**
* 상위 컴포넌트에서의 레이아웃 계산 <br>
* 상위 컴포넌트가 null 인 경우 전체 페이지를 기준 <br>
* Compute layout on parent components <br>
* Based on full page when parent component is null
*/
public void measure(){
measure(relativeX, relativeY);
}
/**
* 상위 컴포넌트에서의 레이아웃 계산 <br>
* 상위 컴포넌트가 null 인 경우 전체 페이지를 기준 <br>
* Compute layout on parent components <br>
* Based on full page when parent component is null
* @param x 상대적인 X 위치, Relative X position
* @param y 상대적인 Y 위치, Relative Y position
*/
public void measure(float x, float y){
if(width < 0) {
width = 0;
}
if(height < 0) {
height = 0;
}
relativeX = x;
relativeY = y;
float dx, dy;
int gapX = 0;
int gapY = 0;
int left = margin.left;
int top = margin.top;
int right = margin.right;
int bottom = margin.bottom;
// Measure Width and Height
if(parent == null){
measureWidth = (width - left - right);
measureHeight = (height - top - bottom);
}
else{
// Get Max Width and Height from Parent
int maxW = Math.round (parent.measureWidth
- parent.border.size.left - parent.border.size.right
- parent.padding.left - parent.padding.right
- left - right);
int maxH = Math.round (parent.measureHeight
- parent.border.size.top - parent.border.size.bottom
- parent.padding.top - parent.padding.bottom
- top - bottom);
if(maxW < 0) maxW = 0;
if(maxH < 0) maxH = 0;
// 설정한 Width 나 Height 가 최대값을 넘지 않으면, 설정한 값으로
if(0 < width && width + relativeX <= maxW) measureWidth = width;
// 설정한 Width 나 Height 가 최대값을 넘으면, 최대 값으로 Width 나 Height를 설정
else measureWidth = Math.round (maxW - relativeX);
if(0 < height && height + relativeY <= maxH) measureHeight = height;
else measureHeight = Math.round (maxH - relativeY);
gapX = maxW - measureWidth;
gapY = maxH - measureHeight;
}
dx = Anchor.getDeltaPixel(anchor.horizontal, gapX);
dy = Anchor.getDeltaPixel(anchor.vertical, gapY);
if(parent != null){
dx += parent.measureX + parent.border.size.left + parent.padding.left;
dy += parent.measureY + parent.border.size.top + parent.padding.top;
}
measureX = relativeX + left + dx;
measureY = relativeY + top + dy;
}
/**
* 부모 컴포넌트에서 부모 컴포넌트의 연산에 맞게<br>
* 자식 컴포넌트를 강제로 수정해야할 떄 사용<br>
* Used when a parent component needs to force a child component ~<br>
* to be modified to match the parent component's operations
* @param width
* @param height
*/
protected void force(Integer width, Integer height, Rect forceMargin) {
int max;
int gap = 0;
float d;
if (width != null) {
if(forceMargin == null)
max = (width - margin.left - margin.right);
else
max = width;
gap = max - measureWidth;
// Measure X Anchor and Y Anchor
d = Anchor.getDeltaPixel(anchor.horizontal, gap);
if (parent != null)
d += parent.measureX + parent.border.size.left + parent.padding.left;
// Set Absolute Position From Parent
measureWidth = max;
measureX = relativeX + margin.left + d;
}
if(height != null) {
if(forceMargin == null)
max = (height - margin.top - margin.bottom);
else
max = height;
gap = max - measureHeight;
// Measure X Anchor and Y Anchor
d = Anchor.getDeltaPixel(anchor.vertical, gap);
if (parent != null)
d += parent.measureY + parent.border.size.top + parent.padding.top;
// Set Absolute Position From Parent
measureHeight = max;
measureY = relativeY + margin.top + d;
}
}
public void draw(Canvas canvas){
//---------------배경 그리기-------------//
Paint background = new Paint();
background.setColor(backgroundColor);
background.setStyle(Paint.Style.FILL);
background.setFlags(TextPaint.FILTER_BITMAP_FLAG | TextPaint.LINEAR_TEXT_FLAG | TextPaint.ANTI_ALIAS_FLAG);
float left = relativeX + margin.left;
float top = relativeY + margin.top;
if (parent != null) {
left += parent.measureX + parent.border.size.left + parent.padding.left;
top += parent.measureY + parent.border.size.top + parent.padding.top;
}
if(measureWidth > 0 && measureHeight > 0) {
canvas.drawRect(left, top,
left + measureWidth, top + measureHeight,
background);
}
//--------------테두리 그리기-------------//
border.draw(canvas, left, top, measureWidth, measureHeight);
}
/**
* 하위 컴포넌트로 상위 컴포넌트 업데이트 <br>
* Update parent components to child components
* @param heightGap
*/
protected void updateHeight(float heightGap){
int top = margin.top;
int bottom = margin.bottom;
if(parent == null){
height += heightGap;
measureHeight = (height - top - bottom);
}
else{
parent.updateHeight(heightGap);
int maxH = Math.round (parent.measureHeight
- parent.border.size.top - parent.border.size.bottom
- parent.padding.top - parent.padding.bottom
- top - bottom);
if(0 < height && height + relativeY <= maxH) measureHeight = height;
else measureHeight = Math.round (maxH - relativeY);
}
}
/**
* 계산된 전체 너비를 구한다.<br>
* Get the calculated total width.
* @return 전체 너비
*/
public int getTotalWidth(){
return measureWidth + margin.right + margin.left;
}
/**
* 계산된 전체 높이를 구한다.<br>
* Get the calculated total height.
* @return 전체 높이
*/
public int getTotalHeight(){
return measureHeight + margin.top + margin.bottom;
}
/**
* 컴포넌트 내의 내용(content)의 크기 설정 <br>
* Setting the size of content within a component
* @param width 가로 크기
* @param height 세로 크기
* @return 컴포넌트 자기자신
*/
public PDFComponent setSize(Float width, Float height){
if(width != null){
if(width < 0) width = 0f;
this.width = Math.round(width * Zoomable.getInstance().density);
}
if(height != null){
if(height < 0) height = 0f;
this.height = Math.round(height * Zoomable.getInstance().density);
}
return this;
}
/**
* 컴포넌트 내의 배경의 색상 설정<br>
* Set the color of the background within the component
* @param color 색상
* @return 컴포넌트 자기자신
*/
public PDFComponent setBackgroundColor(int color){
this.backgroundColor = color;
return this;
}
/**
* 컴포넌트 밖의 여백 설정<br>
* Setting margins outside of components
* @param margin 여백
* @return 컴포넌트 자기자신
*/
public PDFComponent setMargin(Rect margin){
this.margin.set(new Rect(
Math.round(margin.left * Zoomable.getInstance().density),
Math.round(margin.top * Zoomable.getInstance().density),
Math.round(margin.right * Zoomable.getInstance().density),
Math.round(margin.bottom * Zoomable.getInstance().density))
);
return this;
}
/**
* 컴포넌트 밖의 여백 설정<br>
* Setting margins outside of components
* @param all 여백
* @return 컴포넌트 자기자신
*/
public PDFComponent setMargin(int all){
return setMargin(all, all, all, all);
}
/**
* 컴포넌트 밖의 여백 설정<br>
* Setting margins outside of components
* @param horizontal 가로 여백
* @param vertical 세로 여백
* @return 컴포넌트 자기자신
*/
public PDFComponent setMargin(int horizontal, int vertical){
return setMargin(horizontal, vertical, horizontal, vertical);
}
/**
* 컴포넌트 밖의 여백 설정<br>
* Setting margins outside of components
* @param left 왼쪽 여백
* @param top 위쪽 여백
* @param right 오른쪽 여백
* @param bottom 아래쪽 여백
* @return 컴포넌트 자기자신
*/
public PDFComponent setMargin(int left, int top, int right, int bottom){
this.margin.set(
Math.round(left * Zoomable.getInstance().density),
Math.round(top * Zoomable.getInstance().density),
Math.round(right * Zoomable.getInstance().density),
Math.round(bottom * Zoomable.getInstance().density)
);
return this;
}
/**
* 컴포넌트 내의 내용(content)과 테두리(border) 사이의 간격 설정<br>
* Setting the interval between content and border within a component
* @param padding 패딩
* @return 컴포넌트 자기자신
*/
public PDFComponent setPadding(Rect padding){
this.padding.set(new Rect(
Math.round(padding.left * Zoomable.getInstance().density),
Math.round(padding.top * Zoomable.getInstance().density),
Math.round(padding.right * Zoomable.getInstance().density),
Math.round(padding.bottom * Zoomable.getInstance().density))
);
return this;
}
/**
* 컴포넌트 내의 내용(content)과 테두리(border) 사이의 간격 설정<br>
* Setting the interval between content and border within a component
* @param all 패딩
* @return 컴포넌트 자기자신
*/
public PDFComponent setPadding(int all){
this.padding.set(
Math.round(all * Zoomable.getInstance().density),
Math.round(all * Zoomable.getInstance().density),
Math.round(all * Zoomable.getInstance().density),
Math.round(all * Zoomable.getInstance().density)
);
return this;
}
/**
* 컴포넌트 내의 내용(content)과 테두리(border) 사이의 간격 설정<br>
* Setting the interval between content and border within a component
* @param horizontal 가로 패딩
* @param vertical 세로 패딩
* @return 컴포넌트 자기자신
*/
public PDFComponent setPadding(int horizontal, int vertical){
this.padding.set(
Math.round(horizontal * Zoomable.getInstance().density),
Math.round(vertical * Zoomable.getInstance().density),
Math.round(horizontal * Zoomable.getInstance().density),
Math.round(vertical * Zoomable.getInstance().density)
);
return this;
}
/**
* 컴포넌트 내의 내용(content)과 테두리(border) 사이의 간격 설정<br>
* Setting the interval between content and border within a component
* @param left 왼쪽 패딩
* @param top 위쪽 패딩
* @param right 오른쪽 패딩
* @param bottom 아래쪽 패딩
* @return 컴포넌트 자기자신
*/
public PDFComponent setPadding(int left, int top, int right, int bottom){
this.padding.set(
Math.round(left * Zoomable.getInstance().density),
Math.round(top * Zoomable.getInstance().density),
Math.round(right * Zoomable.getInstance().density),
Math.round(bottom * Zoomable.getInstance().density)
);
return this;
}
/**
* 테두리 굵기 및 색상 지정<br>
* Specify border thickness and color
* @param action 테두리 변경 함수
*/ | public PDFComponent setBorder(Action<Border, Border> action){ | 2 | 2023-11-15 08:05:28+00:00 | 8k |
cometcake575/Origins-Reborn | src/main/java/com/starshootercity/abilities/impossible/ExtraReach.java | [
{
"identifier": "OriginSwapper",
"path": "src/main/java/com/starshootercity/OriginSwapper.java",
"snippet": "public class OriginSwapper implements Listener {\n private final static NamespacedKey displayKey = new NamespacedKey(OriginsReborn.getInstance(), \"display-item\");\n private final static N... | import com.starshootercity.OriginSwapper;
import com.starshootercity.abilities.VisibleAbility;
import net.kyori.adventure.key.Key;
import org.jetbrains.annotations.NotNull;
import java.util.List; | 6,355 | package com.starshootercity.abilities.impossible;
public class ExtraReach implements VisibleAbility {
@Override
public @NotNull Key getKey() {
return Key.key("origins:extra_reach");
}
@Override | package com.starshootercity.abilities.impossible;
public class ExtraReach implements VisibleAbility {
@Override
public @NotNull Key getKey() {
return Key.key("origins:extra_reach");
}
@Override | public @NotNull List<OriginSwapper.LineData.LineComponent> getDescription() { | 0 | 2023-11-10 21:39:16+00:00 | 8k |
SoBadFish/Report | src/main/java/org/sobadfish/report/command/ReportCommand.java | [
{
"identifier": "ReportMainClass",
"path": "src/main/java/org/sobadfish/report/ReportMainClass.java",
"snippet": "public class ReportMainClass extends PluginBase {\n\n private static IDataManager dataManager;\n\n private static ReportMainClass mainClass;\n\n private ReportConfig reportConfig;\n... | import cn.nukkit.Player;
import cn.nukkit.Server;
import cn.nukkit.command.Command;
import cn.nukkit.command.CommandSender;
import org.sobadfish.report.ReportMainClass;
import org.sobadfish.report.form.DisplayCustomForm;
import org.sobadfish.report.form.DisplayForm;
import org.sobadfish.report.form.DisplayHistoryForm;
import java.util.List; | 4,139 | package org.sobadfish.report.command;
/**
* @author SoBadFish
* 2022/1/21
*/
public class ReportCommand extends Command {
public ReportCommand(String name) {
super(name);
}
@Override
public boolean execute(CommandSender commandSender, String s, String[] strings) {
if(strings.length == 0) {
if (commandSender instanceof Player) {
DisplayCustomForm displayCustomForm = new DisplayCustomForm(DisplayCustomForm.getRid());
displayCustomForm.disPlay((Player) commandSender,null);
}else{
ReportMainClass.sendMessageToObject("&c请不要在控制台执行", commandSender);
}
return true;
}
String cmd = strings[0];
if("r".equalsIgnoreCase(cmd)){
if(strings.length > 1){
DisplayCustomForm displayCustomForm = new DisplayCustomForm(DisplayCustomForm.getRid());
displayCustomForm.disPlay((Player) commandSender,strings[1]);
return true;
}
}
if(commandSender.isOp() || ReportMainClass.getMainClass().getAdminPlayers().contains(commandSender.getName())){
switch (cmd){
case "a":
if(commandSender instanceof Player){ | package org.sobadfish.report.command;
/**
* @author SoBadFish
* 2022/1/21
*/
public class ReportCommand extends Command {
public ReportCommand(String name) {
super(name);
}
@Override
public boolean execute(CommandSender commandSender, String s, String[] strings) {
if(strings.length == 0) {
if (commandSender instanceof Player) {
DisplayCustomForm displayCustomForm = new DisplayCustomForm(DisplayCustomForm.getRid());
displayCustomForm.disPlay((Player) commandSender,null);
}else{
ReportMainClass.sendMessageToObject("&c请不要在控制台执行", commandSender);
}
return true;
}
String cmd = strings[0];
if("r".equalsIgnoreCase(cmd)){
if(strings.length > 1){
DisplayCustomForm displayCustomForm = new DisplayCustomForm(DisplayCustomForm.getRid());
displayCustomForm.disPlay((Player) commandSender,strings[1]);
return true;
}
}
if(commandSender.isOp() || ReportMainClass.getMainClass().getAdminPlayers().contains(commandSender.getName())){
switch (cmd){
case "a":
if(commandSender instanceof Player){ | DisplayForm displayFrom = new DisplayForm(DisplayForm.getRid()); | 2 | 2023-11-15 03:08:23+00:00 | 8k |
toxicity188/InventoryAPI | plugin/src/main/java/kor/toxicity/inventory/InventoryAPIImpl.java | [
{
"identifier": "InventoryAPI",
"path": "api/src/main/java/kor/toxicity/inventory/api/InventoryAPI.java",
"snippet": "@SuppressWarnings(\"unused\")\npublic abstract class InventoryAPI extends JavaPlugin {\n private static InventoryAPI api;\n\n private ImageManager imageManager;\n private FontMa... | import kor.toxicity.inventory.api.InventoryAPI;
import kor.toxicity.inventory.api.event.PluginReloadEndEvent;
import kor.toxicity.inventory.api.event.PluginReloadStartEvent;
import kor.toxicity.inventory.api.gui.*;
import kor.toxicity.inventory.api.manager.InventoryManager;
import kor.toxicity.inventory.manager.FontManagerImpl;
import kor.toxicity.inventory.manager.ImageManagerImpl;
import kor.toxicity.inventory.manager.ResourcePackManagerImpl;
import kor.toxicity.inventory.util.AdventureUtil;
import kor.toxicity.inventory.util.PluginUtil;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextColor;
import net.kyori.adventure.text.format.TextDecoration;
import net.kyori.adventure.text.minimessage.Context;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.Tag;
import net.kyori.adventure.text.minimessage.tag.resolver.ArgumentQueue;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitTask;
import org.jetbrains.annotations.NotNull;
import java.awt.*;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.*;
import java.util.List;
import java.util.jar.JarFile; | 4,386 | package kor.toxicity.inventory;
@SuppressWarnings("unused")
public final class InventoryAPIImpl extends InventoryAPI {
private static final Tag NONE_TAG = Tag.selfClosingInserting(Component.text(""));
private static final Tag ERROR_TAG = Tag.selfClosingInserting(Component.text("error!"));
private static final MiniMessage MINI_MESSAGE = MiniMessage.builder()
.tags(TagResolver.builder()
.resolvers(
TagResolver.standard(),
TagResolver.resolver("space", (ArgumentQueue argumentQueue, Context context) -> {
if (argumentQueue.hasNext()) {
var next = argumentQueue.pop().value();
try {
return Tag.selfClosingInserting(AdventureUtil.getSpaceFont(Integer.parseInt(next)));
} catch (Exception e) {
return ERROR_TAG;
}
} else return NONE_TAG;
})
)
.build()
)
.postProcessor(c -> {
var style = c.style();
if (style.color() == null) style = style.color(NamedTextColor.WHITE);
var deco = style.decorations();
var newDeco = new EnumMap<TextDecoration, TextDecoration.State>(TextDecoration.class);
for (TextDecoration value : TextDecoration.values()) {
var get = deco.get(value);
if (get == null || get == TextDecoration.State.NOT_SET) {
newDeco.put(value, TextDecoration.State.FALSE);
} else newDeco.put(value, get);
}
style = style.decorations(newDeco);
return c.style(style);
})
.build();
private GuiFont font;
private final List<InventoryManager> managers = new ArrayList<>();
private static final ItemStack AIR = new ItemStack(Material.AIR);
@Override
public void onEnable() {
var pluginManager = Bukkit.getPluginManager();
var fontManager = new FontManagerImpl();
setFontManager(fontManager);
var imageManager = new ImageManagerImpl();
setImageManager(imageManager); | package kor.toxicity.inventory;
@SuppressWarnings("unused")
public final class InventoryAPIImpl extends InventoryAPI {
private static final Tag NONE_TAG = Tag.selfClosingInserting(Component.text(""));
private static final Tag ERROR_TAG = Tag.selfClosingInserting(Component.text("error!"));
private static final MiniMessage MINI_MESSAGE = MiniMessage.builder()
.tags(TagResolver.builder()
.resolvers(
TagResolver.standard(),
TagResolver.resolver("space", (ArgumentQueue argumentQueue, Context context) -> {
if (argumentQueue.hasNext()) {
var next = argumentQueue.pop().value();
try {
return Tag.selfClosingInserting(AdventureUtil.getSpaceFont(Integer.parseInt(next)));
} catch (Exception e) {
return ERROR_TAG;
}
} else return NONE_TAG;
})
)
.build()
)
.postProcessor(c -> {
var style = c.style();
if (style.color() == null) style = style.color(NamedTextColor.WHITE);
var deco = style.decorations();
var newDeco = new EnumMap<TextDecoration, TextDecoration.State>(TextDecoration.class);
for (TextDecoration value : TextDecoration.values()) {
var get = deco.get(value);
if (get == null || get == TextDecoration.State.NOT_SET) {
newDeco.put(value, TextDecoration.State.FALSE);
} else newDeco.put(value, get);
}
style = style.decorations(newDeco);
return c.style(style);
})
.build();
private GuiFont font;
private final List<InventoryManager> managers = new ArrayList<>();
private static final ItemStack AIR = new ItemStack(Material.AIR);
@Override
public void onEnable() {
var pluginManager = Bukkit.getPluginManager();
var fontManager = new FontManagerImpl();
setFontManager(fontManager);
var imageManager = new ImageManagerImpl();
setImageManager(imageManager); | var resourcePackManager = new ResourcePackManagerImpl(); | 6 | 2023-11-13 00:19:46+00:00 | 8k |
GoogleCloudPlatform/dataflow-ordered-processing | beam-ordered-processing/src/main/java/org/apache/beam/sdk/extensions/ordered/OrderedEventProcessor.java | [
{
"identifier": "Builder",
"path": "beam-ordered-processing/src/main/java/org/apache/beam/sdk/extensions/ordered/OrderedProcessingDiagnosticEvent.java",
"snippet": "@AutoValue.Builder\npublic abstract static class Builder {\n\n public abstract Builder setSequenceNumber(long value);\n\n public abstract... | import com.google.auto.value.AutoValue;
import java.util.Arrays;
import java.util.Iterator;
import javax.annotation.Nullable;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.coders.BooleanCoder;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.coders.KvCoder;
import org.apache.beam.sdk.coders.VarLongCoder;
import org.apache.beam.sdk.extensions.ordered.OrderedProcessingDiagnosticEvent.Builder;
import org.apache.beam.sdk.extensions.ordered.OrderedProcessingDiagnosticEvent.ClearedBufferedEvents;
import org.apache.beam.sdk.extensions.ordered.OrderedProcessingDiagnosticEvent.QueriedBufferedEvents;
import org.apache.beam.sdk.extensions.ordered.ProcessingState.ProcessingStateCoder;
import org.apache.beam.sdk.extensions.ordered.UnprocessedEvent.Reason;
import org.apache.beam.sdk.extensions.ordered.UnprocessedEvent.UnprocessedEventCoder;
import org.apache.beam.sdk.schemas.NoSuchSchemaException;
import org.apache.beam.sdk.schemas.SchemaCoder;
import org.apache.beam.sdk.schemas.SchemaRegistry;
import org.apache.beam.sdk.state.OrderedListState;
import org.apache.beam.sdk.state.StateSpec;
import org.apache.beam.sdk.state.StateSpecs;
import org.apache.beam.sdk.state.TimeDomain;
import org.apache.beam.sdk.state.Timer;
import org.apache.beam.sdk.state.TimerSpec;
import org.apache.beam.sdk.state.TimerSpecs;
import org.apache.beam.sdk.state.ValueState;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.PCollection.IsBounded;
import org.apache.beam.sdk.values.PCollectionTuple;
import org.apache.beam.sdk.values.TimestampedValue;
import org.apache.beam.sdk.values.TupleTag;
import org.apache.beam.sdk.values.TupleTagList;
import org.apache.beam.sdk.values.TypeDescriptor;
import org.joda.time.Duration;
import org.joda.time.Instant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | 4,898 | * Main DoFn for processing ordered events
*
* @param <Event>
* @param <EventKey>
* @param <State>
*/
static class OrderedProcessorDoFn<Event, EventKey, Result, State extends MutableState<Event, Result>> extends
DoFn<KV<EventKey, KV<Long, Event>>, KV<EventKey, Result>> {
private static final Logger LOG = LoggerFactory.getLogger(OrderedProcessorDoFn.class);
private static final String PROCESSING_STATE = "processingState";
private static final String MUTABLE_STATE = "mutableState";
private static final String BUFFERED_EVENTS = "bufferedEvents";
private static final String STATUS_EMISSION_TIMER = "statusTimer";
private static final String LARGE_BATCH_EMISSION_TIMER = "largeBatchTimer";
private static final String WINDOW_CLOSED = "windowClosed";
private final EventExaminer<Event, State> eventExaminer;
@StateId(BUFFERED_EVENTS)
@SuppressWarnings("unused")
private final StateSpec<OrderedListState<Event>> bufferedEventsSpec;
@StateId(PROCESSING_STATE)
@SuppressWarnings("unused")
private final StateSpec<ValueState<ProcessingState<EventKey>>> processingStateSpec;
@SuppressWarnings("unused")
@StateId(MUTABLE_STATE)
private final StateSpec<ValueState<State>> mutableStateSpec;
@StateId(WINDOW_CLOSED)
@SuppressWarnings("unused")
private final StateSpec<ValueState<Boolean>> windowClosedSpec;
@TimerId(STATUS_EMISSION_TIMER)
@SuppressWarnings("unused")
private final TimerSpec statusEmissionTimer = TimerSpecs.timer(TimeDomain.PROCESSING_TIME);
@TimerId(LARGE_BATCH_EMISSION_TIMER)
@SuppressWarnings("unused")
private final TimerSpec largeBatchEmissionTimer = TimerSpecs.timer(TimeDomain.EVENT_TIME);
private final TupleTag<KV<EventKey, OrderedProcessingStatus>> statusTupleTag;
private final Duration statusUpdateFrequency;
private final TupleTag<KV<EventKey, Result>> mainOutputTupleTag;
private final TupleTag<KV<EventKey, OrderedProcessingDiagnosticEvent>> diagnosticEventsTupleTag;
private final TupleTag<KV<EventKey, KV<Long, UnprocessedEvent<Event>>>> unprocessedEventsTupleTag;
private final boolean produceDiagnosticEvents;
private final boolean produceStatusUpdateOnEveryEvent;
private final long maxNumberOfResultsToProduce;
private Long numberOfResultsBeforeBundleStart;
/**
* Stateful DoFn to do the bulk of processing
*
* @param eventExaminer
* @param eventCoder
* @param stateCoder
* @param keyCoder
* @param mainOutputTupleTag
* @param statusTupleTag
* @param statusUpdateFrequency
* @param diagnosticEventsTupleTag
* @param unprocessedEventTupleTag
* @param produceDiagnosticEvents
* @param produceStatusUpdateOnEveryEvent
* @param maxNumberOfResultsToProduce
*/
OrderedProcessorDoFn(
EventExaminer<Event, State> eventExaminer, Coder<Event> eventCoder,
Coder<State> stateCoder, Coder<EventKey> keyCoder,
TupleTag<KV<EventKey, Result>> mainOutputTupleTag,
TupleTag<KV<EventKey, OrderedProcessingStatus>> statusTupleTag,
Duration statusUpdateFrequency,
TupleTag<KV<EventKey, OrderedProcessingDiagnosticEvent>> diagnosticEventsTupleTag,
TupleTag<KV<EventKey, KV<Long, UnprocessedEvent<Event>>>> unprocessedEventTupleTag,
boolean produceDiagnosticEvents, boolean produceStatusUpdateOnEveryEvent,
long maxNumberOfResultsToProduce) {
this.eventExaminer = eventExaminer;
this.bufferedEventsSpec = StateSpecs.orderedList(eventCoder);
this.mutableStateSpec = StateSpecs.value(stateCoder);
this.processingStateSpec = StateSpecs.value(ProcessingStateCoder.of(keyCoder));
this.windowClosedSpec = StateSpecs.value(BooleanCoder.of());
this.mainOutputTupleTag = mainOutputTupleTag;
this.statusTupleTag = statusTupleTag;
this.unprocessedEventsTupleTag = unprocessedEventTupleTag;
this.statusUpdateFrequency = statusUpdateFrequency;
this.diagnosticEventsTupleTag = diagnosticEventsTupleTag;
this.produceDiagnosticEvents = produceDiagnosticEvents;
this.produceStatusUpdateOnEveryEvent = produceStatusUpdateOnEveryEvent;
this.maxNumberOfResultsToProduce = maxNumberOfResultsToProduce;
}
@StartBundle
public void onBundleStart() {
numberOfResultsBeforeBundleStart = null;
}
@FinishBundle
public void onBundleFinish() {
// This might be necessary because this field is also used in a Timer
numberOfResultsBeforeBundleStart = null;
}
@ProcessElement
public void processElement(
@StateId(BUFFERED_EVENTS) OrderedListState<Event> bufferedEventsState,
@AlwaysFetched @StateId(PROCESSING_STATE) ValueState<ProcessingState<EventKey>> processingStateState,
@StateId(MUTABLE_STATE) ValueState<State> mutableStateState,
@TimerId(STATUS_EMISSION_TIMER) Timer statusEmissionTimer,
@TimerId(LARGE_BATCH_EMISSION_TIMER) Timer largeBatchEmissionTimer,
@Element KV<EventKey, KV<Long, Event>> eventAndSequence,
MultiOutputReceiver outputReceiver,
BoundedWindow window) {
// TODO: should we make diagnostics generation optional? | /*
* Copyright 2023 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 org.apache.beam.sdk.extensions.ordered;
/**
* Transform for processing ordered events. Events are grouped by the key and within each key they
* are applied according to the provided sequence. Events which arrive out of sequence are buffered
* and reprocessed when new events for a given key arrived.
*
* @param <Event>
* @param <EventKey>
* @param <State>
*/
@AutoValue
@SuppressWarnings({"nullness", "TypeNameShadowing"})
public abstract class OrderedEventProcessor<Event, EventKey, Result, State extends MutableState<Event, Result>> extends
PTransform<PCollection<KV<EventKey, KV<Long, Event>>>, OrderedEventProcessorResult<EventKey, Result, Event>> {
public static final int DEFAULT_STATUS_UPDATE_FREQUENCY_SECONDS = 5;
public static final boolean DEFAULT_PRODUCE_DIAGNOSTIC_EVENTS = false;
private static final boolean DEFAULT_PRODUCE_STATUS_UPDATE_ON_EVERY_EVENT = false;
public static final int DEFAULT_MAX_ELEMENTS_TO_OUTPUT = 10_000;
public static <EventType, KeyType, ResultType, StateType extends MutableState<EventType, ResultType>> OrderedEventProcessor<EventType, KeyType, ResultType, StateType> create(
EventExaminer<EventType, StateType> eventExaminer, Coder<KeyType> keyCoder,
Coder<StateType> stateCoder, Coder<ResultType> resultTypeCoder) {
return new AutoValue_OrderedEventProcessor<>(eventExaminer, null /* no event coder */,
stateCoder, keyCoder, resultTypeCoder,
DEFAULT_STATUS_UPDATE_FREQUENCY_SECONDS, DEFAULT_PRODUCE_STATUS_UPDATE_ON_EVERY_EVENT,
DEFAULT_PRODUCE_DIAGNOSTIC_EVENTS, DEFAULT_MAX_ELEMENTS_TO_OUTPUT);
}
/**
* Default constructor method
*
* @param <EventType>
* @param <KeyType>
* @param <StateType>
* @param eventCoder coder for the Event class
* @param keyCoder coder for the Key class
* @param stateCoder coder for the State class
* @param resultCoder
* @return
*/
public static <EventType, KeyType, ResultType, StateType extends MutableState<EventType, ResultType>> OrderedEventProcessor<EventType, KeyType, ResultType, StateType> create(
EventExaminer<EventType, StateType> eventExaminer, Coder<EventType> eventCoder,
Coder<KeyType> keyCoder, Coder<StateType> stateCoder, Coder<ResultType> resultCoder) {
// TODO: none of the values are marked as @Nullable and the transform will fail if nulls are provided. But need a better error messaging.
return new AutoValue_OrderedEventProcessor<>(eventExaminer, eventCoder,
stateCoder, keyCoder, resultCoder,
DEFAULT_STATUS_UPDATE_FREQUENCY_SECONDS, DEFAULT_PRODUCE_STATUS_UPDATE_ON_EVERY_EVENT,
DEFAULT_PRODUCE_DIAGNOSTIC_EVENTS, DEFAULT_MAX_ELEMENTS_TO_OUTPUT);
}
/**
* Provide a custom status update frequency
*
* @param seconds
* @return
*/
public OrderedEventProcessor<Event, EventKey, Result, State> withStatusUpdateFrequencySeconds(
int seconds) {
return new AutoValue_OrderedEventProcessor<>(
this.getEventExaminer(), this.getEventCoder(), this.getStateCoder(), this.getKeyCoder(),
this.getResultCoder(), seconds,
this.isProduceStatusUpdateOnEveryEvent(), this.isProduceDiagnosticEvents(),
this.getMaxNumberOfResultsPerOutput());
}
public OrderedEventProcessor<Event, EventKey, Result, State> produceDiagnosticEvents(
boolean produceDiagnosticEvents) {
return new AutoValue_OrderedEventProcessor<>(
this.getEventExaminer(), this.getEventCoder(), this.getStateCoder(), this.getKeyCoder(),
this.getResultCoder(),
this.getStatusUpdateFrequencySeconds(), this.isProduceStatusUpdateOnEveryEvent(),
produceDiagnosticEvents, this.getMaxNumberOfResultsPerOutput());
}
/**
* Notice that unless the status frequency update is set to 0 or negative number the status will
* be produced on every event and with the specified frequency.
*/
public OrderedEventProcessor<Event, EventKey, Result, State> produceStatusUpdatesOnEveryEvent(
boolean value) {
return new AutoValue_OrderedEventProcessor<>(
this.getEventExaminer(), this.getEventCoder(), this.getStateCoder(), this.getKeyCoder(),
this.getResultCoder(),
this.getStatusUpdateFrequencySeconds(), value, this.isProduceDiagnosticEvents(),
this.getMaxNumberOfResultsPerOutput());
}
public OrderedEventProcessor<Event, EventKey, Result, State> withMaxResultsPerOutput(
long maxResultsPerOutput) {
return new AutoValue_OrderedEventProcessor<>(
this.getEventExaminer(), this.getEventCoder(), this.getStateCoder(), this.getKeyCoder(),
this.getResultCoder(),
this.getStatusUpdateFrequencySeconds(), this.isProduceStatusUpdateOnEveryEvent(),
this.isProduceDiagnosticEvents(), maxResultsPerOutput);
}
abstract EventExaminer<Event, State> getEventExaminer();
@Nullable
abstract Coder<Event> getEventCoder();
abstract Coder<State> getStateCoder();
@Nullable
abstract Coder<EventKey> getKeyCoder();
abstract Coder<Result> getResultCoder();
abstract int getStatusUpdateFrequencySeconds();
abstract boolean isProduceStatusUpdateOnEveryEvent();
abstract boolean isProduceDiagnosticEvents();
abstract long getMaxNumberOfResultsPerOutput();
@Override
public OrderedEventProcessorResult<EventKey, Result, Event> expand(
PCollection<KV<EventKey, KV<Long, Event>>> input) {
final TupleTag<KV<EventKey, Result>> mainOutput = new TupleTag<>("mainOutput") {
};
final TupleTag<KV<EventKey, OrderedProcessingStatus>> statusOutput = new TupleTag<>("status") {
};
final TupleTag<KV<EventKey, OrderedProcessingDiagnosticEvent>> diagnosticOutput = new TupleTag<>(
"diagnostics") {
};
final TupleTag<KV<EventKey, KV<Long, UnprocessedEvent<Event>>>> unprocessedEventOutput = new TupleTag<>(
"unprocessed-events") {
};
Coder<EventKey> keyCoder = getKeyCoder();
if (keyCoder == null) {
// Assume that the default key coder is used and use the key coder from it.
keyCoder = ((KvCoder<EventKey, KV<Long, Event>>) input.getCoder()).getKeyCoder();
}
Coder<Event> eventCoder = getEventCoder();
if (eventCoder == null) {
// Assume that the default key coder is used and use the event coder from it.
eventCoder = ((KvCoder<Long, Event>) ((KvCoder<EventKey, KV<Long, Event>>) input.getCoder()).getValueCoder()).getValueCoder();
}
PCollectionTuple processingResult = input.apply(ParDo.of(
new OrderedProcessorDoFn<>(getEventExaminer(), eventCoder,
getStateCoder(),
keyCoder, mainOutput, statusOutput,
getStatusUpdateFrequencySeconds() <= 0 ? null
: Duration.standardSeconds(getStatusUpdateFrequencySeconds()), diagnosticOutput,
unprocessedEventOutput,
isProduceDiagnosticEvents(), isProduceStatusUpdateOnEveryEvent(),
input.isBounded() == IsBounded.BOUNDED ? Integer.MAX_VALUE
: getMaxNumberOfResultsPerOutput())).withOutputTags(mainOutput,
TupleTagList.of(Arrays.asList(statusOutput, diagnosticOutput, unprocessedEventOutput))));
KvCoder<EventKey, Result> mainOutputCoder = KvCoder.of(keyCoder, getResultCoder());
KvCoder<EventKey, OrderedProcessingStatus> processingStatusCoder = KvCoder.of(keyCoder,
getOrderedProcessingStatusCoder(input.getPipeline()));
KvCoder<EventKey, OrderedProcessingDiagnosticEvent> diagnosticOutputCoder = KvCoder.of(keyCoder,
getOrderedProcessingDiagnosticsCoder(input.getPipeline()));
KvCoder<EventKey, KV<Long, UnprocessedEvent<Event>>> unprocessedEventsCoder = KvCoder.of(
keyCoder,
KvCoder.of(VarLongCoder.of(), new UnprocessedEventCoder<>(eventCoder)));
return new OrderedEventProcessorResult<>(
input.getPipeline(),
processingResult.get(mainOutput).setCoder(mainOutputCoder),
mainOutput,
processingResult.get(statusOutput).setCoder(processingStatusCoder),
statusOutput,
processingResult.get(diagnosticOutput).setCoder(diagnosticOutputCoder),
diagnosticOutput,
processingResult.get(unprocessedEventOutput).setCoder(unprocessedEventsCoder),
unprocessedEventOutput);
}
private static Coder<OrderedProcessingStatus> getOrderedProcessingStatusCoder(Pipeline pipeline) {
SchemaRegistry schemaRegistry = pipeline.getSchemaRegistry();
Coder<OrderedProcessingStatus> result;
try {
result = SchemaCoder.of(schemaRegistry.getSchema(OrderedProcessingStatus.class),
TypeDescriptor.of(OrderedProcessingStatus.class),
schemaRegistry.getToRowFunction(OrderedProcessingStatus.class),
schemaRegistry.getFromRowFunction(OrderedProcessingStatus.class));
} catch (NoSuchSchemaException e) {
throw new RuntimeException(e);
}
return result;
}
private static Coder<OrderedProcessingDiagnosticEvent> getOrderedProcessingDiagnosticsCoder(
Pipeline pipeline) {
SchemaRegistry schemaRegistry = pipeline.getSchemaRegistry();
Coder<OrderedProcessingDiagnosticEvent> result;
try {
result = SchemaCoder.of(schemaRegistry.getSchema(OrderedProcessingDiagnosticEvent.class),
TypeDescriptor.of(OrderedProcessingDiagnosticEvent.class),
schemaRegistry.getToRowFunction(OrderedProcessingDiagnosticEvent.class),
schemaRegistry.getFromRowFunction(OrderedProcessingDiagnosticEvent.class));
} catch (NoSuchSchemaException e) {
throw new RuntimeException(e);
}
return result;
}
/**
* Main DoFn for processing ordered events
*
* @param <Event>
* @param <EventKey>
* @param <State>
*/
static class OrderedProcessorDoFn<Event, EventKey, Result, State extends MutableState<Event, Result>> extends
DoFn<KV<EventKey, KV<Long, Event>>, KV<EventKey, Result>> {
private static final Logger LOG = LoggerFactory.getLogger(OrderedProcessorDoFn.class);
private static final String PROCESSING_STATE = "processingState";
private static final String MUTABLE_STATE = "mutableState";
private static final String BUFFERED_EVENTS = "bufferedEvents";
private static final String STATUS_EMISSION_TIMER = "statusTimer";
private static final String LARGE_BATCH_EMISSION_TIMER = "largeBatchTimer";
private static final String WINDOW_CLOSED = "windowClosed";
private final EventExaminer<Event, State> eventExaminer;
@StateId(BUFFERED_EVENTS)
@SuppressWarnings("unused")
private final StateSpec<OrderedListState<Event>> bufferedEventsSpec;
@StateId(PROCESSING_STATE)
@SuppressWarnings("unused")
private final StateSpec<ValueState<ProcessingState<EventKey>>> processingStateSpec;
@SuppressWarnings("unused")
@StateId(MUTABLE_STATE)
private final StateSpec<ValueState<State>> mutableStateSpec;
@StateId(WINDOW_CLOSED)
@SuppressWarnings("unused")
private final StateSpec<ValueState<Boolean>> windowClosedSpec;
@TimerId(STATUS_EMISSION_TIMER)
@SuppressWarnings("unused")
private final TimerSpec statusEmissionTimer = TimerSpecs.timer(TimeDomain.PROCESSING_TIME);
@TimerId(LARGE_BATCH_EMISSION_TIMER)
@SuppressWarnings("unused")
private final TimerSpec largeBatchEmissionTimer = TimerSpecs.timer(TimeDomain.EVENT_TIME);
private final TupleTag<KV<EventKey, OrderedProcessingStatus>> statusTupleTag;
private final Duration statusUpdateFrequency;
private final TupleTag<KV<EventKey, Result>> mainOutputTupleTag;
private final TupleTag<KV<EventKey, OrderedProcessingDiagnosticEvent>> diagnosticEventsTupleTag;
private final TupleTag<KV<EventKey, KV<Long, UnprocessedEvent<Event>>>> unprocessedEventsTupleTag;
private final boolean produceDiagnosticEvents;
private final boolean produceStatusUpdateOnEveryEvent;
private final long maxNumberOfResultsToProduce;
private Long numberOfResultsBeforeBundleStart;
/**
* Stateful DoFn to do the bulk of processing
*
* @param eventExaminer
* @param eventCoder
* @param stateCoder
* @param keyCoder
* @param mainOutputTupleTag
* @param statusTupleTag
* @param statusUpdateFrequency
* @param diagnosticEventsTupleTag
* @param unprocessedEventTupleTag
* @param produceDiagnosticEvents
* @param produceStatusUpdateOnEveryEvent
* @param maxNumberOfResultsToProduce
*/
OrderedProcessorDoFn(
EventExaminer<Event, State> eventExaminer, Coder<Event> eventCoder,
Coder<State> stateCoder, Coder<EventKey> keyCoder,
TupleTag<KV<EventKey, Result>> mainOutputTupleTag,
TupleTag<KV<EventKey, OrderedProcessingStatus>> statusTupleTag,
Duration statusUpdateFrequency,
TupleTag<KV<EventKey, OrderedProcessingDiagnosticEvent>> diagnosticEventsTupleTag,
TupleTag<KV<EventKey, KV<Long, UnprocessedEvent<Event>>>> unprocessedEventTupleTag,
boolean produceDiagnosticEvents, boolean produceStatusUpdateOnEveryEvent,
long maxNumberOfResultsToProduce) {
this.eventExaminer = eventExaminer;
this.bufferedEventsSpec = StateSpecs.orderedList(eventCoder);
this.mutableStateSpec = StateSpecs.value(stateCoder);
this.processingStateSpec = StateSpecs.value(ProcessingStateCoder.of(keyCoder));
this.windowClosedSpec = StateSpecs.value(BooleanCoder.of());
this.mainOutputTupleTag = mainOutputTupleTag;
this.statusTupleTag = statusTupleTag;
this.unprocessedEventsTupleTag = unprocessedEventTupleTag;
this.statusUpdateFrequency = statusUpdateFrequency;
this.diagnosticEventsTupleTag = diagnosticEventsTupleTag;
this.produceDiagnosticEvents = produceDiagnosticEvents;
this.produceStatusUpdateOnEveryEvent = produceStatusUpdateOnEveryEvent;
this.maxNumberOfResultsToProduce = maxNumberOfResultsToProduce;
}
@StartBundle
public void onBundleStart() {
numberOfResultsBeforeBundleStart = null;
}
@FinishBundle
public void onBundleFinish() {
// This might be necessary because this field is also used in a Timer
numberOfResultsBeforeBundleStart = null;
}
@ProcessElement
public void processElement(
@StateId(BUFFERED_EVENTS) OrderedListState<Event> bufferedEventsState,
@AlwaysFetched @StateId(PROCESSING_STATE) ValueState<ProcessingState<EventKey>> processingStateState,
@StateId(MUTABLE_STATE) ValueState<State> mutableStateState,
@TimerId(STATUS_EMISSION_TIMER) Timer statusEmissionTimer,
@TimerId(LARGE_BATCH_EMISSION_TIMER) Timer largeBatchEmissionTimer,
@Element KV<EventKey, KV<Long, Event>> eventAndSequence,
MultiOutputReceiver outputReceiver,
BoundedWindow window) {
// TODO: should we make diagnostics generation optional? | OrderedProcessingDiagnosticEvent.Builder diagnostics = OrderedProcessingDiagnosticEvent.builder(); | 0 | 2023-11-15 21:26:06+00:00 | 8k |
Hikaito/Fox-Engine | src/system/gui/project/ProjectEditor.java | [
{
"identifier": "ProjectManager",
"path": "src/system/project/ProjectManager.java",
"snippet": "public class ProjectManager {\n\n // UUID methods\n public String getUUID(){return root.getUUID();}\n public boolean matchesUUID(String other){\n return root.getUUID().equals(other);\n }\n\... | import system.project.ProjectManager;
import system.setting.CoreGlobal;
import system.backbone.EventE;
import system.project.treeElements.ProjectRoot;
import system.project.treeElements.ProjectUnitCore;
import system.project.treeElements.ProjectFile;
import system.project.treeElements.ProjectFolder;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;
import java.awt.*;
import java.io.IOException; | 6,286 | package system.gui.project;
//====================================================================================================
// Authors: Hikaito
// Project: Fox Engine
//====================================================================================================
public class ProjectEditor {
protected ProjectManager source;
JPanel editorPane = null; // used for resetting display
JPanel imageDisplay = null; // used for resetting display
JSplitPane splitPane = null;
DefaultMutableTreeNode treeRoot = null;
JTree tree;
// used for drawing background decision
private boolean[] color;
//constructor
public ProjectEditor(ProjectManager source) throws IOException {
// initialize color decision
color= new boolean[1];
color[0] = true;
//initialize frame
this.source = source;
//overall window
JFrame jFrame = new JFrame("Project Editor"); //initialize window title
jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //instate window close when exited
jFrame.setSize(CoreGlobal.EDITOR_WINDOW_WIDTH,CoreGlobal.EDITOR_WINDOW_HEIGHT); //initialize size
jFrame.setLocationRelativeTo(null); //center window
// on close, generate dictionary
jFrame.addWindowListener(new java.awt.event.WindowAdapter(){
@Override
public void windowClosed(java.awt.event.WindowEvent windowEvent){
source.updateDependencies(); //rebuild dictionary
}
});
//label region
imageDisplay = new JPanel();
imageDisplay.setLayout(new GridBagLayout()); //center items
//editor region
editorPane = new JPanel();
//editorPane.setLayout(new BoxLayout(editorPane, BoxLayout.Y_AXIS));
editorPane.setLayout(new FlowLayout()); //fixme I want this to be vertical but I'm not willing to fight it
//prepare regions
regenerateEditorPane(null); // initialize to null selection
// tree region
treeRoot = source.getTree();
tree = generateTree();
JSplitPane secondaryPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, imageDisplay, editorPane);
//new JScrollPane(editorPane,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER ));
secondaryPane.setResizeWeight(.7);
//Main split pane; generate tree [needs to initialize under editor for null selection reasons]
splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(tree), secondaryPane);
splitPane.setResizeWeight(.3);
jFrame.add(splitPane);
jFrame.setVisible(true); //initialize visibility (needs to be at the end of initialization)
}
// variable used for selection memory
ProjectUnitCore activeSelection = new ProjectFolder("NULL", -1); // empty file that is overwritten
protected JTree generateTree(){
// tree panel generation
JTree tree = new JTree(treeRoot); // make tree object
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); // set tree as selectable, one at a time
//selection listener
tree.addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
// on selection, call selection update
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); //get last selected item
regenerateEditorPane(node);
}
});
return tree;
}
// class for regenerating editor pane
public static class RegenerateEvent implements EventE {
private final ProjectEditor editor;
public RegenerateEvent(ProjectEditor editor){
this.editor = editor;
}
@Override
public void enact() {
editor.regenerateEditorPane();
}
}
protected void regenerateEditorPane(){
regenerateEditorPane((DefaultMutableTreeNode) tree.getLastSelectedPathComponent());
}
protected void regenerateEditorPane(DefaultMutableTreeNode selection){
//if no selection, render for no selection
if(selection == null){
generateNullDetails(); // if no selection, render for no selection
activeSelection = null; //update selection
return;
}
// render selection
ProjectUnitCore select = (ProjectUnitCore) selection.getUserObject();
// if selection has not changed, do nothing
//if (select == activeSelection) return; //removed so this can be used to intentionally refresh data
//otherwise generate appropriate details
if (select == null) generateNullDetails();
else if (select instanceof ProjectFile) generateFileDetails(selection);
else if (select instanceof ProjectFolder) generateFolderDetails(selection); | package system.gui.project;
//====================================================================================================
// Authors: Hikaito
// Project: Fox Engine
//====================================================================================================
public class ProjectEditor {
protected ProjectManager source;
JPanel editorPane = null; // used for resetting display
JPanel imageDisplay = null; // used for resetting display
JSplitPane splitPane = null;
DefaultMutableTreeNode treeRoot = null;
JTree tree;
// used for drawing background decision
private boolean[] color;
//constructor
public ProjectEditor(ProjectManager source) throws IOException {
// initialize color decision
color= new boolean[1];
color[0] = true;
//initialize frame
this.source = source;
//overall window
JFrame jFrame = new JFrame("Project Editor"); //initialize window title
jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //instate window close when exited
jFrame.setSize(CoreGlobal.EDITOR_WINDOW_WIDTH,CoreGlobal.EDITOR_WINDOW_HEIGHT); //initialize size
jFrame.setLocationRelativeTo(null); //center window
// on close, generate dictionary
jFrame.addWindowListener(new java.awt.event.WindowAdapter(){
@Override
public void windowClosed(java.awt.event.WindowEvent windowEvent){
source.updateDependencies(); //rebuild dictionary
}
});
//label region
imageDisplay = new JPanel();
imageDisplay.setLayout(new GridBagLayout()); //center items
//editor region
editorPane = new JPanel();
//editorPane.setLayout(new BoxLayout(editorPane, BoxLayout.Y_AXIS));
editorPane.setLayout(new FlowLayout()); //fixme I want this to be vertical but I'm not willing to fight it
//prepare regions
regenerateEditorPane(null); // initialize to null selection
// tree region
treeRoot = source.getTree();
tree = generateTree();
JSplitPane secondaryPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, imageDisplay, editorPane);
//new JScrollPane(editorPane,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER ));
secondaryPane.setResizeWeight(.7);
//Main split pane; generate tree [needs to initialize under editor for null selection reasons]
splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(tree), secondaryPane);
splitPane.setResizeWeight(.3);
jFrame.add(splitPane);
jFrame.setVisible(true); //initialize visibility (needs to be at the end of initialization)
}
// variable used for selection memory
ProjectUnitCore activeSelection = new ProjectFolder("NULL", -1); // empty file that is overwritten
protected JTree generateTree(){
// tree panel generation
JTree tree = new JTree(treeRoot); // make tree object
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); // set tree as selectable, one at a time
//selection listener
tree.addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
// on selection, call selection update
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); //get last selected item
regenerateEditorPane(node);
}
});
return tree;
}
// class for regenerating editor pane
public static class RegenerateEvent implements EventE {
private final ProjectEditor editor;
public RegenerateEvent(ProjectEditor editor){
this.editor = editor;
}
@Override
public void enact() {
editor.regenerateEditorPane();
}
}
protected void regenerateEditorPane(){
regenerateEditorPane((DefaultMutableTreeNode) tree.getLastSelectedPathComponent());
}
protected void regenerateEditorPane(DefaultMutableTreeNode selection){
//if no selection, render for no selection
if(selection == null){
generateNullDetails(); // if no selection, render for no selection
activeSelection = null; //update selection
return;
}
// render selection
ProjectUnitCore select = (ProjectUnitCore) selection.getUserObject();
// if selection has not changed, do nothing
//if (select == activeSelection) return; //removed so this can be used to intentionally refresh data
//otherwise generate appropriate details
if (select == null) generateNullDetails();
else if (select instanceof ProjectFile) generateFileDetails(selection);
else if (select instanceof ProjectFolder) generateFolderDetails(selection); | else if (select instanceof ProjectRoot) generateRootDetails(selection); | 3 | 2023-11-12 21:12:21+00:00 | 8k |
KomnisEvangelos/GeoApp | app/src/main/java/gr/ihu/geoapp/ui/signin/SignInViewModel.java | [
{
"identifier": "Repository",
"path": "app/src/main/java/gr/ihu/geoapp/managers/Repository.java",
"snippet": "public class Repository {\n private static final String BASE_URL = \"http://192.168.1.6/geoapp/\";\n private static Repository instance;\n\n private Repository() {\n }\n\n public ... | import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarException;
import gr.ihu.geoapp.managers.Repository;
import gr.ihu.geoapp.models.Image;
import gr.ihu.geoapp.models.users.RegularUser;
import gr.ihu.geoapp.models.users.User; | 4,905 | package gr.ihu.geoapp.ui.signin;
/**
* ViewModel class for the SignInFragment.
* This class handles user sign-in operations, communicates with the repository, and manages the UI-related data for the SignInFragment.
*/
public class SignInViewModel extends ViewModel {
/**
* MutableLiveData to notify observers about the success or failure of the sign-in operation.
*/
private MutableLiveData<Boolean> signinSuccess = new MutableLiveData<>();
/**
* Instance of the repository for handling user-related operations.
*/
private Repository repository;
/**
* The RegularUser instance representing the signed-in user.
*/
private RegularUser user = RegularUser.getInstance();
/**
* Constructor for the SignInViewModel.
* Initializes the repository instance.
*/
public SignInViewModel(){
repository = Repository.getInstance();
}
/**
* Retrieves the LiveData object containing the sign-in result.
*
*
*/
public LiveData<Boolean> getSigninResult(){
return signinSuccess;
}
/**
* Initiates the sign-in process with the provided email and password.
*
* @param signinEmail the user's email for sign-in
* @param signinPassword the user's password for sign-in
*/
public void signIn(String signinEmail, String signinPassword) {
repository.login(signinEmail, signinPassword, new Repository.RepositoryCallback() {
@Override
public void onSuccess(JSONObject response) {
//Log.d("response",response.toString());
if (response != null) {
try {
JSONObject jsonResponse = new JSONObject(String.valueOf(response));
if (jsonResponse.has("status")) {
String status = jsonResponse.getString("status");
if (status.equals("success")) {
JSONObject userData = (JSONObject) jsonResponse.get("user_data");
Integer idInt = (Integer) userData.get("id");
String idString = String.valueOf(idInt);
String fullName = (String) userData.get("full_name");
String email = (String) userData.get("email");
// String password = (String) userData.get("password");
String birthdate = (String) userData.get("birthdate");
String job = (String) userData.get("job");
String diploma = (String) userData.get("diploma");
String apiKey = (String) userData.get("api_key");
user.setUserId(idString);
user.setFullName(fullName);
user.setEmail(email);
user.setBirthdate(birthdate);
user.setJob(job);
user.setDiploma(diploma);
user.setApi_key(apiKey);
//try{
// String website = jsonResponse.getString("website");
// user.setWebsite(website);
// }catch (Exception e){
// user.setWebsite(null);
// }
// String photo = jsonResponse.isNull("photo") ? null : jsonResponse.getString("photo");
// user.setPhoto(photo);
//
JSONArray iamgesArray = userData.getJSONArray("photos"); | package gr.ihu.geoapp.ui.signin;
/**
* ViewModel class for the SignInFragment.
* This class handles user sign-in operations, communicates with the repository, and manages the UI-related data for the SignInFragment.
*/
public class SignInViewModel extends ViewModel {
/**
* MutableLiveData to notify observers about the success or failure of the sign-in operation.
*/
private MutableLiveData<Boolean> signinSuccess = new MutableLiveData<>();
/**
* Instance of the repository for handling user-related operations.
*/
private Repository repository;
/**
* The RegularUser instance representing the signed-in user.
*/
private RegularUser user = RegularUser.getInstance();
/**
* Constructor for the SignInViewModel.
* Initializes the repository instance.
*/
public SignInViewModel(){
repository = Repository.getInstance();
}
/**
* Retrieves the LiveData object containing the sign-in result.
*
*
*/
public LiveData<Boolean> getSigninResult(){
return signinSuccess;
}
/**
* Initiates the sign-in process with the provided email and password.
*
* @param signinEmail the user's email for sign-in
* @param signinPassword the user's password for sign-in
*/
public void signIn(String signinEmail, String signinPassword) {
repository.login(signinEmail, signinPassword, new Repository.RepositoryCallback() {
@Override
public void onSuccess(JSONObject response) {
//Log.d("response",response.toString());
if (response != null) {
try {
JSONObject jsonResponse = new JSONObject(String.valueOf(response));
if (jsonResponse.has("status")) {
String status = jsonResponse.getString("status");
if (status.equals("success")) {
JSONObject userData = (JSONObject) jsonResponse.get("user_data");
Integer idInt = (Integer) userData.get("id");
String idString = String.valueOf(idInt);
String fullName = (String) userData.get("full_name");
String email = (String) userData.get("email");
// String password = (String) userData.get("password");
String birthdate = (String) userData.get("birthdate");
String job = (String) userData.get("job");
String diploma = (String) userData.get("diploma");
String apiKey = (String) userData.get("api_key");
user.setUserId(idString);
user.setFullName(fullName);
user.setEmail(email);
user.setBirthdate(birthdate);
user.setJob(job);
user.setDiploma(diploma);
user.setApi_key(apiKey);
//try{
// String website = jsonResponse.getString("website");
// user.setWebsite(website);
// }catch (Exception e){
// user.setWebsite(null);
// }
// String photo = jsonResponse.isNull("photo") ? null : jsonResponse.getString("photo");
// user.setPhoto(photo);
//
JSONArray iamgesArray = userData.getJSONArray("photos"); | List<Image> imageList = new ArrayList<>(); | 1 | 2023-11-10 17:43:18+00:00 | 8k |
Nel1yMinecraft/Grim | src/main/java/ac/grim/grimac/manager/init/start/PacketManager.java | [
{
"identifier": "PacketWorldReaderEight",
"path": "src/main/java/ac/grim/grimac/events/packets/worldreader/PacketWorldReaderEight.java",
"snippet": "public class PacketWorldReaderEight extends BasePacketWorldReader {\n // Synchronous\n private void readChunk(ShortBuffer buf, BaseChunk[] chunks, Bi... | import ac.grim.grimac.events.packets.*;
import ac.grim.grimac.events.packets.worldreader.PacketWorldReaderEight;
import ac.grim.grimac.events.packets.worldreader.PacketWorldReaderNine;
import ac.grim.grimac.events.packets.worldreader.PacketWorldReaderSeven;
import ac.grim.grimac.events.packets.worldreader.PacketWorldReaderSixteen;
import ac.grim.grimac.manager.init.Initable;
import ac.grim.grimac.utils.anticheat.LogUtil;
import io.github.retrooper.packetevents.PacketEvents;
import io.github.retrooper.packetevents.utils.server.ServerVersion; | 4,740 | package ac.grim.grimac.manager.init.start;
public class PacketManager implements Initable {
@Override
public void start() {
LogUtil.info("Registering packets...");
PacketEvents.get().registerListener(new PacketPlayerAbilities());
PacketEvents.get().registerListener(new PacketPingListener());
PacketEvents.get().registerListener(new PacketPlayerDigging());
PacketEvents.get().registerListener(new PacketPlayerAttack());
PacketEvents.get().registerListener(new PacketEntityAction());
PacketEvents.get().registerListener(new PacketBlockAction());
PacketEvents.get().registerListener(new PacketFireworkListener());
PacketEvents.get().registerListener(new PacketSelfMetadataListener());
PacketEvents.get().registerListener(new PacketServerTeleport());
PacketEvents.get().registerListener(new PacketPlayerCooldown());
PacketEvents.get().registerListener(new PacketPlayerRespawn());
PacketEvents.get().registerListener(new CheckManagerListener());
PacketEvents.get().registerListener(new PacketPlayerSteer());
if (ServerVersion.getVersion().isNewerThanOrEquals(ServerVersion.v_1_16)) { | package ac.grim.grimac.manager.init.start;
public class PacketManager implements Initable {
@Override
public void start() {
LogUtil.info("Registering packets...");
PacketEvents.get().registerListener(new PacketPlayerAbilities());
PacketEvents.get().registerListener(new PacketPingListener());
PacketEvents.get().registerListener(new PacketPlayerDigging());
PacketEvents.get().registerListener(new PacketPlayerAttack());
PacketEvents.get().registerListener(new PacketEntityAction());
PacketEvents.get().registerListener(new PacketBlockAction());
PacketEvents.get().registerListener(new PacketFireworkListener());
PacketEvents.get().registerListener(new PacketSelfMetadataListener());
PacketEvents.get().registerListener(new PacketServerTeleport());
PacketEvents.get().registerListener(new PacketPlayerCooldown());
PacketEvents.get().registerListener(new PacketPlayerRespawn());
PacketEvents.get().registerListener(new CheckManagerListener());
PacketEvents.get().registerListener(new PacketPlayerSteer());
if (ServerVersion.getVersion().isNewerThanOrEquals(ServerVersion.v_1_16)) { | PacketEvents.get().registerListener(new PacketWorldReaderSixteen()); | 3 | 2023-11-11 05:14:12+00:00 | 8k |
kawainime/IOT-Smart_Farming | IOT_Farm_V.2/src/UI/task.java | [
{
"identifier": "Bugs_Log",
"path": "IOT_Farm_V.2/src/Core/Background/Bugs_Log.java",
"snippet": "public class Bugs_Log \n{\n public static void exceptions(String message)\n {\n String file_name = get_localDate.LocalDate()+\"Bugs.dat\";\n \n try\n {\n FileOut... | import Core.Background.Bugs_Log;
import Core.Background.ID_Genarator;
import Core.Background.Upcomming_Events;
import Core.MySql.Connector;
import com.deshan.model.ModelStaff;
import java.awt.Color;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.ImageIcon;
import javax.swing.plaf.basic.BasicInternalFrameUI;
import javax.swing.table.DefaultTableModel; | 4,113 | },
new String [] {
"ICO", "ACTIVITY INFO", "SCHEDULED DATE", "ACTIVITY ID", "ACTIVITY STATUS"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
table2.setFont(new java.awt.Font("Yu Gothic UI", 0, 14)); // NOI18N
table2.setGridColor(new java.awt.Color(255, 255, 255));
table2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
table2MouseClicked(evt);
}
});
jScrollPane2.setViewportView(table2);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 1247, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 233, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(jLabel8)
.addGap(18, 18, 18)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 568, Short.MAX_VALUE))
);
materialTabbed1.addTab("ALL EVENTS", jPanel2);
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addComponent(materialTabbed1, javax.swing.GroupLayout.PREFERRED_SIZE, 1252, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 28, Short.MAX_VALUE))
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addComponent(materialTabbed1, javax.swing.GroupLayout.PREFERRED_SIZE, 688, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 52, Short.MAX_VALUE))
);
getContentPane().add(jPanel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1280, 740));
pack();
}// </editor-fold>//GEN-END:initComponents
private void jTextField1FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField1FocusGained
if(jTextField1.getText().equals("Add Location"))
{
jTextField1.setText("");
jTextField1.setForeground(new Color(102,102,102));
}
}//GEN-LAST:event_jTextField1FocusGained
private void jTextField1FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField1FocusLost
if(jTextField1.getText().equals(""))
{
jTextField1.setText("Add Location");
jTextField1.setForeground(new Color(102,102,102));
}
}//GEN-LAST:event_jTextField1FocusLost
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField1ActionPerformed
private void jLabel4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel4MouseClicked
add_task();
}//GEN-LAST:event_jLabel4MouseClicked
private void table2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_table2MouseClicked
int row = table2.getSelectedRow();
String ID = table2.getValueAt(row,3).toString();
View view = new View();
view.load(ID);
view.setVisible(true);
}//GEN-LAST:event_table2MouseClicked
public void table_clean()
{
DefaultTableModel model = (DefaultTableModel) table2.getModel();
int rowCount = model.getRowCount();
for (int i = rowCount - 1; i >= 0; i--)
{
model.removeRow(i);
}
}
public void add_task()
{ | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package UI;
/**
*
* @author Jayashanka Deshan
*/
public class task extends javax.swing.JInternalFrame {
Integer value;
public task()
{
initComponents();
this.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
BasicInternalFrameUI bis = (BasicInternalFrameUI) this.getUI();
bis.setNorthPane(null);
jLabel2.setText("Activity ID : "+String.valueOf(ID_Genarator.id()));
initData();
Upcomming_Events.noticeboard_update();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel7 = new javax.swing.JLabel();
jPanel6 = new javax.swing.JPanel();
materialTabbed1 = new tabbed.MaterialTabbed();
jPanel3 = new javax.swing.JPanel();
jLabel6 = new javax.swing.JLabel();
roundPanel7 = new com.deshan.swing.RoundPanel();
noticeBoard = new com.deshan.swing.noticeboard.NoticeBoard();
jLabel14 = new javax.swing.JLabel();
roundPanel10 = new com.deshan.swing.RoundPanel();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
roundPanel11 = new com.deshan.swing.RoundPanel();
jLabel9 = new javax.swing.JLabel();
jLabel17 = new javax.swing.JLabel();
jLabel18 = new javax.swing.JLabel();
jLabel21 = new javax.swing.JLabel();
roundPanel12 = new com.deshan.swing.RoundPanel();
jLabel16 = new javax.swing.JLabel();
jLabel19 = new javax.swing.JLabel();
jLabel20 = new javax.swing.JLabel();
jLabel22 = new javax.swing.JLabel();
jPanel4 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
roundPanel2 = new com.deshan.swing.RoundPanel();
jLabel3 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
roundPanel3 = new com.deshan.swing.RoundPanel();
jTextField1 = new javax.swing.JTextField();
roundPanel4 = new com.deshan.swing.RoundPanel();
date = new com.toedter.calendar.JDateChooser();
roundPanel5 = new com.deshan.swing.RoundPanel();
jLabel2 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jLabel15 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jLabel8 = new javax.swing.JLabel();
jScrollPane2 = new javax.swing.JScrollPane();
table2 = new com.deshans.swing.Table();
jLabel7.setText("jLabel7");
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jPanel6.setBackground(new java.awt.Color(242, 242, 242));
materialTabbed1.setTabPlacement(javax.swing.JTabbedPane.BOTTOM);
materialTabbed1.setFont(new java.awt.Font("Monospaced", 0, 14)); // NOI18N
jPanel3.setBackground(new java.awt.Color(242, 242, 242));
jPanel3.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jLabel6.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel6.setForeground(new java.awt.Color(102, 102, 102));
jLabel6.setText("ICEBURG KEEP EVENTS ");
roundPanel7.setBackground(new java.awt.Color(255, 255, 255));
noticeBoard.setBackground(new java.awt.Color(204, 204, 204));
jLabel14.setFont(new java.awt.Font("Yu Gothic UI Semibold", 1, 16)); // NOI18N
jLabel14.setForeground(new java.awt.Color(102, 102, 102));
jLabel14.setText("UPCOMMING EVENTS");
javax.swing.GroupLayout roundPanel7Layout = new javax.swing.GroupLayout(roundPanel7);
roundPanel7.setLayout(roundPanel7Layout);
roundPanel7Layout.setHorizontalGroup(
roundPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(roundPanel7Layout.createSequentialGroup()
.addContainerGap()
.addGroup(roundPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(noticeBoard, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel14, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
roundPanel7Layout.setVerticalGroup(
roundPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, roundPanel7Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel14, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(noticeBoard, javax.swing.GroupLayout.DEFAULT_SIZE, 302, Short.MAX_VALUE)
.addContainerGap())
);
roundPanel10.setBackground(new java.awt.Color(255, 255, 255));
jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/history/2002.i039.018_remote_management_distant_work_isometric_icons-17.jpg"))); // NOI18N
jLabel11.setFont(new java.awt.Font("Yu Gothic UI Semibold", 0, 36)); // NOI18N
jLabel11.setForeground(new java.awt.Color(102, 102, 102));
jLabel11.setText("ICEBURG");
jLabel12.setFont(new java.awt.Font("Yu Gothic UI Semibold", 1, 30)); // NOI18N
jLabel12.setForeground(new java.awt.Color(102, 102, 102));
jLabel12.setText("KEEP EVENTS");
javax.swing.GroupLayout roundPanel10Layout = new javax.swing.GroupLayout(roundPanel10);
roundPanel10.setLayout(roundPanel10Layout);
roundPanel10Layout.setHorizontalGroup(
roundPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(roundPanel10Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(roundPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel12, javax.swing.GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE)
.addComponent(jLabel11, javax.swing.GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE))
.addContainerGap())
);
roundPanel10Layout.setVerticalGroup(
roundPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(roundPanel10Layout.createSequentialGroup()
.addContainerGap()
.addGroup(roundPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(roundPanel10Layout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(jLabel11)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE))
.addContainerGap())
);
roundPanel11.setBackground(new java.awt.Color(255, 255, 255));
jLabel9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/history/2002.i039.018_remote_management_distant_work_isometric_icons-15.jpg"))); // NOI18N
jLabel17.setFont(new java.awt.Font("Yu Gothic UI Semibold", 0, 36)); // NOI18N
jLabel17.setForeground(new java.awt.Color(102, 102, 102));
jLabel17.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel17.setText("TOTAL");
jLabel18.setFont(new java.awt.Font("Yu Gothic UI Semibold", 0, 80)); // NOI18N
jLabel18.setForeground(new java.awt.Color(102, 102, 102));
jLabel18.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel18.setText("29");
jLabel21.setFont(new java.awt.Font("Yu Gothic UI Semibold", 0, 36)); // NOI18N
jLabel21.setForeground(new java.awt.Color(102, 102, 102));
jLabel21.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel21.setText("EVENTS");
javax.swing.GroupLayout roundPanel11Layout = new javax.swing.GroupLayout(roundPanel11);
roundPanel11.setLayout(roundPanel11Layout);
roundPanel11Layout.setHorizontalGroup(
roundPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(roundPanel11Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel18, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(roundPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel17, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel21, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE)))
);
roundPanel11Layout.setVerticalGroup(
roundPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(roundPanel11Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel9, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE))
.addGroup(roundPanel11Layout.createSequentialGroup()
.addGap(52, 52, 52)
.addComponent(jLabel17, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel21, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(roundPanel11Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel18, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
roundPanel12.setBackground(new java.awt.Color(255, 255, 255));
jLabel16.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/history/2002.i039.018_remote_management_distant_work_isometric_icons-13.jpg"))); // NOI18N
jLabel19.setFont(new java.awt.Font("Yu Gothic UI Semibold", 0, 80)); // NOI18N
jLabel19.setForeground(new java.awt.Color(102, 102, 102));
jLabel19.setText("06 ");
jLabel20.setFont(new java.awt.Font("Yu Gothic UI Semibold", 0, 36)); // NOI18N
jLabel20.setForeground(new java.awt.Color(102, 102, 102));
jLabel20.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel20.setText("EVENTS");
jLabel22.setFont(new java.awt.Font("Yu Gothic UI Semibold", 0, 18)); // NOI18N
jLabel22.setForeground(new java.awt.Color(102, 102, 102));
jLabel22.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel22.setText("UPCOMMING");
javax.swing.GroupLayout roundPanel12Layout = new javax.swing.GroupLayout(roundPanel12);
roundPanel12.setLayout(roundPanel12Layout);
roundPanel12Layout.setHorizontalGroup(
roundPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(roundPanel12Layout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(jLabel16, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel19, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(roundPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel20, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel22, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(268, 268, 268))
);
roundPanel12Layout.setVerticalGroup(
roundPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(roundPanel12Layout.createSequentialGroup()
.addGap(51, 51, 51)
.addComponent(jLabel20, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel22, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(roundPanel12Layout.createSequentialGroup()
.addContainerGap()
.addGroup(roundPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel16, javax.swing.GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE)
.addComponent(jLabel19, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(roundPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(roundPanel10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(roundPanel11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(roundPanel12, javax.swing.GroupLayout.PREFERRED_SIZE, 403, Short.MAX_VALUE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel6)
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel6)
.addGap(14, 14, 14)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(roundPanel11, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(roundPanel12, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(roundPanel10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(roundPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
materialTabbed1.addTab("EVENT HOME", jPanel3);
jPanel4.setBackground(new java.awt.Color(255, 255, 255));
jPanel5.setBackground(new java.awt.Color(255, 255, 255));
jPanel5.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel1.setForeground(new java.awt.Color(102, 102, 102));
jLabel1.setText("ADD EVENTS");
jPanel5.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(21, 24, 199, -1));
roundPanel2.setBackground(new java.awt.Color(242, 242, 242));
jLabel3.setFont(new java.awt.Font("Yu Gothic UI", 0, 16)); // NOI18N
jLabel3.setForeground(new java.awt.Color(102, 102, 102));
jLabel3.setText("Discription : ");
jScrollPane1.setBackground(new java.awt.Color(255, 255, 255));
jScrollPane1.setBorder(null);
jScrollPane1.setForeground(new java.awt.Color(255, 255, 255));
jTextArea1.setBackground(new java.awt.Color(242, 242, 242));
jTextArea1.setColumns(20);
jTextArea1.setFont(new java.awt.Font("Yu Gothic UI", 0, 15)); // NOI18N
jTextArea1.setForeground(new java.awt.Color(102, 102, 102));
jTextArea1.setRows(5);
jTextArea1.setBorder(null);
jScrollPane1.setViewportView(jTextArea1);
javax.swing.GroupLayout roundPanel2Layout = new javax.swing.GroupLayout(roundPanel2);
roundPanel2.setLayout(roundPanel2Layout);
roundPanel2Layout.setHorizontalGroup(
roundPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(roundPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(roundPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(roundPanel2Layout.createSequentialGroup()
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 704, Short.MAX_VALUE))
.addContainerGap())
);
roundPanel2Layout.setVerticalGroup(
roundPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(roundPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(19, Short.MAX_VALUE))
);
jPanel5.add(roundPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(21, 245, -1, -1));
roundPanel3.setBackground(new java.awt.Color(242, 242, 242));
jTextField1.setBackground(new java.awt.Color(242, 242, 242));
jTextField1.setFont(new java.awt.Font("Yu Gothic UI", 0, 16)); // NOI18N
jTextField1.setForeground(new java.awt.Color(102, 102, 102));
jTextField1.setText("Add Location");
jTextField1.setBorder(null);
jTextField1.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextField1FocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jTextField1FocusLost(evt);
}
});
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
javax.swing.GroupLayout roundPanel3Layout = new javax.swing.GroupLayout(roundPanel3);
roundPanel3.setLayout(roundPanel3Layout);
roundPanel3Layout.setHorizontalGroup(
roundPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(roundPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 694, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(20, Short.MAX_VALUE))
);
roundPanel3Layout.setVerticalGroup(
roundPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, roundPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 41, Short.MAX_VALUE)
.addContainerGap())
);
jPanel5.add(roundPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(21, 164, -1, -1));
roundPanel4.setBackground(new java.awt.Color(242, 242, 242));
date.setBackground(new java.awt.Color(242, 242, 242));
date.setForeground(new java.awt.Color(204, 204, 204));
date.setFocusable(false);
date.setFont(new java.awt.Font("Yu Gothic UI", 0, 16)); // NOI18N
javax.swing.GroupLayout roundPanel4Layout = new javax.swing.GroupLayout(roundPanel4);
roundPanel4.setLayout(roundPanel4Layout);
roundPanel4Layout.setHorizontalGroup(
roundPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, roundPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(date, javax.swing.GroupLayout.DEFAULT_SIZE, 324, Short.MAX_VALUE)
.addContainerGap())
);
roundPanel4Layout.setVerticalGroup(
roundPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(roundPanel4Layout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(date, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(14, Short.MAX_VALUE))
);
jPanel5.add(roundPanel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(401, 83, -1, -1));
roundPanel5.setBackground(new java.awt.Color(242, 242, 242));
jLabel2.setFont(new java.awt.Font("Yu Gothic UI", 0, 16)); // NOI18N
jLabel2.setForeground(new java.awt.Color(102, 102, 102));
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel2.setText("Activity ID : 165383");
jLabel2.setToolTipText("");
javax.swing.GroupLayout roundPanel5Layout = new javax.swing.GroupLayout(roundPanel5);
roundPanel5.setLayout(roundPanel5Layout);
roundPanel5Layout.setHorizontalGroup(
roundPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(roundPanel5Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 330, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(22, Short.MAX_VALUE))
);
roundPanel5Layout.setVerticalGroup(
roundPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, roundPanel5Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanel5.add(roundPanel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(21, 83, -1, 63));
jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel4.setForeground(new java.awt.Color(102, 102, 102));
jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/icons/registration_30px.png"))); // NOI18N
jLabel4.setText("ADD CURRENT EVENT");
jLabel4.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel4MouseClicked(evt);
}
});
jPanel5.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 560, 190, 30));
jPanel5.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 554, 350, 40));
jSeparator1.setForeground(new java.awt.Color(255, 255, 255));
jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);
jPanel5.add(jSeparator1, new org.netbeans.lib.awtextra.AbsoluteConstraints(760, 10, -1, 630));
jLabel15.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/history/2002.i039.018_remote_management_distant_work_isometric_icons-01.jpg"))); // NOI18N
jPanel5.add(jLabel15, new org.netbeans.lib.awtextra.AbsoluteConstraints(770, 80, 470, 500));
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, 1247, Short.MAX_VALUE)
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
materialTabbed1.addTab("ADD EVENT", jPanel4);
jPanel2.setBackground(new java.awt.Color(242, 242, 242));
jLabel8.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel8.setForeground(new java.awt.Color(102, 102, 102));
jLabel8.setText("EVENTS MANEGAR");
table2.setForeground(new java.awt.Color(255, 255, 255));
table2.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"ICO", "ACTIVITY INFO", "SCHEDULED DATE", "ACTIVITY ID", "ACTIVITY STATUS"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
table2.setFont(new java.awt.Font("Yu Gothic UI", 0, 14)); // NOI18N
table2.setGridColor(new java.awt.Color(255, 255, 255));
table2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
table2MouseClicked(evt);
}
});
jScrollPane2.setViewportView(table2);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 1247, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 233, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(jLabel8)
.addGap(18, 18, 18)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 568, Short.MAX_VALUE))
);
materialTabbed1.addTab("ALL EVENTS", jPanel2);
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addComponent(materialTabbed1, javax.swing.GroupLayout.PREFERRED_SIZE, 1252, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 28, Short.MAX_VALUE))
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addComponent(materialTabbed1, javax.swing.GroupLayout.PREFERRED_SIZE, 688, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 52, Short.MAX_VALUE))
);
getContentPane().add(jPanel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1280, 740));
pack();
}// </editor-fold>//GEN-END:initComponents
private void jTextField1FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField1FocusGained
if(jTextField1.getText().equals("Add Location"))
{
jTextField1.setText("");
jTextField1.setForeground(new Color(102,102,102));
}
}//GEN-LAST:event_jTextField1FocusGained
private void jTextField1FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField1FocusLost
if(jTextField1.getText().equals(""))
{
jTextField1.setText("Add Location");
jTextField1.setForeground(new Color(102,102,102));
}
}//GEN-LAST:event_jTextField1FocusLost
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField1ActionPerformed
private void jLabel4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel4MouseClicked
add_task();
}//GEN-LAST:event_jLabel4MouseClicked
private void table2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_table2MouseClicked
int row = table2.getSelectedRow();
String ID = table2.getValueAt(row,3).toString();
View view = new View();
view.load(ID);
view.setVisible(true);
}//GEN-LAST:event_table2MouseClicked
public void table_clean()
{
DefaultTableModel model = (DefaultTableModel) table2.getModel();
int rowCount = model.getRowCount();
for (int i = rowCount - 1; i >= 0; i--)
{
model.removeRow(i);
}
}
public void add_task()
{ | Connection conn = Connector.connection(); | 3 | 2023-11-11 08:23:10+00:00 | 8k |
Outer-Fields/item-server | src/main/java/io/mindspice/itemserver/monitor/BlockchainMonitor.java | [
{
"identifier": "PackType",
"path": "src/main/java/io/mindspice/itemserver/schema/PackType.java",
"snippet": "public enum PackType {\n BOOSTER(12),\n STARTER(39);\n\n public int cardAmount;\n\n PackType(int cardAmount) {\n this.cardAmount = cardAmount;\n }\n\n}"
},
{
"ident... | import io.mindspice.databaseservice.client.api.OkraChiaAPI;
import io.mindspice.databaseservice.client.api.OkraNFTAPI;
import io.mindspice.databaseservice.client.schema.AccountDid;
import io.mindspice.databaseservice.client.schema.Card;
import io.mindspice.databaseservice.client.schema.CardAndAccountCheck;
import io.mindspice.databaseservice.client.schema.NftUpdate;
import io.mindspice.itemserver.schema.PackPurchase;
import io.mindspice.itemserver.schema.PackType;
import io.mindspice.itemserver.Settings;
import io.mindspice.itemserver.util.CustomLogger;
import io.mindspice.itemserver.services.PackMint;
import io.mindspice.itemserver.util.Utils;
import io.mindspice.jxch.rpc.http.FullNodeAPI;
import io.mindspice.jxch.rpc.http.WalletAPI;
import io.mindspice.jxch.rpc.schemas.ApiResponse;
import io.mindspice.jxch.rpc.schemas.custom.CatSenderInfo;
import io.mindspice.jxch.rpc.schemas.fullnode.AdditionsAndRemovals;
import io.mindspice.jxch.rpc.schemas.object.CoinRecord;
import io.mindspice.jxch.rpc.schemas.wallet.nft.NftInfo;
import io.mindspice.jxch.rpc.util.ChiaUtils;
import io.mindspice.jxch.rpc.util.RPCException;
import io.mindspice.jxch.transact.service.mint.MintService;
import io.mindspice.jxch.transact.logging.TLogLevel;
import io.mindspice.mindlib.data.tuples.Pair;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Supplier;
import java.util.stream.Stream; | 4,570 | public void run() {
if (Settings.get().isPaused) { return; }
if (semaphore.availablePermits() == 0) { return; }
try {
semaphore.acquire();
if (!((nodeAPI.getHeight().data().orElseThrow() - Settings.get().heightBuffer) >= nextHeight)) {
return;
}
long start = System.currentTimeMillis();
AdditionsAndRemovals coinRecords = chiaAPI.getCoinRecordsByHeight(nextHeight)
.data().orElseThrow(chiaExcept);
List<CoinRecord> additions = coinRecords.additions().stream().filter(a -> !a.coinbase()).toList();
List<CoinRecord> removals = coinRecords.removals().stream().filter(a -> !a.coinbase()).toList();
if (additions.isEmpty()) {
logger.logApp(this.getClass(), TLogLevel.INFO, "Finished scan of block height: " + nextHeight +
" | Additions: 0" +
" | Block scan took: " + (System.currentTimeMillis() - start) + " ms");
nextHeight++; // Non-atomic inc doesn't matter, non-critical, is volatile to observe when monitoring
return;
}
// NOTE offer transactions need to be discovered via finding the parent in the removals
// since they do some intermediate operations
CompletableFuture<CardAndAccountCheck> cardAndAccountCheck = CompletableFuture.supplyAsync(() -> {
var cardOrAccountUpdates = nftAPI.checkIfCardOrAccountExists(
Stream.concat(additions.stream(), removals.stream())
.map(a -> a.coin().parentCoinInfo())
.distinct().toList()
);
if (cardOrAccountUpdates.data().isPresent()) {
return cardOrAccountUpdates.data().get();
}
return null;
}, virtualExec);
CompletableFuture<List<PackPurchase>> packCheck = CompletableFuture.supplyAsync(() -> {
List<PackPurchase> packPurchases = null;
var packRecords = additions.stream().filter(a -> assetMap.containsKey(a.coin().puzzleHash())).toList();
if (!packRecords.isEmpty()) {
packPurchases = new ArrayList<>(packRecords.size());
for (var record : packRecords) {
int amount = (int) (record.coin().amount() / 1000);
try {
ApiResponse<CatSenderInfo> catInfoResp = nodeAPI.getCatSenderInfo(record);
if (!catInfoResp.success()) {
logger.logApp(this.getClass(), TLogLevel.ERROR, " Failed asset lookup, wrong asset?" +
" | Coin: " + ChiaUtils.getCoinId(record.coin()) +
" | Amount(mojos / 1000): " + amount +
" | Error: " + catInfoResp.error());
continue;
}
CatSenderInfo catInfo = catInfoResp.data().orElseThrow(chiaExcept);
if (!catInfo.assetId().equals(assetMap.get(record.coin().puzzleHash()).first())) {
logger.logApp(this.getClass(), TLogLevel.INFO, "Wrong Asset Received: " + catInfo.assetId()
+ " | Coin: " + ChiaUtils.getCoinId(record.coin())
+ " | Expected: " + assetMap.get(record.coin().puzzleHash()).first()
+ " | Amount: " + record.coin().amount());
continue;
}
PackType packType = assetMap.get(record.coin().puzzleHash()).second();
for (int i = 0; i < amount; ++i) {
String uuid = UUID.randomUUID().toString();
logger.logApp(this.getClass(), TLogLevel.INFO, "Submitted pack purchase " +
" | UUID: " + uuid +
" | Coin: " + ChiaUtils.getCoinId(record.coin()) +
" | Amount(mojos / 1000): " + amount +
" | Asset: " + catInfo.assetId() +
" | Sender Address" + catInfo.senderPuzzleHash()
);
packPurchases.add(new PackPurchase(
catInfo.senderPuzzleHash(),
packType, uuid,
nextHeight,
ChiaUtils.getCoinId(record.coin()))
);
}
} catch (RPCException e) {
logger.logApp(this.getClass(), TLogLevel.FAILED, "Failed asset lookups at height: " + nextHeight +
" | Reason: " + e.getMessage() +
" | Coin: " + ChiaUtils.getCoinId(record.coin()) +
" | Amount(mojos / 1000): " + amount);
}
}
return packPurchases;
}
return null;
}, virtualExec);
CardAndAccountCheck cardAndAccountResults = cardAndAccountCheck.get();
List<PackPurchase> packPurchasesResults = packCheck.get();
boolean foundChange = false;
if (cardAndAccountResults != null) {
if (!cardAndAccountResults.existingCards().isEmpty() || !cardAndAccountResults.existingAccounts().isEmpty()) {
virtualExec.submit(new UpdateDbInfo(
cardAndAccountResults.existingCards(),
cardAndAccountResults.existingAccounts())
);
foundChange = true;
}
}
if (packPurchasesResults != null && !packPurchasesResults.isEmpty()) {
packPurchasesResults.forEach(
p -> virtualExec.submit(() -> nftAPI.addPackPurchases(
p.uuid(),
p.address(),
p.packType().name(),
p.height(),
p.coinId())
)
);
logger.logApp(this.getClass(), TLogLevel.DEBUG, "Submitting purchases"); | package io.mindspice.itemserver.monitor;
public class BlockchainMonitor implements Runnable {
private volatile int nextHeight;
private final FullNodeAPI nodeAPI;
private final WalletAPI walletAPI;
private final OkraChiaAPI chiaAPI;
private final OkraNFTAPI nftAPI;
private final MintService mintService;
private final Map<String, Pair<String, PackType>> assetMap;
private final List<Card> cardList;
private final CustomLogger logger;
private final Semaphore semaphore = new Semaphore(1);
protected final Supplier<RPCException> chiaExcept =
() -> new RPCException("Required Chia RPC call returned Optional.empty");
private final ExecutorService virtualExec = Executors.newVirtualThreadPerTaskExecutor();
public BlockchainMonitor(
FullNodeAPI nodeAPI, WalletAPI walletAPI,
OkraChiaAPI chiaAPI, OkraNFTAPI nftAPI,
MintService mintService, Map<String,
Pair<String, PackType>> assetMap,
List<Card> cardList, int startHeight,
CustomLogger logger) {
nextHeight = startHeight;
this.nodeAPI = nodeAPI;
this.walletAPI = walletAPI;
this.chiaAPI = chiaAPI;
this.nftAPI = nftAPI;
this.mintService = mintService;
this.assetMap = assetMap;
this.cardList = cardList;
this.logger = logger;
logger.logApp(this.getClass(), TLogLevel.INFO, "Started Blockchain Monitor");
}
public int getNextHeight() {
return nextHeight;
}
@Override
public void run() {
if (Settings.get().isPaused) { return; }
if (semaphore.availablePermits() == 0) { return; }
try {
semaphore.acquire();
if (!((nodeAPI.getHeight().data().orElseThrow() - Settings.get().heightBuffer) >= nextHeight)) {
return;
}
long start = System.currentTimeMillis();
AdditionsAndRemovals coinRecords = chiaAPI.getCoinRecordsByHeight(nextHeight)
.data().orElseThrow(chiaExcept);
List<CoinRecord> additions = coinRecords.additions().stream().filter(a -> !a.coinbase()).toList();
List<CoinRecord> removals = coinRecords.removals().stream().filter(a -> !a.coinbase()).toList();
if (additions.isEmpty()) {
logger.logApp(this.getClass(), TLogLevel.INFO, "Finished scan of block height: " + nextHeight +
" | Additions: 0" +
" | Block scan took: " + (System.currentTimeMillis() - start) + " ms");
nextHeight++; // Non-atomic inc doesn't matter, non-critical, is volatile to observe when monitoring
return;
}
// NOTE offer transactions need to be discovered via finding the parent in the removals
// since they do some intermediate operations
CompletableFuture<CardAndAccountCheck> cardAndAccountCheck = CompletableFuture.supplyAsync(() -> {
var cardOrAccountUpdates = nftAPI.checkIfCardOrAccountExists(
Stream.concat(additions.stream(), removals.stream())
.map(a -> a.coin().parentCoinInfo())
.distinct().toList()
);
if (cardOrAccountUpdates.data().isPresent()) {
return cardOrAccountUpdates.data().get();
}
return null;
}, virtualExec);
CompletableFuture<List<PackPurchase>> packCheck = CompletableFuture.supplyAsync(() -> {
List<PackPurchase> packPurchases = null;
var packRecords = additions.stream().filter(a -> assetMap.containsKey(a.coin().puzzleHash())).toList();
if (!packRecords.isEmpty()) {
packPurchases = new ArrayList<>(packRecords.size());
for (var record : packRecords) {
int amount = (int) (record.coin().amount() / 1000);
try {
ApiResponse<CatSenderInfo> catInfoResp = nodeAPI.getCatSenderInfo(record);
if (!catInfoResp.success()) {
logger.logApp(this.getClass(), TLogLevel.ERROR, " Failed asset lookup, wrong asset?" +
" | Coin: " + ChiaUtils.getCoinId(record.coin()) +
" | Amount(mojos / 1000): " + amount +
" | Error: " + catInfoResp.error());
continue;
}
CatSenderInfo catInfo = catInfoResp.data().orElseThrow(chiaExcept);
if (!catInfo.assetId().equals(assetMap.get(record.coin().puzzleHash()).first())) {
logger.logApp(this.getClass(), TLogLevel.INFO, "Wrong Asset Received: " + catInfo.assetId()
+ " | Coin: " + ChiaUtils.getCoinId(record.coin())
+ " | Expected: " + assetMap.get(record.coin().puzzleHash()).first()
+ " | Amount: " + record.coin().amount());
continue;
}
PackType packType = assetMap.get(record.coin().puzzleHash()).second();
for (int i = 0; i < amount; ++i) {
String uuid = UUID.randomUUID().toString();
logger.logApp(this.getClass(), TLogLevel.INFO, "Submitted pack purchase " +
" | UUID: " + uuid +
" | Coin: " + ChiaUtils.getCoinId(record.coin()) +
" | Amount(mojos / 1000): " + amount +
" | Asset: " + catInfo.assetId() +
" | Sender Address" + catInfo.senderPuzzleHash()
);
packPurchases.add(new PackPurchase(
catInfo.senderPuzzleHash(),
packType, uuid,
nextHeight,
ChiaUtils.getCoinId(record.coin()))
);
}
} catch (RPCException e) {
logger.logApp(this.getClass(), TLogLevel.FAILED, "Failed asset lookups at height: " + nextHeight +
" | Reason: " + e.getMessage() +
" | Coin: " + ChiaUtils.getCoinId(record.coin()) +
" | Amount(mojos / 1000): " + amount);
}
}
return packPurchases;
}
return null;
}, virtualExec);
CardAndAccountCheck cardAndAccountResults = cardAndAccountCheck.get();
List<PackPurchase> packPurchasesResults = packCheck.get();
boolean foundChange = false;
if (cardAndAccountResults != null) {
if (!cardAndAccountResults.existingCards().isEmpty() || !cardAndAccountResults.existingAccounts().isEmpty()) {
virtualExec.submit(new UpdateDbInfo(
cardAndAccountResults.existingCards(),
cardAndAccountResults.existingAccounts())
);
foundChange = true;
}
}
if (packPurchasesResults != null && !packPurchasesResults.isEmpty()) {
packPurchasesResults.forEach(
p -> virtualExec.submit(() -> nftAPI.addPackPurchases(
p.uuid(),
p.address(),
p.packType().name(),
p.height(),
p.coinId())
)
);
logger.logApp(this.getClass(), TLogLevel.DEBUG, "Submitting purchases"); | virtualExec.submit(new PackMint(cardList, packPurchasesResults, mintService, nftAPI, logger, virtualExec)); | 3 | 2023-11-14 14:56:37+00:00 | 8k |
CodecNomad/CodecClient | src/main/java/com/github/codecnomad/codecclient/Client.java | [
{
"identifier": "MainCommand",
"path": "src/main/java/com/github/codecnomad/codecclient/command/MainCommand.java",
"snippet": "@SuppressWarnings(\"unused\")\n@Command(value = \"codecclient\", aliases = {\"codec\"})\npublic class MainCommand {\n List<BlockPos> waypoints = new ArrayList<>();\n ... | import cc.polyfrost.oneconfig.utils.commands.CommandManager;
import com.github.codecnomad.codecclient.command.MainCommand;
import com.github.codecnomad.codecclient.modules.FishingMacro;
import com.github.codecnomad.codecclient.modules.Module;
import com.github.codecnomad.codecclient.ui.Config;
import com.github.codecnomad.codecclient.utils.Rotation;
import net.minecraft.client.Minecraft;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.network.FMLNetworkEvent;
import java.util.HashMap;
import java.util.Map; | 5,009 | package com.github.codecnomad.codecclient;
@Mod(modid = "codecclient", useMetadata = true)
public class Client {
public static Map<String, Module> modules = new HashMap<>();
public static Minecraft mc = Minecraft.getMinecraft();
public static Rotation rotation = new Rotation();
public static Config guiConfig;
static { | package com.github.codecnomad.codecclient;
@Mod(modid = "codecclient", useMetadata = true)
public class Client {
public static Map<String, Module> modules = new HashMap<>();
public static Minecraft mc = Minecraft.getMinecraft();
public static Rotation rotation = new Rotation();
public static Config guiConfig;
static { | modules.put("FishingMacro", new FishingMacro()); | 1 | 2023-11-16 10:12:20+00:00 | 8k |
maarlakes/common | src/main/java/cn/maarlakes/common/factory/bean/BeanFactories.java | [
{
"identifier": "SpiServiceLoader",
"path": "src/main/java/cn/maarlakes/common/spi/SpiServiceLoader.java",
"snippet": "public final class SpiServiceLoader<T> implements Iterable<T> {\n\n private static final String PREFIX = \"META-INF/services/\";\n\n private static final ConcurrentMap<ClassLoader... | import cn.maarlakes.common.spi.SpiServiceLoader;
import cn.maarlakes.common.utils.ClassUtils;
import cn.maarlakes.common.utils.Lazy;
import jakarta.annotation.Nonnull;
import java.lang.reflect.Constructor;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.*;
import java.util.function.Supplier; | 4,174 | throw new BeanException("Bean of type " + beanType.getName() + " not found.");
}
@Nonnull
public static <T> Optional<T> getBeanOptional(@Nonnull Class<T> beanType) {
return Optional.ofNullable(getBeanOrNull(beanType));
}
@Nonnull
public static <T> T getBean(@Nonnull Class<T> beanType, @Nonnull Object... args) {
if (SERVICES.isEmpty()) {
return ReflectBeanProvider.getInstance().getBean(beanType, args);
}
for (BeanProvider provider : SERVICES) {
if (provider.contains(beanType)) {
return provider.getBean(beanType, args);
}
}
throw new BeanException("Bean of type " + beanType.getName() + " not found.");
}
public static <T> T getBeanOrNull(@Nonnull Class<T> beanType) {
if (SERVICES.isEmpty()) {
return ReflectBeanProvider.getInstance().getBeanOrNull(beanType);
}
for (BeanProvider provider : SERVICES) {
if (provider.contains(beanType)) {
return provider.getBeanOrNull(beanType);
}
}
return null;
}
@Nonnull
public static <T> T getBean(@Nonnull String beanName) {
if (SERVICES.isEmpty()) {
return ReflectBeanProvider.getInstance().getBean(beanName);
}
for (BeanProvider provider : SERVICES) {
if (provider.contains(beanName)) {
return provider.getBean(beanName);
}
}
throw new BeanException("Bean of name " + beanName + " not found.");
}
@Nonnull
public static <T> Optional<T> getBeanOptional(@Nonnull String beanName) {
return Optional.ofNullable(getBeanOrNull(beanName));
}
public static <T> T getBeanOrNull(@Nonnull String beanName) {
if (SERVICES.isEmpty()) {
return ReflectBeanProvider.getInstance().getBeanOrNull(beanName);
}
for (BeanProvider provider : SERVICES) {
if (provider.contains(beanName)) {
return provider.getBeanOrNull(beanName);
}
}
return null;
}
public static <T> T getBeanOrDefault(@Nonnull Class<T> beanType, @Nonnull T defaultValue) {
final T bean = getBeanOrNull(beanType);
if (bean == null) {
return defaultValue;
}
return bean;
}
public static <T> T getBeanOrDefault(@Nonnull Class<T> beanType, @Nonnull Supplier<T> defaultValue) {
final T bean = getBeanOrNull(beanType);
if (bean == null) {
return defaultValue.get();
}
return bean;
}
@Nonnull
public static <T> T getBeanOrNew(@Nonnull Class<T> beanType, @Nonnull Object... args) {
return getBeanOrNew(beanType, ClassUtils.parameterTypes(args), args);
}
@Nonnull
@SuppressWarnings("unchecked")
public static <T> T getBeanOrNew(@Nonnull Class<T> beanType, @Nonnull Class<?>[] argTypes, @Nonnull Object[] args) {
final T bean = getBeanOrNull(beanType);
if (bean != null) {
return bean;
}
return (T) newInstance(ClassUtils.getMatchingAccessibleDeclaredConstructor(beanType, argTypes), args);
}
@Nonnull
public static <T> List<T> getBeans(@Nonnull Class<T> beanType) {
if (SERVICES.isEmpty()) {
return ReflectBeanProvider.getInstance().getBeans(beanType);
}
final List<T> list = new ArrayList<>();
for (BeanProvider provider : SERVICES) {
list.addAll(provider.getBeans(beanType));
}
return list;
}
@Nonnull
public static <T> Map<String, T> getBeanMap(@Nonnull Class<T> beanType) {
if (SERVICES.isEmpty()) {
return ReflectBeanProvider.getInstance().getBeanMap(beanType);
}
final Map<String, T> map = new HashMap<>();
for (BeanProvider provider : SERVICES) {
map.putAll(provider.getBeanMap(beanType));
}
return map;
}
@Nonnull
public static <T> Supplier<T> getBeanLazy(@Nonnull Class<T> beanType) { | package cn.maarlakes.common.factory.bean;
/**
* @author linjpxc
*/
public final class BeanFactories {
private BeanFactories() {
}
private static final SpiServiceLoader<BeanProvider> SERVICES = SpiServiceLoader.loadShared(BeanProvider.class);
public static boolean contains(@Nonnull Class<?> beanType) {
if (SERVICES.isEmpty()) {
return ReflectBeanProvider.getInstance().contains(beanType);
}
for (BeanProvider provider : SERVICES) {
if (provider.contains(beanType)) {
return true;
}
}
return false;
}
public static boolean contains(@Nonnull String beanName) {
if (SERVICES.isEmpty()) {
return ReflectBeanProvider.getInstance().contains(beanName);
}
for (BeanProvider provider : SERVICES) {
if (provider.contains(beanName)) {
return true;
}
}
return false;
}
@Nonnull
public static <T> T getBean(@Nonnull Class<T> beanType) {
if (SERVICES.isEmpty()) {
return ReflectBeanProvider.getInstance().getBean(beanType);
}
for (BeanProvider provider : SERVICES) {
if (provider.contains(beanType)) {
return provider.getBean(beanType);
}
}
throw new BeanException("Bean of type " + beanType.getName() + " not found.");
}
@Nonnull
public static <T> Optional<T> getBeanOptional(@Nonnull Class<T> beanType) {
return Optional.ofNullable(getBeanOrNull(beanType));
}
@Nonnull
public static <T> T getBean(@Nonnull Class<T> beanType, @Nonnull Object... args) {
if (SERVICES.isEmpty()) {
return ReflectBeanProvider.getInstance().getBean(beanType, args);
}
for (BeanProvider provider : SERVICES) {
if (provider.contains(beanType)) {
return provider.getBean(beanType, args);
}
}
throw new BeanException("Bean of type " + beanType.getName() + " not found.");
}
public static <T> T getBeanOrNull(@Nonnull Class<T> beanType) {
if (SERVICES.isEmpty()) {
return ReflectBeanProvider.getInstance().getBeanOrNull(beanType);
}
for (BeanProvider provider : SERVICES) {
if (provider.contains(beanType)) {
return provider.getBeanOrNull(beanType);
}
}
return null;
}
@Nonnull
public static <T> T getBean(@Nonnull String beanName) {
if (SERVICES.isEmpty()) {
return ReflectBeanProvider.getInstance().getBean(beanName);
}
for (BeanProvider provider : SERVICES) {
if (provider.contains(beanName)) {
return provider.getBean(beanName);
}
}
throw new BeanException("Bean of name " + beanName + " not found.");
}
@Nonnull
public static <T> Optional<T> getBeanOptional(@Nonnull String beanName) {
return Optional.ofNullable(getBeanOrNull(beanName));
}
public static <T> T getBeanOrNull(@Nonnull String beanName) {
if (SERVICES.isEmpty()) {
return ReflectBeanProvider.getInstance().getBeanOrNull(beanName);
}
for (BeanProvider provider : SERVICES) {
if (provider.contains(beanName)) {
return provider.getBeanOrNull(beanName);
}
}
return null;
}
public static <T> T getBeanOrDefault(@Nonnull Class<T> beanType, @Nonnull T defaultValue) {
final T bean = getBeanOrNull(beanType);
if (bean == null) {
return defaultValue;
}
return bean;
}
public static <T> T getBeanOrDefault(@Nonnull Class<T> beanType, @Nonnull Supplier<T> defaultValue) {
final T bean = getBeanOrNull(beanType);
if (bean == null) {
return defaultValue.get();
}
return bean;
}
@Nonnull
public static <T> T getBeanOrNew(@Nonnull Class<T> beanType, @Nonnull Object... args) {
return getBeanOrNew(beanType, ClassUtils.parameterTypes(args), args);
}
@Nonnull
@SuppressWarnings("unchecked")
public static <T> T getBeanOrNew(@Nonnull Class<T> beanType, @Nonnull Class<?>[] argTypes, @Nonnull Object[] args) {
final T bean = getBeanOrNull(beanType);
if (bean != null) {
return bean;
}
return (T) newInstance(ClassUtils.getMatchingAccessibleDeclaredConstructor(beanType, argTypes), args);
}
@Nonnull
public static <T> List<T> getBeans(@Nonnull Class<T> beanType) {
if (SERVICES.isEmpty()) {
return ReflectBeanProvider.getInstance().getBeans(beanType);
}
final List<T> list = new ArrayList<>();
for (BeanProvider provider : SERVICES) {
list.addAll(provider.getBeans(beanType));
}
return list;
}
@Nonnull
public static <T> Map<String, T> getBeanMap(@Nonnull Class<T> beanType) {
if (SERVICES.isEmpty()) {
return ReflectBeanProvider.getInstance().getBeanMap(beanType);
}
final Map<String, T> map = new HashMap<>();
for (BeanProvider provider : SERVICES) {
map.putAll(provider.getBeanMap(beanType));
}
return map;
}
@Nonnull
public static <T> Supplier<T> getBeanLazy(@Nonnull Class<T> beanType) { | return Lazy.of(() -> getBean(beanType)); | 2 | 2023-11-18 07:49:00+00:00 | 8k |
Mightinity/store-management-system | src/main/java/com/systeminventory/controller/productController.java | [
{
"identifier": "App",
"path": "src/main/java/com/systeminventory/App.java",
"snippet": "public class App extends Application {\n\n private static Stage primaryStage;\n\n public static void main(String[] args) {\n launch(args);\n }\n\n public void start(Stage stage) throws IOException... | import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.systeminventory.App;
import com.systeminventory.interfaces.DeleteProductListener;
import com.systeminventory.interfaces.DetailsProductListener;
import com.systeminventory.interfaces.EditProductListener;
import com.systeminventory.model.Product;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.*;
import java.text.NumberFormat; | 3,917 | }
private static String generateIdProduct(Random random){
StringBuilder randomString = new StringBuilder();
for (int i = 0; i < 12; i++){
char randomCharacter = randomCharacter(random);
randomString.append(randomCharacter);
}
return randomString.toString();
}
private static char randomCharacter(Random random){
String characters = "ABDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
int index = random.nextInt(characters.length());
return characters.charAt(index);
}
@FXML
private void onAddProductCancelButtonClick(ActionEvent actionEvent) {
backgroundPopup.setVisible(false);
addProductPopup.setVisible(false);
}
@FXML
private void onAddProductApplyButtonMouseEnter(MouseEvent mouseEvent) {
addProductApplyButton.setStyle("-fx-background-color: #33b8ff;" + "-fx-background-radius: 13");
}
@FXML
private void onAddProductApplyButtonMouseExit(MouseEvent mouseEvent) {
addProductApplyButton.setStyle("-fx-background-color: #00a6ff;" + "-fx-background-radius: 13");
}
@FXML
private void onAddProductCancelButtonMouseEnter(MouseEvent mouseEvent) {
addProductCancelButton.setStyle("-fx-background-color: #e0005c;" + "-fx-background-radius: 13");
}
@FXML
private void onAddProductCancelButtonMouseExit(MouseEvent mouseEvent) {
addProductCancelButton.setStyle("-fx-background-color: #ff1474;" + "-fx-background-radius: 13");
}
@FXML
private void onAddProductChooseFilePaneMouseEnter(MouseEvent mouseEvent) {
addProductChooseFilePane.setStyle("-fx-background-color: #ffa132;" + "-fx-background-radius: 5;" + "-fx-border-color: #f6f6f6;" + "-fx-border-radius: 5;");
}
@FXML
private void onAddProductChooseFilePaneMouseExit(MouseEvent mouseEvent) {
addProductChooseFilePane.setStyle("-fx-background-color: #fe8a00;" + "-fx-background-radius: 5;" + "-fx-border-color: #f6f6f6;" + "-fx-border-radius: 5;");
}
@FXML
private void onAddProductChooseFilePaneMouseClick(MouseEvent mouseEvent) {
FileChooser filechooser = new FileChooser();
filechooser.setTitle("Select product image");
filechooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("PNG Files", "*.png"));
File selectedFile = filechooser.showOpenDialog(App.getPrimaryStage());
if(selectedFile != null){
setLabelPropertiesTextFillWhite(addProductProductImageLabel, "Product image:");
addProductProductImagePathLabel.setText(selectedFile.getName());
addProductProductImageGetFullPathLabel.setText(selectedFile.getPath());
}
}
@FXML
private void onAddProductOriginalPriceKeyTyped(KeyEvent keyEvent) {
addProductOriginalPriceField.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observableValue, String oldValue, String newValue) {
if(!newValue.matches("\\d*")){
addProductOriginalPriceField.setText(newValue.replaceAll("[^\\d]", ""));
}
}
});
}
@FXML
private void onAddProductSellingPriceKeyTyped(KeyEvent keyEvent) {
addProductSellingPriceField.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observableValue, String oldValue, String newValue) {
if(!newValue.matches("\\d*")){
addProductSellingPriceField.setText(newValue.replaceAll("[^\\d]", ""));
}
}
});
}
@FXML
private void onAddProductProductStockKeyTyped(KeyEvent keyEvent) {
addProductProductStockField.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observableValue, String oldValue, String newValue) {
if(!newValue.matches("\\d*")){
addProductProductStockField.setText(newValue.replaceAll("[^\\d]", ""));
}
}
});
}
@FXML
private void onButtonAddProductClick(ActionEvent actionEvent) throws IOException {
addProductLabel.setText("Add Product");
addProductProductNameField.setText("");
addProductOriginalPriceField.setText("");
addProductSellingPriceField.setText("");
addProductProductImagePathLabel.setText("");
addProductProductStockField.setText("");
setLabelPropertiesTextFillWhite(addProductProductNameLabel, "Product name:");
setLabelPropertiesTextFillWhite(addProductOriginalPriceLabel, "Original price:");
setLabelPropertiesTextFillWhite(addProductSellingPriceLabel, "Selling price:");
setLabelPropertiesTextFillWhite(addProductProductImageLabel, "Product image:");
setLabelPropertiesTextFillWhite(addProductProductStockLabel, "Product stock:");
backgroundPopup.setVisible(true);
addProductPopup.setVisible(true);
}
| package com.systeminventory.controller;
public class productController {
@FXML
public Pane filterDropdown;
@FXML
public Button filterButton;
public ImageView imageFIlter;
@FXML
private Pane profileDropdown;
@FXML
private Button settingsDropdown;
@FXML
private Button buttonCashier;
@FXML
private Button buttonProduct;
@FXML
private Button logoutDropdown;
@FXML
private Button buttonDashboard;
@FXML
private ScrollPane scrollPane;
@FXML
private Button buttonAddProduct;
@FXML
public Pane backgroundPopup;
@FXML
private Pane addProductPopup;
@FXML
private Button addProductApplyButton;
@FXML
private Button addProductCancelButton;
@FXML
private TextField addProductProductNameField;
@FXML
private TextField addProductOriginalPriceField;
@FXML
private TextField addProductSellingPriceField;
@FXML
private TextField addProductProductStockField;
@FXML
private Label addProductProductImagePathLabel;
@FXML
private Pane addProductChooseFilePane;
@FXML
private Label addProductProductImageLabel;
@FXML
private Label addProductSellingPriceLabel;
@FXML
private Label addProductOriginalPriceLabel;
@FXML
private Label addProductProductNameLabel;
@FXML
private Label addProductProductStockLabel;
@FXML
private GridPane productCardContainer;
@FXML
private Label addProductProductImageGetFullPathLabel;
@FXML
private TextField searchProductNameField;
@FXML
private Label confirmDeleteVariableProductName;
@FXML
private Button confirmDeleteDeleteButton;
@FXML
private Button confirmDeleteCancelButton;
@FXML
private Label confirmDeleteKeyProduct;
@FXML
public Pane confirmDeletePane;
@FXML
private Label addProductLabel;
@FXML
private Label keyProductOnPopUp;
@FXML
private Pane detailsProductPopup;
@FXML
private Label varProductNameDetailsProduct;
@FXML
private Label varOriginalPriceDetailsProduct;
@FXML
private Label varSellingPriceDetailsProduct;
@FXML
private Label varProductStockDetailsProduct;
@FXML
private ImageView barcodeImageDetailsProduct;
private DeleteProductListener deleteProductListener;
private EditProductListener editProductListener;
private DetailsProductListener detailsProductListener;
@FXML
private Button downloadBarcodeDetailsProduct;
@FXML
private Button cancelButtonDetailsProduct;
@FXML
private Label idProductDetailsProduct;
@FXML
private Pane downloadAlertPopup;
@FXML
private Label varStatusDownload;
@FXML
private Button okButtonStatusDownloadPopup;
@FXML
private Label confirmDeleteKeyProduct1;
@FXML
private Pane backgroundPopupDownload;
@FXML
void onButtonCashierClick(ActionEvent event) throws IOException {
App.loadCashierScene();
}
@FXML
void onButtonDashboardClick(ActionEvent event) throws IOException {
App.loadDashboardScene();
}
@FXML
void onButtonProductClick(ActionEvent event) throws IOException {
}
@FXML
void onLogoutClick(ActionEvent event) throws IOException {
App.loadLogoutScene();
}
@FXML
void onProfileClick(MouseEvent event) {
profileDropdown.setVisible(!profileDropdown.isVisible());
}
@FXML
void onLogoutDropdownMouseEnter(MouseEvent event) {
logoutDropdown.setStyle("-fx-background-color: #2f3d4e;" + "-fx-background-radius: 11");
}
@FXML
void onLogoutDropdownMouseExit(MouseEvent event) {
logoutDropdown.setStyle("-fx-background-color: #1c242e;" + "-fx-background-radius: 11");
}
@FXML
void onSettingsDropdownMouseEnter(MouseEvent event) {
settingsDropdown.setStyle("-fx-background-color: #2f3d4e;" + "-fx-background-radius: 11");
}
@FXML
void onSettingsDropdownMouseExit(MouseEvent event) {
settingsDropdown.setStyle("-fx-background-color: #1c242e;" + "-fx-background-radius: 11");
}
@FXML
private void onButtonProductMouseEnter(MouseEvent mouseEvent) {
}
@FXML
private void onButtonProductMouseExit(MouseEvent mouseEvent) {
}
@FXML
private void onCashierProductMouseEnter(MouseEvent mouseEvent) {
buttonCashier.setStyle("-fx-background-color: #697b7b;" + "-fx-border-color: #697b7b;" + "-fx-text-fill: #151d26;" + "-fx-background-radius: 20;" + "-fx-border-radius: 20;");
}
@FXML
private void onCashierProductMouseExit(MouseEvent mouseEvent) {
buttonCashier.setStyle("-fx-background-color: #151d26;" + "-fx-border-color: #697b7b;" + "-fx-text-fill: #697b7b;" + "-fx-background-radius: 20;" + "-fx-border-radius: 20;");
}
@FXML
private void onProfileDropdownMouseExit(MouseEvent mouseEvent) {
profileDropdown.setVisible(false);
}
@FXML
private void onButtonDashboardMouseEnter(MouseEvent mouseEvent) {
buttonDashboard.setStyle("-fx-background-color: #697b7b;" + "-fx-border-color: #697b7b;" + "-fx-text-fill: #151d26;" + "-fx-background-radius: 20;" + "-fx-border-radius: 20;");
}
@FXML
private void onButtonDashboardMouseExit(MouseEvent mouseEvent) {
buttonDashboard.setStyle("-fx-background-color: #151d26;" + "-fx-border-color: #697b7b;" + "-fx-text-fill: #697b7b;" + "-fx-background-radius: 20;" + "-fx-border-radius: 20;");
}
public void onFilterButtonClick(ActionEvent actionEvent) {
filterDropdown.setVisible(!filterDropdown.isVisible());
}
@FXML
public void onFilterButtonMouseEnter(MouseEvent mouseEvent) {
filterButton.setStyle("-fx-background-color: #ffa132;" + "-fx-background-radius: 20;");
}
@FXML
public void onFilterButtonMouseExit(MouseEvent mouseEvent) {
filterButton.setStyle("-fx-background-color: #fe8a00;" + "-fx-background-radius: 20;");
}
@FXML
public void onImageFilterMouseEnter(MouseEvent mouseEvent) {
filterButton.setStyle("-fx-background-color: #ffa132;" + "-fx-background-radius: 20;");
}
@FXML
public void onFilterDropdownMouseExit(MouseEvent mouseEvent) {
filterDropdown.setVisible(false);
}
@FXML
private void onImageFilterMouseClick(MouseEvent mouseEvent) {
filterDropdown.setVisible(!filterDropdown.isVisible());
}
@FXML
private void onButtonAddProductMouseExit(MouseEvent mouseEvent) {
buttonAddProduct.setStyle("-fx-background-color: #fe8a00;" + "-fx-background-radius: 20;");
}
@FXML
private void onButtonAddProductMouseEnter(MouseEvent mouseEvent) {
buttonAddProduct.setStyle("-fx-background-color: #ffa132;" + "-fx-background-radius: 20;");
}
private void setLabelPropertiesTextFillWhite(Label label, String text){
label.setText(text);
label.setStyle("-fx-text-fill: #f6f6f6;");
}
@FXML
private void onAddProductApplyButtonClick(ActionEvent actionEvent) throws IOException {
String jsonPath = "./src/main/java/com/systeminventory/assets/json/productList.json";
String imageProductPath = "./src/main/java/com/systeminventory/assets/imagesProduct/";
setLabelPropertiesTextFillWhite(addProductProductNameLabel, "Product name:");
setLabelPropertiesTextFillWhite(addProductOriginalPriceLabel, "Original price:");
setLabelPropertiesTextFillWhite(addProductSellingPriceLabel, "Selling price:");
setLabelPropertiesTextFillWhite(addProductProductImageLabel, "Product image:");
setLabelPropertiesTextFillWhite(addProductProductStockLabel, "Product stock:");
TextField[] fields = { addProductProductNameField, addProductOriginalPriceField, addProductSellingPriceField, addProductProductStockField };
Label[] labels = { addProductProductNameLabel, addProductOriginalPriceLabel, addProductSellingPriceLabel, addProductProductStockLabel };
if (addProductLabel.getText().equals("Add Product")){
int status = 0;
for (int i = 0; i < fields.length;i++){
TextField field = fields[i];
Label label = labels[i];
if(field.getText().isEmpty()){
label.setText(label.getText()+" (Required)");
label.setStyle("-fx-text-fill: #ff1474;");
status++;
}
}
if (addProductProductImagePathLabel.getText().isEmpty()){
addProductProductImageLabel.setText("Product image: (Required)");
addProductProductImageLabel.setStyle("-fx-text-fill: #ff1474;");
status++;
}
if (status == 0){
Gson gson = new GsonBuilder().setPrettyPrinting().create();
Random random = new Random();
try (InputStream inputStream = new FileInputStream(jsonPath)){
InputStreamReader reader = new InputStreamReader(inputStream);
JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);
List<String> productKeys = new ArrayList<>(jsonObject.keySet());
//Collections.sort(productKeys);
int nextKeyNumber = productKeys.size()+1;
String newProductKey = "product"+nextKeyNumber;
while (productKeys.contains(newProductKey)){
nextKeyNumber++;
newProductKey = "product"+nextKeyNumber;
}
JsonObject newProductData = new JsonObject();
int originalPrice = Integer.parseInt(addProductOriginalPriceField.getText());
int sellingPrice = Integer.parseInt(addProductSellingPriceField.getText());
int stock = Integer.parseInt(addProductProductStockField.getText());
String imageFileName = addProductProductImagePathLabel.getText();
Path sourceImagePath = Paths.get(addProductProductImageGetFullPathLabel.getText());
Path targetImagePath = Paths.get(imageProductPath, imageFileName);
newProductData.addProperty("idProduct", generateIdProduct(random));
newProductData.addProperty("Title", addProductProductNameField.getText());
newProductData.addProperty("OriginalPrice", originalPrice);
newProductData.addProperty("SellingPrice", sellingPrice);
newProductData.addProperty("Image", imageProductPath+imageFileName);
newProductData.addProperty("Stock", stock);
try{
Files.copy(sourceImagePath, targetImagePath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException err){
err.printStackTrace();
}
jsonObject.add(newProductKey, newProductData);
try (Writer writer = new FileWriter(jsonPath)){
gson.toJson(jsonObject, writer);
}
} catch (IOException err){
err.printStackTrace();
}
App.loadProductScene();
}
} else if (addProductLabel.getText().equals("Edit Product")) {
int status = 0;
for (int i = 0; i < fields.length; i++) {
TextField field = fields[i];
Label label = labels[i];
if (field.getText().isEmpty()) {
label.setText(label.getText() + " (Required)");
label.setStyle("-fx-text-fill: #ff1474;");
status++;
}
}
if (addProductProductImagePathLabel.getText().isEmpty()) {
addProductProductImageLabel.setText("Product image: (Required)");
addProductProductImageLabel.setStyle("-fx-text-fill: #ff1474;");
status++;
}
if (status == 0) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
try (InputStream inputStream = new FileInputStream(jsonPath)) {
InputStreamReader reader = new InputStreamReader(inputStream);
JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);
JsonObject productKey = jsonObject.getAsJsonObject(keyProductOnPopUp.getText());
if (keyProductOnPopUp.getText() != null) {
int originalPrice = Integer.parseInt(addProductOriginalPriceField.getText());
int sellingPrice = Integer.parseInt(addProductSellingPriceField.getText());
int stock = Integer.parseInt(addProductProductStockField.getText());
String imageFileName = addProductProductImagePathLabel.getText();
if (!(imageProductPath + imageFileName).equals(productKey.get("Image").getAsString())) {
Path newSourceImagePath = Paths.get(addProductProductImageGetFullPathLabel.getText());
Path targetImagePath = Paths.get(imageProductPath, imageFileName);
try {
Files.copy(newSourceImagePath, targetImagePath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException err) {
err.printStackTrace();
}
}
productKey.addProperty("Title", addProductProductNameField.getText());
productKey.addProperty("OriginalPrice", originalPrice);
productKey.addProperty("SellingPrice", sellingPrice);
productKey.addProperty("Image", imageProductPath + imageFileName);
productKey.addProperty("Stock", stock);
try (Writer writer = new FileWriter(jsonPath)) {
gson.toJson(jsonObject, writer);
}
}
} catch (IOException err) {
err.printStackTrace();
}
}
App.loadProductScene();
}
}
private static String generateIdProduct(Random random){
StringBuilder randomString = new StringBuilder();
for (int i = 0; i < 12; i++){
char randomCharacter = randomCharacter(random);
randomString.append(randomCharacter);
}
return randomString.toString();
}
private static char randomCharacter(Random random){
String characters = "ABDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
int index = random.nextInt(characters.length());
return characters.charAt(index);
}
@FXML
private void onAddProductCancelButtonClick(ActionEvent actionEvent) {
backgroundPopup.setVisible(false);
addProductPopup.setVisible(false);
}
@FXML
private void onAddProductApplyButtonMouseEnter(MouseEvent mouseEvent) {
addProductApplyButton.setStyle("-fx-background-color: #33b8ff;" + "-fx-background-radius: 13");
}
@FXML
private void onAddProductApplyButtonMouseExit(MouseEvent mouseEvent) {
addProductApplyButton.setStyle("-fx-background-color: #00a6ff;" + "-fx-background-radius: 13");
}
@FXML
private void onAddProductCancelButtonMouseEnter(MouseEvent mouseEvent) {
addProductCancelButton.setStyle("-fx-background-color: #e0005c;" + "-fx-background-radius: 13");
}
@FXML
private void onAddProductCancelButtonMouseExit(MouseEvent mouseEvent) {
addProductCancelButton.setStyle("-fx-background-color: #ff1474;" + "-fx-background-radius: 13");
}
@FXML
private void onAddProductChooseFilePaneMouseEnter(MouseEvent mouseEvent) {
addProductChooseFilePane.setStyle("-fx-background-color: #ffa132;" + "-fx-background-radius: 5;" + "-fx-border-color: #f6f6f6;" + "-fx-border-radius: 5;");
}
@FXML
private void onAddProductChooseFilePaneMouseExit(MouseEvent mouseEvent) {
addProductChooseFilePane.setStyle("-fx-background-color: #fe8a00;" + "-fx-background-radius: 5;" + "-fx-border-color: #f6f6f6;" + "-fx-border-radius: 5;");
}
@FXML
private void onAddProductChooseFilePaneMouseClick(MouseEvent mouseEvent) {
FileChooser filechooser = new FileChooser();
filechooser.setTitle("Select product image");
filechooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("PNG Files", "*.png"));
File selectedFile = filechooser.showOpenDialog(App.getPrimaryStage());
if(selectedFile != null){
setLabelPropertiesTextFillWhite(addProductProductImageLabel, "Product image:");
addProductProductImagePathLabel.setText(selectedFile.getName());
addProductProductImageGetFullPathLabel.setText(selectedFile.getPath());
}
}
@FXML
private void onAddProductOriginalPriceKeyTyped(KeyEvent keyEvent) {
addProductOriginalPriceField.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observableValue, String oldValue, String newValue) {
if(!newValue.matches("\\d*")){
addProductOriginalPriceField.setText(newValue.replaceAll("[^\\d]", ""));
}
}
});
}
@FXML
private void onAddProductSellingPriceKeyTyped(KeyEvent keyEvent) {
addProductSellingPriceField.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observableValue, String oldValue, String newValue) {
if(!newValue.matches("\\d*")){
addProductSellingPriceField.setText(newValue.replaceAll("[^\\d]", ""));
}
}
});
}
@FXML
private void onAddProductProductStockKeyTyped(KeyEvent keyEvent) {
addProductProductStockField.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observableValue, String oldValue, String newValue) {
if(!newValue.matches("\\d*")){
addProductProductStockField.setText(newValue.replaceAll("[^\\d]", ""));
}
}
});
}
@FXML
private void onButtonAddProductClick(ActionEvent actionEvent) throws IOException {
addProductLabel.setText("Add Product");
addProductProductNameField.setText("");
addProductOriginalPriceField.setText("");
addProductSellingPriceField.setText("");
addProductProductImagePathLabel.setText("");
addProductProductStockField.setText("");
setLabelPropertiesTextFillWhite(addProductProductNameLabel, "Product name:");
setLabelPropertiesTextFillWhite(addProductOriginalPriceLabel, "Original price:");
setLabelPropertiesTextFillWhite(addProductSellingPriceLabel, "Selling price:");
setLabelPropertiesTextFillWhite(addProductProductImageLabel, "Product image:");
setLabelPropertiesTextFillWhite(addProductProductStockLabel, "Product stock:");
backgroundPopup.setVisible(true);
addProductPopup.setVisible(true);
}
| private List<Product> readProductsFromJson(String searchTerm) { | 4 | 2023-11-18 02:53:02+00:00 | 8k |
CivilisationPlot/CivilisationPlot_Papermc | src/main/java/fr/laptoff/civilisationplot/civils/Civil.java | [
{
"identifier": "CivilisationPlot",
"path": "src/main/java/fr/laptoff/civilisationplot/CivilisationPlot.java",
"snippet": "public final class CivilisationPlot extends JavaPlugin {\n\n public static final Logger LOGGER = Logger.getLogger(\"CivilisationPlot\");\n private static CivilisationPlot inst... | import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import fr.laptoff.civilisationplot.CivilisationPlot;
import fr.laptoff.civilisationplot.Managers.DatabaseManager;
import fr.laptoff.civilisationplot.Managers.FileManager;
import fr.laptoff.civilisationplot.nation.Nation;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID; | 4,077 | package fr.laptoff.civilisationplot.civils;
public class Civil {
private String PlayerName;
private float Money;
private UUID Nation; | package fr.laptoff.civilisationplot.civils;
public class Civil {
private String PlayerName;
private float Money;
private UUID Nation; | private static final Connection co = CivilisationPlot.getInstance().getDatabase().getConnection(); | 0 | 2023-11-11 18:26:55+00:00 | 8k |
JohnTWD/meteor-rejects-vanillacpvp | src/main/java/anticope/rejects/modules/FullFlight.java | [
{
"identifier": "MeteorRejectsAddon",
"path": "src/main/java/anticope/rejects/MeteorRejectsAddon.java",
"snippet": "public class MeteorRejectsAddon extends MeteorAddon {\n public static final Logger LOG = LoggerFactory.getLogger(\"Rejects\");\n public static final Category CATEGORY = new Category(... | import anticope.rejects.MeteorRejectsAddon;
import anticope.rejects.utils.RejectsUtils;
import com.google.common.collect.Streams;
import meteordevelopment.meteorclient.events.entity.player.PlayerMoveEvent;
import meteordevelopment.meteorclient.events.packets.PacketEvent;
import meteordevelopment.meteorclient.mixin.ClientPlayerEntityAccessor;
import meteordevelopment.meteorclient.mixin.PlayerMoveC2SPacketAccessor;
import meteordevelopment.meteorclient.settings.*;
import meteordevelopment.meteorclient.systems.modules.Module;
import meteordevelopment.orbit.EventHandler;
import net.minecraft.block.AbstractBlock;
import net.minecraft.entity.Entity;
import net.minecraft.network.packet.c2s.play.PlayerMoveC2SPacket;
import net.minecraft.util.math.Box;
import net.minecraft.util.shape.VoxelShape;
import java.util.stream.Stream; | 3,746 |
// Copied from ServerPlayNetworkHandler#isEntityOnAir
private boolean isEntityOnAir(Entity entity) {
return entity.getWorld().getStatesInBox(entity.getBoundingBox().expand(0.0625).stretch(0.0, -0.55, 0.0)).allMatch(AbstractBlock.AbstractBlockState::isAir);
}
private int delayLeft = 20;
private double lastPacketY = Double.MAX_VALUE;
private boolean shouldFlyDown(double currentY, double lastY) {
if (currentY >= lastY) {
return true;
} else return lastY - currentY < 0.03130D;
}
private void antiKickPacket(PlayerMoveC2SPacket packet, double currentY) {
// maximum time we can be "floating" is 80 ticks, so 4 seconds max
if (this.delayLeft <= 0 && this.lastPacketY != Double.MAX_VALUE &&
shouldFlyDown(currentY, this.lastPacketY) && isEntityOnAir(mc.player)) {
// actual check is for >= -0.03125D, but we have to do a bit more than that
// due to the fact that it's a bigger or *equal* to, and not just a bigger than
((PlayerMoveC2SPacketAccessor) packet).setY(lastPacketY - 0.03130D);
lastPacketY -= 0.03130D;
delayLeft = 20;
} else {
lastPacketY = currentY;
if (!isEntityOnAir(mc.player))
delayLeft = 20;
}
if (delayLeft > 0) delayLeft--;
}
@EventHandler
private void onSendPacket(PacketEvent.Send event) {
if (mc.player.getVehicle() == null || !(event.packet instanceof PlayerMoveC2SPacket packet) || antiKickMode.get() != AntiKickMode.PaperNew)
return;
double currentY = packet.getY(Double.MAX_VALUE);
if (currentY != Double.MAX_VALUE) {
antiKickPacket(packet, currentY);
} else {
// if the packet is a LookAndOnGround packet or an OnGroundOnly packet then we need to
// make it a Full packet or a PositionAndOnGround packet respectively, so it has a Y value
PlayerMoveC2SPacket fullPacket;
if (packet.changesLook()) {
fullPacket = new PlayerMoveC2SPacket.Full(
mc.player.getX(),
mc.player.getY(),
mc.player.getZ(),
packet.getYaw(0),
packet.getPitch(0),
packet.isOnGround()
);
} else {
fullPacket = new PlayerMoveC2SPacket.PositionAndOnGround(
mc.player.getX(),
mc.player.getY(),
mc.player.getZ(),
packet.isOnGround()
);
}
event.cancel();
antiKickPacket(fullPacket, mc.player.getY());
mc.getNetworkHandler().sendPacket(fullPacket);
}
}
private int floatingTicks = 0;
@EventHandler
private void onPlayerMove(PlayerMoveEvent event) {
if (antiKickMode.get() == AntiKickMode.PaperNew) {
// Resend movement packets
((ClientPlayerEntityAccessor) mc.player).setTicksSinceLastPositionPacketSent(20);
}
if (floatingTicks >= 20) {
switch (antiKickMode.get()) {
case New -> {
Box box = mc.player.getBoundingBox();
Box adjustedBox = box.offset(0, -0.4, 0);
Stream<VoxelShape> blockCollisions = Streams.stream(mc.world.getBlockCollisions(mc.player, adjustedBox));
if (blockCollisions.findAny().isPresent()) break;
mc.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(mc.player.getX(), mc.player.getY() - 0.4, mc.player.getZ(), mc.player.isOnGround()));
mc.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(mc.player.getX(), mc.player.getY(), mc.player.getZ(), mc.player.isOnGround()));
}
case Old -> {
Box box = mc.player.getBoundingBox();
Box adjustedBox = box.offset(0, -0.4, 0);
Stream<VoxelShape> blockCollisions = Streams.stream(mc.world.getBlockCollisions(mc.player, adjustedBox));
if (blockCollisions.findAny().isPresent()) break;
double ground = calculateGround();
double groundExtra = ground + 0.1D;
for (double posY = mc.player.getY(); posY > groundExtra; posY -= 4D) {
mc.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(mc.player.getX(), posY, mc.player.getZ(), true));
if (posY - 4D < groundExtra) break; // Prevent next step
}
mc.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(mc.player.getX(), groundExtra, mc.player.getZ(), true));
for (double posY = groundExtra; posY < mc.player.getY(); posY += 4D) {
mc.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(mc.player.getX(), posY, mc.player.getZ(), mc.player.isOnGround()));
if (posY + 4D > mc.player.getY()) break; // Prevent next step
}
mc.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(mc.player.getX(), mc.player.getY(), mc.player.getZ(), mc.player.isOnGround()));
}
}
floatingTicks = 0;
}
| package anticope.rejects.modules;
public class FullFlight extends Module {
private final SettingGroup sgGeneral = settings.getDefaultGroup();
private final SettingGroup sgAntiKick = settings.createGroup("Anti Kick");
private final Setting<Double> speed = sgGeneral.add(new DoubleSetting.Builder()
.name("speed")
.description("Your speed when flying.")
.defaultValue(0.3)
.min(0.0)
.sliderMax(10)
.build()
);
private final Setting<Boolean> verticalSpeedMatch = sgGeneral.add(new BoolSetting.Builder()
.name("vertical-speed-match")
.description("Matches your vertical speed to your horizontal speed, otherwise uses vanilla ratio.")
.defaultValue(false)
.build()
);
private final Setting<AntiKickMode> antiKickMode = sgAntiKick.add(new EnumSetting.Builder<AntiKickMode>()
.name("mode")
.description("The mode for anti kick.")
.defaultValue(AntiKickMode.PaperNew)
.build()
);
public FullFlight() {
super(MeteorRejectsAddon.CATEGORY, "fullflight", "FullFlight.");
}
private double calculateGround() {
for (double ground = mc.player.getY(); ground > 0D; ground -= 0.05) {
Box box = mc.player.getBoundingBox();
Box adjustedBox = box.offset(0, ground - mc.player.getY(), 0);
Stream<VoxelShape> blockCollisions = Streams.stream(mc.world.getBlockCollisions(mc.player, adjustedBox));
if (blockCollisions.findAny().isPresent()) return ground + 0.05;
}
return 0F;
}
// Copied from ServerPlayNetworkHandler#isEntityOnAir
private boolean isEntityOnAir(Entity entity) {
return entity.getWorld().getStatesInBox(entity.getBoundingBox().expand(0.0625).stretch(0.0, -0.55, 0.0)).allMatch(AbstractBlock.AbstractBlockState::isAir);
}
private int delayLeft = 20;
private double lastPacketY = Double.MAX_VALUE;
private boolean shouldFlyDown(double currentY, double lastY) {
if (currentY >= lastY) {
return true;
} else return lastY - currentY < 0.03130D;
}
private void antiKickPacket(PlayerMoveC2SPacket packet, double currentY) {
// maximum time we can be "floating" is 80 ticks, so 4 seconds max
if (this.delayLeft <= 0 && this.lastPacketY != Double.MAX_VALUE &&
shouldFlyDown(currentY, this.lastPacketY) && isEntityOnAir(mc.player)) {
// actual check is for >= -0.03125D, but we have to do a bit more than that
// due to the fact that it's a bigger or *equal* to, and not just a bigger than
((PlayerMoveC2SPacketAccessor) packet).setY(lastPacketY - 0.03130D);
lastPacketY -= 0.03130D;
delayLeft = 20;
} else {
lastPacketY = currentY;
if (!isEntityOnAir(mc.player))
delayLeft = 20;
}
if (delayLeft > 0) delayLeft--;
}
@EventHandler
private void onSendPacket(PacketEvent.Send event) {
if (mc.player.getVehicle() == null || !(event.packet instanceof PlayerMoveC2SPacket packet) || antiKickMode.get() != AntiKickMode.PaperNew)
return;
double currentY = packet.getY(Double.MAX_VALUE);
if (currentY != Double.MAX_VALUE) {
antiKickPacket(packet, currentY);
} else {
// if the packet is a LookAndOnGround packet or an OnGroundOnly packet then we need to
// make it a Full packet or a PositionAndOnGround packet respectively, so it has a Y value
PlayerMoveC2SPacket fullPacket;
if (packet.changesLook()) {
fullPacket = new PlayerMoveC2SPacket.Full(
mc.player.getX(),
mc.player.getY(),
mc.player.getZ(),
packet.getYaw(0),
packet.getPitch(0),
packet.isOnGround()
);
} else {
fullPacket = new PlayerMoveC2SPacket.PositionAndOnGround(
mc.player.getX(),
mc.player.getY(),
mc.player.getZ(),
packet.isOnGround()
);
}
event.cancel();
antiKickPacket(fullPacket, mc.player.getY());
mc.getNetworkHandler().sendPacket(fullPacket);
}
}
private int floatingTicks = 0;
@EventHandler
private void onPlayerMove(PlayerMoveEvent event) {
if (antiKickMode.get() == AntiKickMode.PaperNew) {
// Resend movement packets
((ClientPlayerEntityAccessor) mc.player).setTicksSinceLastPositionPacketSent(20);
}
if (floatingTicks >= 20) {
switch (antiKickMode.get()) {
case New -> {
Box box = mc.player.getBoundingBox();
Box adjustedBox = box.offset(0, -0.4, 0);
Stream<VoxelShape> blockCollisions = Streams.stream(mc.world.getBlockCollisions(mc.player, adjustedBox));
if (blockCollisions.findAny().isPresent()) break;
mc.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(mc.player.getX(), mc.player.getY() - 0.4, mc.player.getZ(), mc.player.isOnGround()));
mc.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(mc.player.getX(), mc.player.getY(), mc.player.getZ(), mc.player.isOnGround()));
}
case Old -> {
Box box = mc.player.getBoundingBox();
Box adjustedBox = box.offset(0, -0.4, 0);
Stream<VoxelShape> blockCollisions = Streams.stream(mc.world.getBlockCollisions(mc.player, adjustedBox));
if (blockCollisions.findAny().isPresent()) break;
double ground = calculateGround();
double groundExtra = ground + 0.1D;
for (double posY = mc.player.getY(); posY > groundExtra; posY -= 4D) {
mc.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(mc.player.getX(), posY, mc.player.getZ(), true));
if (posY - 4D < groundExtra) break; // Prevent next step
}
mc.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(mc.player.getX(), groundExtra, mc.player.getZ(), true));
for (double posY = groundExtra; posY < mc.player.getY(); posY += 4D) {
mc.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(mc.player.getX(), posY, mc.player.getZ(), mc.player.isOnGround()));
if (posY + 4D > mc.player.getY()) break; // Prevent next step
}
mc.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(mc.player.getX(), mc.player.getY(), mc.player.getZ(), mc.player.isOnGround()));
}
}
floatingTicks = 0;
}
| float ySpeed = RejectsUtils.fullFlightMove(event, speed.get(), verticalSpeedMatch.get()); | 1 | 2023-11-13 08:11:28+00:00 | 8k |
stiemannkj1/java-utilities | src/test/java/dev/stiemannkj1/collection/fixmapping/FixMappingsTests.java | [
{
"identifier": "binarySearchArrayPrefixMapping",
"path": "src/main/java/dev/stiemannkj1/collection/fixmapping/FixMappings.java",
"snippet": "public static <T> ImmutablePrefixMapping<T> binarySearchArrayPrefixMapping(\n final Map<String, T> prefixes) {\n return new BinarySearchArrayPrefixMapping<>(p... | import static dev.stiemannkj1.collection.fixmapping.FixMappings.binarySearchArrayPrefixMapping;
import static dev.stiemannkj1.collection.fixmapping.FixMappings.binarySearchArraySuffixMapping;
import static dev.stiemannkj1.collection.fixmapping.FixMappings.limitedCharArrayTriePrefixMapping;
import static dev.stiemannkj1.collection.fixmapping.FixMappings.limitedCharArrayTrieSuffixMapping;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import dev.stiemannkj1.collection.fixmapping.FixMappings.ImmutablePrefixMapping;
import dev.stiemannkj1.collection.fixmapping.FixMappings.ImmutableSuffixMapping;
import dev.stiemannkj1.util.Pair;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource; | 3,902 | return Stream.of(
Collections.emptyMap(),
newTestMapBuilder().add(null, 1).map,
newTestMapBuilder().add(null, 1).add("asdf", 1).map,
newTestMapBuilder().add("", 1).map,
newTestMapBuilder().add("", 1).add("asdf", 1).map,
// Invalid map with duplicate keys:
toMap(Arrays.asList(Pair.of("asdf", 1), Pair.of("asdf", 1))),
// Invalid map with null entry:
toMap(Arrays.asList(null, Pair.of("asdf", 1))));
}
@MethodSource("invalidSuffixes")
@ParameterizedTest
default void throws_illegal_arg_when_provided_invalid_values(
final Map<String, Integer> suffixes) {
final Class<? extends Exception> expectedExceptionType =
suffixes != null ? IllegalArgumentException.class : NullPointerException.class;
assertThrows(expectedExceptionType, () -> newSuffixMap(suffixes));
}
ImmutableSuffixMapping<Integer> newSuffixMap(final Map<String, Integer> prefixes);
}
private static void assertFirstMatchSearchTakesLessSteps(
String string, Integer expectedValue, FixMappings.FixMapping<Integer> fixMapping) {
final AtomicLong firstSearchSteps = new AtomicLong(0);
final AtomicLong longestSearchSteps = new AtomicLong(0);
final Pair<String, Integer> firstMatch =
fixMapping.getKeyAndValue(false, string, firstSearchSteps);
if (expectedValue != null) {
assertNotNull(firstMatch);
} else {
assertNull(firstMatch);
}
final Pair<String, Integer> longestMatch =
fixMapping.getKeyAndValue(true, string, longestSearchSteps);
if (expectedValue != null) {
assertNotNull(longestMatch);
} else {
assertNull(longestMatch);
}
assertTrue(firstSearchSteps.get() <= longestSearchSteps.get());
}
static final class BinarySearchArrayPrefixMapTests implements PrefixMappersTests {
@Override
public ImmutablePrefixMapping<Integer> newPrefixMap(final Map<String, Integer> prefixes) {
return binarySearchArrayPrefixMapping(prefixes);
}
@CsvSource(
value = {
"abdicate,abd,abdicate,3,11,8,8",
"abdicated,abd,abdicate,3,14,8,11",
})
@ParameterizedTest
@Override
public void detects_prefixes_with_minimal_steps(
final String string,
final String firstMatchEvenKeys,
final String firstMatchOddKeys,
final int firstMatchStepsEvenKeys,
final int longestMatchStepsEvenKeys,
final int firstMatchStepsOddKeys,
final int longestMatchStepsOddKeys) {
PrefixMappersTests.super.detects_prefixes_with_minimal_steps(
string,
firstMatchEvenKeys,
firstMatchOddKeys,
firstMatchStepsEvenKeys,
longestMatchStepsEvenKeys,
firstMatchStepsOddKeys,
longestMatchStepsOddKeys);
}
}
static final class BinarySearchArraySuffixMapTests implements SuffixMappersTests {
@Override
public ImmutableSuffixMapping<Integer> newSuffixMap(final Map<String, Integer> suffixes) {
return binarySearchArraySuffixMapping(suffixes);
}
@CsvSource(
value = {
"abdicate,abdicate,ate,8,8,5,13",
"i abdicate,abdicate,ate,8,10,5,13",
})
@ParameterizedTest
@Override
public void detects_suffixes_with_minimal_steps(
final String string,
final String firstMatchEvenKeys,
final String firstMatchOddKeys,
final int firstMatchStepsEvenKeys,
final int longestMatchStepsEvenKeys,
final int firstMatchStepsOddKeys,
final int longestMatchStepsOddKeys) {
SuffixMappersTests.super.detects_suffixes_with_minimal_steps(
string,
firstMatchEvenKeys,
firstMatchOddKeys,
firstMatchStepsEvenKeys,
longestMatchStepsEvenKeys,
firstMatchStepsOddKeys,
longestMatchStepsOddKeys);
}
}
static final class LimitedCharArrayTriePrefixMapTests implements PrefixMappersTests {
@Override
public ImmutablePrefixMapping<Integer> newPrefixMap(final Map<String, Integer> prefixes) { | /*
Copyright 2023 Kyle J. Stiemann
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 dev.stiemannkj1.collection.fixmapping;
final class FixMappingsTests {
// TODO test unicode
interface PrefixMappersTests {
@CsvSource(
value = {
"null,false,null",
",false,null",
"123456,false,null",
"~~~~~~,false,null",
"a,false,null",
"ab,false,null",
"abc,true,0",
"abe,true,1",
"abd,true,2",
"aba,false,null",
"abd,true,2",
"abdi,true,2",
"abdic,true,2",
"abdica,true,2",
"abdicat,true,2",
"abdicat,true,2",
"abdicate,true,3",
"abdicated,true,3",
"x,false,null",
"xy,false,null"
},
nullValues = "null")
@ParameterizedTest
@SuppressWarnings("unchecked")
default void detects_prefixes(
final String string, final boolean expectPrefixed, final Integer expectedValue) {
// Test odd number of prefixes.
final Map<String, Integer> prefixes =
newTestMapBuilder().add("abc", 0).add("abe", 1).add("abd", 2).add("abdicate", 3).map;
ImmutablePrefixMapping<Integer> prefixMap = newPrefixMap(prefixes);
assertEquals(expectPrefixed, prefixMap.matchesAnyPrefix(string));
assertEquals(expectedValue, prefixMap.valueForPrefix(string));
assertEquals(
getKeyAndValueByValue(prefixes, expectedValue), prefixMap.keyAndValueForPrefix(string));
assertFirstMatchSearchTakesLessSteps(
string, expectedValue, (FixMappings.FixMapping<Integer>) prefixMap);
// Test odd number of prefixes.
prefixes.put("xyz", 4);
prefixMap = newPrefixMap(prefixes);
assertEquals(expectPrefixed, prefixMap.matchesAnyPrefix(string));
assertEquals(expectedValue, prefixMap.valueForPrefix(string));
assertEquals(
getKeyAndValueByValue(prefixes, expectedValue), prefixMap.keyAndValueForPrefix(string));
assertFirstMatchSearchTakesLessSteps(
string, expectedValue, (FixMappings.FixMapping<Integer>) prefixMap);
}
@SuppressWarnings("unchecked")
default void detects_prefixes_with_minimal_steps(
final String string,
final String firstMatchEvenKeys,
final String firstMatchOddKeys,
final int firstMatchStepsEvenKeys,
final int longestMatchStepsEvenKeys,
final int firstMatchStepsOddKeys,
final int longestMatchStepsOddKeys) {
// Test even number of prefixes.
final Map<String, Integer> prefixes =
newTestMapBuilder().add("abc", 0).add("abe", 1).add("abd", 2).add("abdicate", 3).map;
ImmutablePrefixMapping<Integer> prefixMap = newPrefixMap(prefixes);
final AtomicLong firstSearchSteps = new AtomicLong();
final AtomicLong longestSearchSteps = new AtomicLong();
firstSearchSteps.set(0);
longestSearchSteps.set(0);
assertEquals(
Pair.of(firstMatchEvenKeys, prefixes.get(firstMatchEvenKeys)),
((FixMappings.FixMapping<Integer>) prefixMap)
.getKeyAndValue(false, string, firstSearchSteps));
assertEquals(
Pair.of("abdicate", 3),
((FixMappings.FixMapping<Integer>) prefixMap)
.getKeyAndValue(true, string, longestSearchSteps));
assertEquals(firstMatchStepsEvenKeys, firstSearchSteps.get());
assertEquals(longestMatchStepsEvenKeys, longestSearchSteps.get());
// Test odd number of prefixes.
prefixes.put("aaa", 4);
prefixMap = newPrefixMap(prefixes);
firstSearchSteps.set(0);
longestSearchSteps.set(0);
assertEquals(
Pair.of(firstMatchOddKeys, prefixes.get(firstMatchOddKeys)),
((FixMappings.FixMapping<Integer>) prefixMap)
.getKeyAndValue(false, string, firstSearchSteps));
assertEquals(
Pair.of("abdicate", 3),
((FixMappings.FixMapping<Integer>) prefixMap)
.getKeyAndValue(true, string, longestSearchSteps));
assertEquals(firstMatchStepsOddKeys, firstSearchSteps.get());
assertEquals(longestMatchStepsOddKeys, longestSearchSteps.get());
}
@Test
default void allows_prefixes_with_matching_suffixes() {
// Test odd number of suffixes.
final Map<String, Integer> suffixes =
newTestMapBuilder().add("bdicate", 0).add("abdicate", 2).map;
assertDoesNotThrow(() -> newPrefixMap(suffixes));
}
static Stream<Map<String, Integer>> invalidPrefixes() {
return Stream.of(
Collections.emptyMap(),
newTestMapBuilder().add(null, 1).map,
newTestMapBuilder().add(null, 1).add("asdf", 1).map,
newTestMapBuilder().add("", 1).map,
newTestMapBuilder().add("", 1).add("asdf", 1).map,
// Invalid map with duplicate keys:
toMap(Arrays.asList(Pair.of("asdf", 1), Pair.of("asdf", 1))),
// Invalid map with null entry:
toMap(Arrays.asList(null, Pair.of("asdf", 1))));
}
@MethodSource("invalidPrefixes")
@ParameterizedTest
default void throws_illegal_arg_when_provided_invalid_values(
final Map<String, Integer> prefixes) {
final Class<? extends Exception> expectedExceptionType =
prefixes != null ? IllegalArgumentException.class : NullPointerException.class;
assertThrows(expectedExceptionType, () -> newPrefixMap(prefixes));
}
ImmutablePrefixMapping<Integer> newPrefixMap(final Map<String, Integer> prefixes);
}
interface SuffixMappersTests {
@CsvSource(
value = {
"null,false,null",
",false,null",
"123456,false,null",
"~~~~~~,false,null",
"a,false,null",
"ab,false,null",
"abc,true,0",
"1abc,true,0",
"abe,true,1",
"abed,false,null",
"abd,false,null",
"aba,false,null",
"at,false,null",
"ate,true,2",
"cate,true,2",
"icate,true,2",
"dicate,true,2",
"bdicate,true,2",
"abdicate,true,3",
"i abdicate,true,3",
"abdicated,false,null",
"z,false,null",
"yz,false,null"
},
nullValues = "null")
@ParameterizedTest
@SuppressWarnings("unchecked")
default void detects_suffixes(
final String string, final boolean expectSuffixed, final Integer expectedValue) {
// Test even number of suffixes.
final Map<String, Integer> suffixes =
newTestMapBuilder().add("abc", 0).add("abe", 1).add("ate", 2).add("abdicate", 3).map;
ImmutableSuffixMapping<Integer> suffixMap = newSuffixMap(suffixes);
assertEquals(expectSuffixed, suffixMap.matchesAnySuffix(string));
assertEquals(expectedValue, suffixMap.valueForSuffix(string));
assertEquals(
getKeyAndValueByValue(suffixes, expectedValue), suffixMap.keyAndValueForSuffix(string));
assertFirstMatchSearchTakesLessSteps(
string, expectedValue, (FixMappings.FixMapping<Integer>) suffixMap);
// Test odd number of suffixes.
suffixes.put("xyz", 4);
suffixMap = newSuffixMap(suffixes);
assertEquals(expectSuffixed, suffixMap.matchesAnySuffix(string));
assertEquals(expectedValue, suffixMap.valueForSuffix(string));
assertEquals(
getKeyAndValueByValue(suffixes, expectedValue), suffixMap.keyAndValueForSuffix(string));
assertFirstMatchSearchTakesLessSteps(
string, expectedValue, (FixMappings.FixMapping<Integer>) suffixMap);
}
@SuppressWarnings("unchecked")
default void detects_suffixes_with_minimal_steps(
final String string,
final String firstMatchEvenKeys,
final String firstMatchOddKeys,
final int firstMatchStepsEvenKeys,
final int longestMatchStepsEvenKeys,
final int firstMatchStepsOddKeys,
final int longestMatchStepsOddKeys) {
// Test even number of suffixes.
final Map<String, Integer> suffixes =
newTestMapBuilder().add("abc", 0).add("abe", 1).add("ate", 2).add("abdicate", 3).map;
ImmutableSuffixMapping<Integer> suffixMap = newSuffixMap(suffixes);
final AtomicLong firstSearchSteps = new AtomicLong();
final AtomicLong longestSearchSteps = new AtomicLong();
firstSearchSteps.set(0);
longestSearchSteps.set(0);
assertEquals(
Pair.of(firstMatchEvenKeys, suffixes.get(firstMatchEvenKeys)),
((FixMappings.FixMapping<Integer>) suffixMap)
.getKeyAndValue(false, string, firstSearchSteps));
assertEquals(
Pair.of("abdicate", 3),
((FixMappings.FixMapping<Integer>) suffixMap)
.getKeyAndValue(true, string, longestSearchSteps));
assertEquals(firstMatchStepsEvenKeys, firstSearchSteps.get());
assertEquals(longestMatchStepsEvenKeys, longestSearchSteps.get());
// Test odd number of suffixes.
suffixes.put("aaa", 4);
suffixMap = newSuffixMap(suffixes);
firstSearchSteps.set(0);
longestSearchSteps.set(0);
assertEquals(
Pair.of(firstMatchOddKeys, suffixes.get(firstMatchOddKeys)),
((FixMappings.FixMapping<Integer>) suffixMap)
.getKeyAndValue(false, string, firstSearchSteps));
assertEquals(
Pair.of("abdicate", 3),
((FixMappings.FixMapping<Integer>) suffixMap)
.getKeyAndValue(true, string, longestSearchSteps));
assertEquals(firstMatchStepsOddKeys, firstSearchSteps.get());
assertEquals(longestMatchStepsOddKeys, longestSearchSteps.get());
}
@Test
default void allows_suffixes_with_matching_prefixes() {
// Test odd number of suffixes.
final Map<String, Integer> suffixes =
newTestMapBuilder().add("abdicat", 0).add("abdicate", 2).map;
assertDoesNotThrow(() -> newSuffixMap(suffixes));
}
static Stream<Map<String, Integer>> invalidSuffixes() {
return Stream.of(
Collections.emptyMap(),
newTestMapBuilder().add(null, 1).map,
newTestMapBuilder().add(null, 1).add("asdf", 1).map,
newTestMapBuilder().add("", 1).map,
newTestMapBuilder().add("", 1).add("asdf", 1).map,
// Invalid map with duplicate keys:
toMap(Arrays.asList(Pair.of("asdf", 1), Pair.of("asdf", 1))),
// Invalid map with null entry:
toMap(Arrays.asList(null, Pair.of("asdf", 1))));
}
@MethodSource("invalidSuffixes")
@ParameterizedTest
default void throws_illegal_arg_when_provided_invalid_values(
final Map<String, Integer> suffixes) {
final Class<? extends Exception> expectedExceptionType =
suffixes != null ? IllegalArgumentException.class : NullPointerException.class;
assertThrows(expectedExceptionType, () -> newSuffixMap(suffixes));
}
ImmutableSuffixMapping<Integer> newSuffixMap(final Map<String, Integer> prefixes);
}
private static void assertFirstMatchSearchTakesLessSteps(
String string, Integer expectedValue, FixMappings.FixMapping<Integer> fixMapping) {
final AtomicLong firstSearchSteps = new AtomicLong(0);
final AtomicLong longestSearchSteps = new AtomicLong(0);
final Pair<String, Integer> firstMatch =
fixMapping.getKeyAndValue(false, string, firstSearchSteps);
if (expectedValue != null) {
assertNotNull(firstMatch);
} else {
assertNull(firstMatch);
}
final Pair<String, Integer> longestMatch =
fixMapping.getKeyAndValue(true, string, longestSearchSteps);
if (expectedValue != null) {
assertNotNull(longestMatch);
} else {
assertNull(longestMatch);
}
assertTrue(firstSearchSteps.get() <= longestSearchSteps.get());
}
static final class BinarySearchArrayPrefixMapTests implements PrefixMappersTests {
@Override
public ImmutablePrefixMapping<Integer> newPrefixMap(final Map<String, Integer> prefixes) {
return binarySearchArrayPrefixMapping(prefixes);
}
@CsvSource(
value = {
"abdicate,abd,abdicate,3,11,8,8",
"abdicated,abd,abdicate,3,14,8,11",
})
@ParameterizedTest
@Override
public void detects_prefixes_with_minimal_steps(
final String string,
final String firstMatchEvenKeys,
final String firstMatchOddKeys,
final int firstMatchStepsEvenKeys,
final int longestMatchStepsEvenKeys,
final int firstMatchStepsOddKeys,
final int longestMatchStepsOddKeys) {
PrefixMappersTests.super.detects_prefixes_with_minimal_steps(
string,
firstMatchEvenKeys,
firstMatchOddKeys,
firstMatchStepsEvenKeys,
longestMatchStepsEvenKeys,
firstMatchStepsOddKeys,
longestMatchStepsOddKeys);
}
}
static final class BinarySearchArraySuffixMapTests implements SuffixMappersTests {
@Override
public ImmutableSuffixMapping<Integer> newSuffixMap(final Map<String, Integer> suffixes) {
return binarySearchArraySuffixMapping(suffixes);
}
@CsvSource(
value = {
"abdicate,abdicate,ate,8,8,5,13",
"i abdicate,abdicate,ate,8,10,5,13",
})
@ParameterizedTest
@Override
public void detects_suffixes_with_minimal_steps(
final String string,
final String firstMatchEvenKeys,
final String firstMatchOddKeys,
final int firstMatchStepsEvenKeys,
final int longestMatchStepsEvenKeys,
final int firstMatchStepsOddKeys,
final int longestMatchStepsOddKeys) {
SuffixMappersTests.super.detects_suffixes_with_minimal_steps(
string,
firstMatchEvenKeys,
firstMatchOddKeys,
firstMatchStepsEvenKeys,
longestMatchStepsEvenKeys,
firstMatchStepsOddKeys,
longestMatchStepsOddKeys);
}
}
static final class LimitedCharArrayTriePrefixMapTests implements PrefixMappersTests {
@Override
public ImmutablePrefixMapping<Integer> newPrefixMap(final Map<String, Integer> prefixes) { | return limitedCharArrayTriePrefixMapping('a', 'z', prefixes); | 2 | 2023-11-12 05:05:22+00:00 | 8k |
slow3586/HypersomniaMapGen | src/main/java/com/slow3586/Main.java | [
{
"identifier": "RoomStyle",
"path": "src/main/java/com/slow3586/Main.java",
"snippet": "@Value\npublic static class RoomStyle {\n int height;\n Color floorColor;\n Color wallColor;\n int patternIdFloor;\n int patternIdWall;\n Color patternColorFloor;\n Color patternColorWall;\n}"
... | import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.slow3586.Main.Room.RoomStyle;
import com.slow3586.Main.Settings.Node.ExternalResource;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.Getter;
import lombok.ToString;
import lombok.Value;
import org.jooq.lambda.Sneaky;
import org.jooq.lambda.function.Consumer1;
import org.jooq.lambda.function.Consumer2;
import org.jooq.lambda.function.Consumer4;
import org.jooq.lambda.function.Function1;
import org.jooq.lambda.function.Function3;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.StringJoiner;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static com.slow3586.Main.Color.WHITE;
import static com.slow3586.Main.MapTile.TileType.DOOR;
import static com.slow3586.Main.MapTile.TileType.WALL;
import static com.slow3586.Main.Settings.Layer;
import static com.slow3586.Main.Settings.Node;
import static com.slow3586.Main.Settings.Node.AsNonPhysical.AS_NON_PHYSICAL_DEFAULT;
import static com.slow3586.Main.Settings.Node.AsPhysical.AS_PHYSICAL_DEFAULT;
import static com.slow3586.Main.Settings.Node.ExternalResource.BASE_PNG_TEXTURE_FILENAME;
import static com.slow3586.Main.Settings.Node.ExternalResource.CRATE_BLOCKING;
import static com.slow3586.Main.Settings.Node.ExternalResource.CRATE_NON_BLOCKING;
import static com.slow3586.Main.Settings.Node.ExternalResource.DOMAIN_FOREGROUND;
import static com.slow3586.Main.Settings.Node.ExternalResource.DOMAIN_PHYSICAL;
import static com.slow3586.Main.Settings.Node.ExternalResource.LINE_FLOOR;
import static com.slow3586.Main.Settings.Node.ExternalResource.LINE_WALL;
import static com.slow3586.Main.Settings.Node.ExternalResource.MAP_GFX_PATH;
import static com.slow3586.Main.Settings.Node.ExternalResource.PNG_EXT;
import static com.slow3586.Main.Settings.Node.ExternalResource.RESOURCE_FLOOR_ID;
import static com.slow3586.Main.Settings.Node.ExternalResource.RESOURCE_ID_PREFIX;
import static com.slow3586.Main.Settings.Node.ExternalResource.RESOURCE_WALL_ID;
import static com.slow3586.Main.Settings.Node.ExternalResource.ROOM_NOISE_CIRCLE;
import static com.slow3586.Main.Settings.Node.ExternalResource.SHADOW_FLOOR_CORNER;
import static com.slow3586.Main.Settings.Node.ExternalResource.SHADOW_FLOOR_LINE;
import static com.slow3586.Main.Settings.Node.ExternalResource.SHADOW_WALL_CORNER;
import static com.slow3586.Main.Settings.Node.ExternalResource.SHADOW_WALL_LINE;
import static com.slow3586.Main.Settings.Playtesting;
import static com.slow3586.Main.Size.CRATE_SIZE;
import static com.slow3586.Main.Size.TILE_SIZE; | 5,989 | + (isBlocking ? "" : "non")
+ "blocking";
//endregion
//region RESOURCES: ROOMS
mapJson.external_resources.add(
ExternalResource.builder()
.path(MAP_GFX_PATH + ROOM_NOISE_CIRCLE + PNG_EXT)
.id(RESOURCE_ID_PREFIX + ROOM_NOISE_CIRCLE)
.stretch_when_resized(true)
.domain(DOMAIN_FOREGROUND)
.color(new Color(255, 255, 255, 150).intArray())
.build());
createTextureSameName.accept(ROOM_NOISE_CIRCLE);
//endregion
//region RESOURCES: STYLES
IntStream.range(0, styles.length)
.boxed()
.forEach((final Integer roomStyleIndex) -> {
final RoomStyle style = styles[roomStyleIndex];
final String floorId = RESOURCE_FLOOR_ID + roomStyleIndex;
mapJson.external_resources.add(
ExternalResource.builder()
.path(MAP_GFX_PATH + floorId + PNG_EXT)
.id(RESOURCE_ID_PREFIX + floorId)
.color(style.floorColor.intArray())
.build());
createTexture.accept(BASE_PNG_TEXTURE_FILENAME, floorId);
final String wallId = RESOURCE_WALL_ID + roomStyleIndex;
mapJson.external_resources.add(
ExternalResource.builder()
.path(MAP_GFX_PATH + wallId + PNG_EXT)
.id(RESOURCE_ID_PREFIX + wallId)
.domain(DOMAIN_PHYSICAL)
.color(style.wallColor.intArray())
.as_physical(AS_PHYSICAL_DEFAULT)
.build());
createTexture.accept(BASE_PNG_TEXTURE_FILENAME, wallId);
final String patternWallTarget = "style" + roomStyleIndex + "_pattern_wall";
mapJson.external_resources.add(
ExternalResource.builder()
.path(MAP_GFX_PATH + patternWallTarget + PNG_EXT)
.id(RESOURCE_ID_PREFIX + patternWallTarget)
.domain(DOMAIN_FOREGROUND)
.color(style.patternColorWall.intArray())
.build());
createTexture.accept("pattern" + style.patternIdWall, patternWallTarget);
final String patternFloorTarget = "style" + roomStyleIndex + "_pattern_floor";
mapJson.external_resources.add(
ExternalResource.builder()
.path(MAP_GFX_PATH + patternFloorTarget + PNG_EXT)
.id(RESOURCE_ID_PREFIX + patternFloorTarget)
.color(style.patternColorFloor.intArray())
.build());
createTexture.accept("pattern" + style.patternIdFloor, patternFloorTarget);
final BiConsumer<Integer, Boolean> createCrate = (
final Integer crateStyleIndex,
final Boolean isBlocking
) -> {
final String crateName = getCrateName.apply(
roomStyleIndex,
crateStyleIndex,
isBlocking);
final float sizeMultiplier = config.crateMinMaxSizeMultiplier.randomize();
mapJson.external_resources.add(
ExternalResource.builder()
.path(MAP_GFX_PATH + crateName + PNG_EXT)
.id(RESOURCE_ID_PREFIX + crateName)
.domain(DOMAIN_PHYSICAL)
.stretch_when_resized(true)
.size(CRATE_SIZE
.mul(sizeMultiplier)
.floatArray())
.color((isBlocking
? config.crateBlockingMinMaxTint
: config.crateNonBlockingMinMaxTint)
.randomize()
.intArray()
).as_physical(Node.AsPhysical.builder()
.custom_shape(Node.AsPhysical.CustomShape
.CRATE_SHAPE
.mul(sizeMultiplier))
.is_see_through(!isBlocking)
.is_shoot_through(!isBlocking)
.is_melee_throw_through(!isBlocking)
.is_throw_through(!isBlocking)
.density(nextFloat(0.6f, 1.3f))
.friction(nextFloat(0.0f, 0.5f))
.bounciness(nextFloat(0.1f, 0.6f))
.penetrability(nextFloat(0.0f, 1.0f))
.angular_damping(nextFloat(10f, 100f))
.build())
.build());
createTexture.accept(isBlocking ? CRATE_BLOCKING : CRATE_NON_BLOCKING, crateName);
};
IntStream.range(0, config.cratesBlockingPerStyle)
.forEach(crateIndex -> createCrate.accept(crateIndex, true));
IntStream.range(0, config.cratesNonBlockingPerStyle)
.forEach(crateIndex -> createCrate.accept(crateIndex, false));
});
//endregion
//region RESOURCES: SHADOWS
mapJson.external_resources.add(
ExternalResource.builder()
.path(MAP_GFX_PATH + SHADOW_WALL_CORNER + PNG_EXT)
.id(RESOURCE_ID_PREFIX + SHADOW_WALL_CORNER)
.domain(DOMAIN_FOREGROUND)
.color(config.shadowTintWall.intArray())
.as_nonphysical(AS_NON_PHYSICAL_DEFAULT)
.build());
createTextureSameName.accept(SHADOW_WALL_CORNER);
mapJson.external_resources.add(
ExternalResource.builder() | package com.slow3586;
public class Main {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
static Random baseRandom;
static Configuration config;
static {
OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
OBJECT_MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
public static void main(String[] args) throws IOException {
//region CONFIGURATION
final String configStr = Files.readString(Path.of("config.json"));
config = OBJECT_MAPPER.readValue(configStr, Configuration.class);
baseRandom = new Random(config.randomSeed);
final Path mapDirectory = Path.of(config.gameDirectoryPath, "user", "projects", config.mapName);
//endregion
//region GENERATION: ROOMS
//region RANDOMIZE DIAGONAL ROOM SIZES
final Size[] diagonalRoomSizes = Stream.generate(() -> config.roomMinMaxSize.randomize())
.limit(Math.max(config.roomsCount.x, config.roomsCount.y))
.toArray(Size[]::new);
//endregion
//region RANDOMIZE ROOM STYLES
final RoomStyle[] styles = IntStream.range(0, config.styleCount)
.boxed()
.map(styleIndex ->
new RoomStyle(
config.styleHeightOverride.length > styleIndex
? config.styleHeightOverride[styleIndex]
: styleIndex,
config.floorMinMaxTintBase
.randomize()
.add(config.floorTintPerHeight.mul(styleIndex)),
config.wallMinMaxTintBase
.randomize()
.add(config.wallTintPerHeight.mul(styleIndex)),
nextInt(1, config.patternResourceCount),
nextInt(1, config.patternResourceCount),
config.patternMinMaxTintFloor.randomize(),
config.patternMinMaxTintWall.randomize())
).toArray(RoomStyle[]::new);
//endregion
final Room[][] rooms = new Room[config.roomsCount.y][config.roomsCount.x];
pointsRect(0, 0, config.roomsCount.x, config.roomsCount.y)
.forEach(roomIndex -> {
final boolean disableRoom = Arrays.asList(config.roomsDisabled).contains(roomIndex);
final boolean disableDoorRight =
Arrays.asList(config.roomsDoorRightDisabled).contains(roomIndex)
|| (disableRoom && Arrays.asList(config.roomsDisabled).contains(roomIndex.add(Point.RIGHT)));
final boolean disableDoorDown =
Arrays.asList(config.roomsDoorDownDisabled).contains(roomIndex)
|| (disableRoom && Arrays.asList(config.roomsDisabled).contains(roomIndex.add(Point.DOWN)));
//region CALCULATE ABSOLUTE ROOM POSITION
final Point roomPosAbs = new Point(
Arrays.stream(diagonalRoomSizes)
.limit(roomIndex.x)
.map(Size::getW)
.reduce(0, Integer::sum),
Arrays.stream(diagonalRoomSizes)
.limit(roomIndex.y)
.map(Size::getH)
.reduce(0, Integer::sum));
//endregion
//region RANDOMIZE WALL
final Size wallSize =
config.wallMinMaxSize.randomize();
final Point wallOffset = new Point(
-nextInt(0, Math.min(wallSize.w, config.wallMaxOffset.x)),
-nextInt(0, Math.min(wallSize.h, config.wallMaxOffset.y)));
//endregion
//region RANDOMIZE DOOR
final Size roomFloorSpace = new Size(
diagonalRoomSizes[roomIndex.x].w + wallOffset.y,
diagonalRoomSizes[roomIndex.y].h + wallOffset.x);
final boolean needVerticalDoor =
!disableDoorRight
&& roomIndex.x > 0
&& roomIndex.x < rooms[0].length - 1;
final boolean needHorizontalDoor =
!disableDoorDown
&& roomIndex.y > 0
&& roomIndex.y < rooms.length - 1;
final Size doorSize = new Size(
needHorizontalDoor
? Math.min(config.doorMinMaxWidth.randomizeWidth(), roomFloorSpace.w - 1)
: 0,
needVerticalDoor
? Math.min(config.doorMinMaxWidth.randomizeHeight(), roomFloorSpace.h - 1)
: 0);
final Point doorOffset = new Point(
needHorizontalDoor
? nextInt(1, roomFloorSpace.w - doorSize.w + 1)
: 0,
needVerticalDoor
? nextInt(1, roomFloorSpace.h - doorSize.h + 1)
: 0);
//endregion
//region RANDOMIZE STYLE
final int styleIndex = nextInt(0, config.styleCount);
final Size styleSize = new Size(
roomIndex.x == config.roomsCount.x - 1 ? 1
: config.styleSizeMinMaxSize.randomizeWidth(),
roomIndex.y == config.roomsCount.y - 1 ? 1
: config.styleSizeMinMaxSize.randomizeHeight());
//endregion
//region PUT ROOM INTO ROOMS ARRAY
rooms[roomIndex.y][roomIndex.x] = new Room(
roomPosAbs,
new Size(
diagonalRoomSizes[roomIndex.x].w,
diagonalRoomSizes[roomIndex.y].h),
new Room.Rect(
wallOffset.x,
wallSize.w),
new Room.Rect(
wallOffset.y,
wallSize.h),
new Room.Rect(
doorOffset.x,
doorSize.w),
new Room.Rect(
doorOffset.y,
doorSize.h),
styleIndex,
styleSize,
disableRoom);
//endregion
});
//endregion
//region GENERATION: BASE MAP TILE ARRAY
final MapTile[][] mapTilesUncropped =
pointsRectRows(
Arrays.stream(diagonalRoomSizes)
.mapToInt(r -> r.w
+ Math.max(config.styleSizeMinMaxSize.max.w, config.wallMaxOffset.x))
.sum() + 1,
Arrays.stream(diagonalRoomSizes)
.mapToInt(r -> r.h
+ Math.max(config.styleSizeMinMaxSize.max.h, config.wallMaxOffset.y))
.sum() + 1)
.stream()
.map(row -> row.stream()
.map(point -> new MapTile(
MapTile.TileType.FLOOR,
null,
false,
false,
null))
.toArray(MapTile[]::new)
).toArray(MapTile[][]::new);
//endregion
//region GENERATION: RENDER BASE ROOMS ONTO BASE MAP TILE ARRAY
pointsRectArray(rooms)
.forEach(roomIndex -> {
final Room room = rooms[roomIndex.y][roomIndex.x];
//region FILL MAP TILES
//region WALL HORIZONTAL
pointsRect(
room.roomPosAbs.x,
room.roomPosAbs.y + room.roomSize.h + room.wallHoriz.offset,
room.roomSize.w,
room.wallHoriz.width
).forEach(pointAbs -> {
final boolean isDoorTile = (mapTilesUncropped[pointAbs.y][pointAbs.x].tileType == MapTile.TileType.DOOR)
|| (pointAbs.x >= room.roomPosAbs.x + room.doorHoriz.offset
&& pointAbs.x < room.roomPosAbs.x + room.doorHoriz.offset + room.doorHoriz.width);
mapTilesUncropped[pointAbs.y][pointAbs.x].disabled = !isDoorTile;
mapTilesUncropped[pointAbs.y][pointAbs.x].tileType =
isDoorTile
? MapTile.TileType.DOOR
: WALL;
});
//endregion
//region WALL VERTICAL
pointsRect(
room.roomPosAbs.x + room.roomSize.w + room.wallVert.offset,
room.roomPosAbs.y,
room.wallVert.width,
room.roomSize.h
).forEach(pointAbs -> {
final boolean isDoorTile = (mapTilesUncropped[pointAbs.y][pointAbs.x].tileType == MapTile.TileType.DOOR)
|| (pointAbs.y >= room.roomPosAbs.y + room.doorVert.offset
&& pointAbs.y < room.roomPosAbs.y + room.doorVert.offset + room.doorVert.width);
mapTilesUncropped[pointAbs.y][pointAbs.x].disabled = !isDoorTile;
mapTilesUncropped[pointAbs.y][pointAbs.x].tileType =
isDoorTile
? MapTile.TileType.DOOR
: WALL;
});
//endregion
//region DISABLE FLOOR
if (room.isDisabled()) {
pointsRect(
room.roomPosAbs.x,
room.roomPosAbs.y,
room.roomSize.w + room.wallVert.offset,
room.roomSize.h + room.wallHoriz.offset
).forEach(pointAbs -> {
final boolean isDoorTile = mapTilesUncropped[pointAbs.y][pointAbs.x].tileType == DOOR;
mapTilesUncropped[pointAbs.y][pointAbs.x].disabled = !isDoorTile;
mapTilesUncropped[pointAbs.y][pointAbs.x].tileType =
isDoorTile
? MapTile.TileType.DOOR
: WALL;
});
}
//endregion
//region CARCASS HORIZONTAL
pointsRect(
room.roomPosAbs.x,
room.roomPosAbs.y + room.roomSize.h,
room.roomSize.w,
1
).forEach(pointAbs ->
mapTilesUncropped[pointAbs.y][pointAbs.x].carcass = true);
//endregion
//region CARCASS VERTICAL
pointsRect(
room.roomPosAbs.x + room.roomSize.w,
room.roomPosAbs.y,
1,
room.roomSize.h
).forEach(pointAbs ->
mapTilesUncropped[pointAbs.y][pointAbs.x].carcass = true);
//endregion
//region TILE ROOM TYPE
pointsRect(
room.roomPosAbs.x,
room.roomPosAbs.y,
room.roomSize.w + room.styleSize.w,
room.roomSize.h + room.styleSize.h
).stream()
.map(pointAbs -> mapTilesUncropped[pointAbs.y][pointAbs.x])
.forEach(tile -> {
if (tile.styleIndex == null) {
tile.styleIndex = room.styleIndex;
}
tile.height = styles[room.styleIndex].height
+ (tile.tileType == WALL
? config.wallHeight
: 0);
});
//endregion
//endregion
});
//endregion
//region GENERATION: CROP MAP
final MapTile[][] mapTilesCrop;
if (config.cropMap) {
final Size croppedMapSize = new Size(
Arrays.stream(diagonalRoomSizes)
.limit(rooms[0].length)
.map(s -> s.w)
.reduce(0, Integer::sum)
- diagonalRoomSizes[0].w
+ 1,
Arrays.stream(diagonalRoomSizes)
.limit(rooms.length)
.map(s -> s.h)
.reduce(0, Integer::sum)
- diagonalRoomSizes[0].h
+ 1);
final MapTile[][] temp = new MapTile[croppedMapSize.h][croppedMapSize.w];
for (int y = 0; y < croppedMapSize.h; y++) {
temp[y] = Arrays.copyOfRange(
mapTilesUncropped[y + diagonalRoomSizes[0].h],
diagonalRoomSizes[0].w,
diagonalRoomSizes[0].w + croppedMapSize.w);
}
mapTilesCrop = temp;
} else {
mapTilesCrop = mapTilesUncropped;
}
//endregion
//region GENERATION: FIX MOST DOWN RIGHT TILE
mapTilesCrop[mapTilesCrop.length - 1][mapTilesCrop[0].length - 1] =
mapTilesCrop[mapTilesCrop.length - 1][mapTilesCrop[0].length - 2];
//endregion
//region GENERATION: FIX DIAGONAL WALLS TOUCH WITH EMPTY SIDES
// #_ _#
// _# OR #_
final Function1<MapTile, Boolean> isWall = (s) -> s.tileType == MapTile.TileType.WALL;
for (int iter = 0; iter < 2; iter++) {
for (int y = 1; y < mapTilesCrop.length - 1; y++) {
for (int x = 1; x < mapTilesCrop[y].length - 1; x++) {
final boolean wall = isWall.apply(mapTilesCrop[y][x]);
final boolean wallR = isWall.apply(mapTilesCrop[y][x + 1]);
final boolean wallD = isWall.apply(mapTilesCrop[y + 1][x]);
final boolean wallRD = isWall.apply(mapTilesCrop[y + 1][x + 1]);
if ((wall && wallRD && !wallR && !wallD)
|| (!wall && !wallRD && wallR && wallD)
) {
if (wall)
mapTilesCrop[y][x].height -= config.wallHeight;
mapTilesCrop[y][x].tileType = MapTile.TileType.FLOOR;
if (wallR)
mapTilesCrop[y][x + 1].height -= config.wallHeight;
mapTilesCrop[y][x + 1].tileType = MapTile.TileType.FLOOR;
if (wallD)
mapTilesCrop[y + 1][x].height -= config.wallHeight;
mapTilesCrop[y + 1][x].tileType = MapTile.TileType.FLOOR;
if (wallRD)
mapTilesCrop[y + 1][x + 1].height -= config.wallHeight;
mapTilesCrop[y + 1][x + 1].tileType = MapTile.TileType.FLOOR;
}
}
}
}
//endregion
//region OUTPUT: PRINT MAP TO TEXT FILE
final StringJoiner wallJoiner = new StringJoiner("\n");
wallJoiner.add("Walls:");
final StringJoiner heightJoiner = new StringJoiner("\n");
heightJoiner.add("Heights:");
final StringJoiner styleIndexJoiner = new StringJoiner("\n");
styleIndexJoiner.add("Styles:");
final StringJoiner carcassJoiner = new StringJoiner("\n");
carcassJoiner.add("Carcass:");
pointsRectArrayByRow(mapTilesCrop)
.forEach(row -> {
final StringBuilder wallJoinerRow = new StringBuilder();
final StringBuilder heightJoinerRow = new StringBuilder();
final StringBuilder styleIndexJoinerRow = new StringBuilder();
final StringBuilder carcassJoinerRow = new StringBuilder();
row.forEach(point -> {
final MapTile mapTile = mapTilesCrop[point.y][point.x];
wallJoinerRow.append(
mapTile.tileType == WALL
? "#"
: mapTile.tileType == MapTile.TileType.DOOR
? "."
: "_");
heightJoinerRow.append(mapTile.height);
styleIndexJoinerRow.append(mapTile.styleIndex);
carcassJoinerRow.append(
mapTile.disabled && !mapTile.carcass
? "X"
: mapTile.carcass || point.x == 0 || point.y == 0
? "#"
: "_");
});
wallJoiner.add(wallJoinerRow.toString());
heightJoiner.add(heightJoinerRow.toString());
styleIndexJoiner.add(styleIndexJoinerRow.toString());
carcassJoiner.add(carcassJoinerRow.toString());
});
final StringJoiner textJoiner = new StringJoiner("\n\n");
textJoiner.add(carcassJoiner.toString());
textJoiner.add(wallJoiner.toString());
textJoiner.add(heightJoiner.toString());
textJoiner.add(styleIndexJoiner.toString());
Files.write(Path.of(config.outputTextFilePath), textJoiner.toString().getBytes());
//endregion
//region OUTPUT: CREATE MAP JSON FILE
//region BASE MAP JSON OBJECT
final Map mapJson = new Map(
new Meta(
config.gameVersion,
config.mapName,
"2023-11-14 17:28:36.619839 UTC"),
new About("Generated map"),
new Settings(
"bomb_defusal",
config.ambientLightColor.intArray()),
new Playtesting(Playtesting.QUICK_TEST),
new ArrayList<>(),
List.of(new Layer(
"default",
new ArrayList<>())),
new ArrayList<>());
//endregion
//region RESOURCES: FUNCTIONS
final File texturesDir = new File("textures");
final Path mapGfxPath = mapDirectory.resolve("gfx");
if (!Files.exists(mapGfxPath)) {
Files.createDirectories(mapGfxPath);
}
final BiConsumer<String, String> createTexture = Sneaky.biConsumer(
(sourceFilename, targetFilename) -> {
final Path sourcePath = texturesDir.toPath().resolve(sourceFilename + PNG_EXT);
final Path targetPath = mapGfxPath.resolve(targetFilename + PNG_EXT);
if (Files.exists(targetPath))
Files.delete(targetPath);
Files.copy(sourcePath, targetPath);
});
final Consumer<String> createTextureSameName = Sneaky.consumer(
(filename) -> createTexture.accept(filename, filename));
final Function3<Integer, Integer, Boolean, String> getCrateName = (
final Integer roomStyleIndex,
final Integer crateStyleIndex,
final Boolean isBlocking
) -> "style"
+ roomStyleIndex
+ "_crate"
+ crateStyleIndex
+ "_"
+ (isBlocking ? "" : "non")
+ "blocking";
//endregion
//region RESOURCES: ROOMS
mapJson.external_resources.add(
ExternalResource.builder()
.path(MAP_GFX_PATH + ROOM_NOISE_CIRCLE + PNG_EXT)
.id(RESOURCE_ID_PREFIX + ROOM_NOISE_CIRCLE)
.stretch_when_resized(true)
.domain(DOMAIN_FOREGROUND)
.color(new Color(255, 255, 255, 150).intArray())
.build());
createTextureSameName.accept(ROOM_NOISE_CIRCLE);
//endregion
//region RESOURCES: STYLES
IntStream.range(0, styles.length)
.boxed()
.forEach((final Integer roomStyleIndex) -> {
final RoomStyle style = styles[roomStyleIndex];
final String floorId = RESOURCE_FLOOR_ID + roomStyleIndex;
mapJson.external_resources.add(
ExternalResource.builder()
.path(MAP_GFX_PATH + floorId + PNG_EXT)
.id(RESOURCE_ID_PREFIX + floorId)
.color(style.floorColor.intArray())
.build());
createTexture.accept(BASE_PNG_TEXTURE_FILENAME, floorId);
final String wallId = RESOURCE_WALL_ID + roomStyleIndex;
mapJson.external_resources.add(
ExternalResource.builder()
.path(MAP_GFX_PATH + wallId + PNG_EXT)
.id(RESOURCE_ID_PREFIX + wallId)
.domain(DOMAIN_PHYSICAL)
.color(style.wallColor.intArray())
.as_physical(AS_PHYSICAL_DEFAULT)
.build());
createTexture.accept(BASE_PNG_TEXTURE_FILENAME, wallId);
final String patternWallTarget = "style" + roomStyleIndex + "_pattern_wall";
mapJson.external_resources.add(
ExternalResource.builder()
.path(MAP_GFX_PATH + patternWallTarget + PNG_EXT)
.id(RESOURCE_ID_PREFIX + patternWallTarget)
.domain(DOMAIN_FOREGROUND)
.color(style.patternColorWall.intArray())
.build());
createTexture.accept("pattern" + style.patternIdWall, patternWallTarget);
final String patternFloorTarget = "style" + roomStyleIndex + "_pattern_floor";
mapJson.external_resources.add(
ExternalResource.builder()
.path(MAP_GFX_PATH + patternFloorTarget + PNG_EXT)
.id(RESOURCE_ID_PREFIX + patternFloorTarget)
.color(style.patternColorFloor.intArray())
.build());
createTexture.accept("pattern" + style.patternIdFloor, patternFloorTarget);
final BiConsumer<Integer, Boolean> createCrate = (
final Integer crateStyleIndex,
final Boolean isBlocking
) -> {
final String crateName = getCrateName.apply(
roomStyleIndex,
crateStyleIndex,
isBlocking);
final float sizeMultiplier = config.crateMinMaxSizeMultiplier.randomize();
mapJson.external_resources.add(
ExternalResource.builder()
.path(MAP_GFX_PATH + crateName + PNG_EXT)
.id(RESOURCE_ID_PREFIX + crateName)
.domain(DOMAIN_PHYSICAL)
.stretch_when_resized(true)
.size(CRATE_SIZE
.mul(sizeMultiplier)
.floatArray())
.color((isBlocking
? config.crateBlockingMinMaxTint
: config.crateNonBlockingMinMaxTint)
.randomize()
.intArray()
).as_physical(Node.AsPhysical.builder()
.custom_shape(Node.AsPhysical.CustomShape
.CRATE_SHAPE
.mul(sizeMultiplier))
.is_see_through(!isBlocking)
.is_shoot_through(!isBlocking)
.is_melee_throw_through(!isBlocking)
.is_throw_through(!isBlocking)
.density(nextFloat(0.6f, 1.3f))
.friction(nextFloat(0.0f, 0.5f))
.bounciness(nextFloat(0.1f, 0.6f))
.penetrability(nextFloat(0.0f, 1.0f))
.angular_damping(nextFloat(10f, 100f))
.build())
.build());
createTexture.accept(isBlocking ? CRATE_BLOCKING : CRATE_NON_BLOCKING, crateName);
};
IntStream.range(0, config.cratesBlockingPerStyle)
.forEach(crateIndex -> createCrate.accept(crateIndex, true));
IntStream.range(0, config.cratesNonBlockingPerStyle)
.forEach(crateIndex -> createCrate.accept(crateIndex, false));
});
//endregion
//region RESOURCES: SHADOWS
mapJson.external_resources.add(
ExternalResource.builder()
.path(MAP_GFX_PATH + SHADOW_WALL_CORNER + PNG_EXT)
.id(RESOURCE_ID_PREFIX + SHADOW_WALL_CORNER)
.domain(DOMAIN_FOREGROUND)
.color(config.shadowTintWall.intArray())
.as_nonphysical(AS_NON_PHYSICAL_DEFAULT)
.build());
createTextureSameName.accept(SHADOW_WALL_CORNER);
mapJson.external_resources.add(
ExternalResource.builder() | .path(MAP_GFX_PATH + SHADOW_WALL_LINE + PNG_EXT) | 23 | 2023-11-18 14:36:04+00:00 | 8k |
intrepidLi/BUAA_Food | app/src/main/java/com/buaa/food/ui/activity/StatusActivity.java | [
{
"identifier": "StatusAction",
"path": "app/src/main/java/com/buaa/food/action/StatusAction.java",
"snippet": "public interface StatusAction {\n\n /**\n * 获取状态布局\n */\n StatusLayout getStatusLayout();\n\n /**\n * 显示加载中\n */\n default void showLoading() {\n showLoading... | import androidx.core.content.ContextCompat;
import com.buaa.food.R;
import com.buaa.food.action.StatusAction;
import com.buaa.food.app.AppActivity;
import com.buaa.food.ui.dialog.MenuDialog;
import com.buaa.food.widget.StatusLayout; | 4,565 | package com.buaa.food.ui.activity;
public final class StatusActivity extends AppActivity
implements StatusAction {
| package com.buaa.food.ui.activity;
public final class StatusActivity extends AppActivity
implements StatusAction {
| private StatusLayout mStatusLayout; | 3 | 2023-11-14 10:04:26+00:00 | 8k |
WallasAR/GUITest | src/main/java/com/session/employee/employeeClientController.java | [
{
"identifier": "Banco",
"path": "src/main/java/com/db/bank/Banco.java",
"snippet": "public class Banco {\n Scanner scanner1 = new Scanner(System.in);\n public static Connection connection = conexao();\n Statement executar;\n {\n try {\n executar = connection.createStateme... | import com.db.bank.Banco;
import com.example.guitest.Main;
import com.table.view.ClienteTable;
import com.warning.alert.AlertMsg;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import static com.db.bank.Banco.connection; | 5,223 | package com.session.employee;
public class employeeClientController implements Initializable {
// Ações para troca de cena
@FXML
protected void MainAction(MouseEvent e) {
if (AlertMsg.msgConfirm("Confimar Logout","Deseja sair para a página de login?")) {
Main.changedScene("main");
}
}
@FXML
protected void MedOrderAction(MouseEvent e) {
Main.changedScene("medOrder");
}
@FXML
protected void SaleAction(MouseEvent e) {
Main.changedScene("sale");
}
@FXML
protected void ClientAction(MouseEvent e) {
Main.changedScene("ClientAdmFunc");
}
// Predefinição da instância banco
Banco banco = new Banco();
// GUI IDs
@FXML
private TableView tbCliente;
@FXML
private TableColumn clIdcli;
@FXML
private TableColumn clNomecli;
@FXML
private TableColumn clSobrenomeli;
@FXML
private TableColumn clUsuario;
@FXML
private TableColumn clFoneCli;
@FXML
private TextField tfNome;
@FXML
private TextField tfSobrenome;
@FXML
private TextField tfUser;
@FXML
private TextField tfFone;
@FXML
private TextField tfId;
@FXML
private TextField tfSearch;
// Show The Client Table
public void tabelacliente()throws SQLException {
List<ClienteTable> clientes = new ArrayList<>();
String consultaSQLcliente = "SELECT * FROM cliente"; | package com.session.employee;
public class employeeClientController implements Initializable {
// Ações para troca de cena
@FXML
protected void MainAction(MouseEvent e) {
if (AlertMsg.msgConfirm("Confimar Logout","Deseja sair para a página de login?")) {
Main.changedScene("main");
}
}
@FXML
protected void MedOrderAction(MouseEvent e) {
Main.changedScene("medOrder");
}
@FXML
protected void SaleAction(MouseEvent e) {
Main.changedScene("sale");
}
@FXML
protected void ClientAction(MouseEvent e) {
Main.changedScene("ClientAdmFunc");
}
// Predefinição da instância banco
Banco banco = new Banco();
// GUI IDs
@FXML
private TableView tbCliente;
@FXML
private TableColumn clIdcli;
@FXML
private TableColumn clNomecli;
@FXML
private TableColumn clSobrenomeli;
@FXML
private TableColumn clUsuario;
@FXML
private TableColumn clFoneCli;
@FXML
private TextField tfNome;
@FXML
private TextField tfSobrenome;
@FXML
private TextField tfUser;
@FXML
private TextField tfFone;
@FXML
private TextField tfId;
@FXML
private TextField tfSearch;
// Show The Client Table
public void tabelacliente()throws SQLException {
List<ClienteTable> clientes = new ArrayList<>();
String consultaSQLcliente = "SELECT * FROM cliente"; | Statement statement = connection.createStatement(); | 4 | 2023-11-16 14:55:08+00:00 | 8k |
wzh933/Buffer-Manager | src/main/java/cs/adb/wzh/dataStorageManager/DSMgr.java | [
{
"identifier": "Buffer",
"path": "src/main/java/cs/adb/wzh/Storage/Buffer.java",
"snippet": "public class Buffer {\n private final int bufSize;\n private final Frame[] buf;\n\n public int getBufSize() {\n return bufSize;\n }\n\n public Frame[] getBuf() {\n return buf;\n ... | import cs.adb.wzh.Storage.Buffer;
import cs.adb.wzh.Storage.Disk;
import cs.adb.wzh.Storage.File;
import cs.adb.wzh.StorageForm.Frame;
import cs.adb.wzh.StorageForm.Page;
import cs.adb.wzh.bufferManager.BMgr;
import java.io.IOException;
import java.util.Arrays; | 5,826 | package cs.adb.wzh.dataStorageManager;
/**
* @author Wang Zihui
* @date 2023/11/12
**/
public class DSMgr {
private final int maxPageNum;
private int pageNum = 0;//开始时被固定的页面数位0
private final int[] pages;
private int curRecordId;
private File curFile; | package cs.adb.wzh.dataStorageManager;
/**
* @author Wang Zihui
* @date 2023/11/12
**/
public class DSMgr {
private final int maxPageNum;
private int pageNum = 0;//开始时被固定的页面数位0
private final int[] pages;
private int curRecordId;
private File curFile; | private final Buffer bf; | 0 | 2023-11-15 16:30:06+00:00 | 8k |
UselessBullets/DragonFly | src/main/java/useless/dragonfly/model/block/BlockModelDragonFly.java | [
{
"identifier": "DragonFly",
"path": "src/main/java/useless/dragonfly/DragonFly.java",
"snippet": "public class DragonFly implements GameStartEntrypoint {\n public static final String MOD_ID = \"dragonfly\";\n public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);\n\tpublic static fi... | import net.minecraft.client.Minecraft;
import net.minecraft.client.render.block.model.BlockModelRenderBlocks;
import net.minecraft.core.block.Block;
import net.minecraft.core.world.WorldSource;
import useless.dragonfly.DragonFly;
import useless.dragonfly.helper.ModelHelper;
import useless.dragonfly.mixins.mixin.accessor.RenderBlocksAccessor;
import useless.dragonfly.model.block.processed.BlockModel;
import useless.dragonfly.model.blockstates.data.BlockstateData;
import useless.dragonfly.model.blockstates.data.ModelPart;
import useless.dragonfly.model.blockstates.data.VariantData;
import useless.dragonfly.model.blockstates.processed.MetaStateInterpreter;
import useless.dragonfly.utilities.NamespaceId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | 4,444 | package useless.dragonfly.model.block;
public class BlockModelDragonFly extends BlockModelRenderBlocks {
public BlockModel baseModel;
public boolean render3d;
public float renderScale;
public BlockstateData blockstateData;
public MetaStateInterpreter metaStateInterpreter;
public BlockModelDragonFly(BlockModel model) {
this(model, null, null,true, 0.25f);
}
public BlockModelDragonFly(BlockModel model, BlockstateData blockstateData, MetaStateInterpreter metaStateInterpreter, boolean render3d) {
this(model, blockstateData, metaStateInterpreter, render3d, 0.25f);
}
public BlockModelDragonFly(BlockModel model, BlockstateData blockstateData, MetaStateInterpreter metaStateInterpreter, boolean render3d, float renderScale) {
super(0);
this.baseModel = model;
this.render3d = render3d;
this.renderScale = renderScale;
this.blockstateData = blockstateData;
this.metaStateInterpreter = metaStateInterpreter;
}
@Override
public boolean render(Block block, int x, int y, int z) {
InternalModel[] models = getModelsFromState(block, x, y, z, false);
boolean didRender = false;
for (InternalModel model : models) {
didRender |= BlockModelRenderer.renderModelNormal(model.model, block, x, y, z, model.rotationX, -model.rotationY);
}
return didRender;
}
@Override
public boolean renderNoCulling(Block block, int x, int y, int z) {
InternalModel[] models = getModelsFromState(block, x, y, z, false);
boolean didRender = false;
for (InternalModel model : models) {
didRender |= BlockModelRenderer.renderModelNoCulling(model.model, block, x, y, z, model.rotationX, -model.rotationY);
}
return didRender;
}
@Override
public boolean renderWithOverrideTexture(Block block, int x, int y, int z, int textureIndex) {
InternalModel[] models = getModelsFromState(block, x, y, z, false);
boolean didRender = false;
for (InternalModel model : models) {
didRender |= BlockModelRenderer.renderModelBlockUsingTexture(model.model, block, x, y, z, textureIndex, model.rotationX, -model.rotationY);
}
return didRender;
}
@Override
public boolean shouldItemRender3d() {
return render3d;
}
@Override
public float getItemRenderScale() {
return renderScale;
}
public InternalModel[] getModelsFromState(Block block, int x, int y, int z, boolean sourceFromWorld){
if (blockstateData == null || metaStateInterpreter == null){
return new InternalModel[]{new InternalModel(baseModel, 0, 0)};
} | package useless.dragonfly.model.block;
public class BlockModelDragonFly extends BlockModelRenderBlocks {
public BlockModel baseModel;
public boolean render3d;
public float renderScale;
public BlockstateData blockstateData;
public MetaStateInterpreter metaStateInterpreter;
public BlockModelDragonFly(BlockModel model) {
this(model, null, null,true, 0.25f);
}
public BlockModelDragonFly(BlockModel model, BlockstateData blockstateData, MetaStateInterpreter metaStateInterpreter, boolean render3d) {
this(model, blockstateData, metaStateInterpreter, render3d, 0.25f);
}
public BlockModelDragonFly(BlockModel model, BlockstateData blockstateData, MetaStateInterpreter metaStateInterpreter, boolean render3d, float renderScale) {
super(0);
this.baseModel = model;
this.render3d = render3d;
this.renderScale = renderScale;
this.blockstateData = blockstateData;
this.metaStateInterpreter = metaStateInterpreter;
}
@Override
public boolean render(Block block, int x, int y, int z) {
InternalModel[] models = getModelsFromState(block, x, y, z, false);
boolean didRender = false;
for (InternalModel model : models) {
didRender |= BlockModelRenderer.renderModelNormal(model.model, block, x, y, z, model.rotationX, -model.rotationY);
}
return didRender;
}
@Override
public boolean renderNoCulling(Block block, int x, int y, int z) {
InternalModel[] models = getModelsFromState(block, x, y, z, false);
boolean didRender = false;
for (InternalModel model : models) {
didRender |= BlockModelRenderer.renderModelNoCulling(model.model, block, x, y, z, model.rotationX, -model.rotationY);
}
return didRender;
}
@Override
public boolean renderWithOverrideTexture(Block block, int x, int y, int z, int textureIndex) {
InternalModel[] models = getModelsFromState(block, x, y, z, false);
boolean didRender = false;
for (InternalModel model : models) {
didRender |= BlockModelRenderer.renderModelBlockUsingTexture(model.model, block, x, y, z, textureIndex, model.rotationX, -model.rotationY);
}
return didRender;
}
@Override
public boolean shouldItemRender3d() {
return render3d;
}
@Override
public float getItemRenderScale() {
return renderScale;
}
public InternalModel[] getModelsFromState(Block block, int x, int y, int z, boolean sourceFromWorld){
if (blockstateData == null || metaStateInterpreter == null){
return new InternalModel[]{new InternalModel(baseModel, 0, 0)};
} | RenderBlocksAccessor blocksAccessor = (RenderBlocksAccessor) BlockModelRenderer.getRenderBlocks(); | 2 | 2023-11-16 01:10:52+00:00 | 8k |
AntonyCheng/ai-bi | src/main/java/top/sharehome/springbootinittemplate/utils/redisson/lock/LockUtils.java | [
{
"identifier": "ReturnCode",
"path": "src/main/java/top/sharehome/springbootinittemplate/common/base/ReturnCode.java",
"snippet": "@Getter\npublic enum ReturnCode {\n\n /**\n * 操作成功 200\n */\n SUCCESS(HttpStatus.SUCCESS, \"操作成功\"),\n\n /**\n * 操作失败 500\n */\n FAIL(HttpStatus... | import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import top.sharehome.springbootinittemplate.common.base.ReturnCode;
import top.sharehome.springbootinittemplate.config.bean.SpringContextHolder;
import top.sharehome.springbootinittemplate.exception.customize.CustomizeLockException;
import top.sharehome.springbootinittemplate.utils.redisson.KeyPrefixConstants;
import top.sharehome.springbootinittemplate.utils.redisson.lock.function.SuccessFunction;
import top.sharehome.springbootinittemplate.utils.redisson.lock.function.VoidFunction;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier; | 4,838 | package top.sharehome.springbootinittemplate.utils.redisson.lock;
/**
* 分布式锁工具类
* 工具类中包含三种情况,在使用时针对同一业务逻辑或线程建议采纳相同的情况:
* 1、无论获取锁成功与否均无返回值
* 2、无论获取锁成功与否均带有boolean类型返回值
* 3、无论获取锁成功与否均带有自定义类型返回值
* 使用该工具类之前需要了解工具类中所设计和涉及的一些概念:
* 1、看门狗释放:看门狗是Redisson分布式锁中设计的一个防宕机死锁机制,宕机死锁指获取锁之后程序没有释放锁就停止运行而导致其他程序拿不到锁的情况,
* 看门狗机制就起到一个监听程序健康状态的作用,默认宕机30秒后自动释放锁。
* 2、自动释放:自动释放需要靠开发者自定义自动释放时间,只要没有设定该时间,那么这个锁就采用看门狗释放,自动释放的存在可提高代码可自定义性,但是
* 容易产生异常,比如A、B线程均需要运行10s,A线程先运行,B线程等待锁,在5s时A线程自动释放了锁,B线程立即拿到锁开始运行,在10s时A结束运行,工
* 具类代码逻辑要求A线程释放锁,但是锁在B线程上,所以就会报出异常,或许一些业务需要以上所描述的逻辑,但是这里为了保持以锁为中心的工具类,强制要
* 求获取锁和释放锁必须在同一线程中操作,即A线程不能释放B线程的锁,如果开发者诚心想实现上述逻辑,请自己编写相关代码,建议使用Redisson缓存或者
* 延迟队列。
* 3、同步等待:同步等待主要针对于“无论获取锁成功与否均无返回值”的情况,因为通过传参没有判断处理该线程是否获取得到锁,所以使用此类方法,多个线程
* 是同步执行的,执行次序取决于线程抢占锁的能力,越强越先执行。
* 4、不可等待:不可等待主要针对于“无论获取锁成功与否均带有自定义/boolean类型返回值”中不含有waitTime形参的情况,其实它是同步等待的一种,只不
* 过此类方法能够处理或者忽略没获取到锁的情况,即拿不到锁就不拿,所以不用等待锁也能执行业务逻辑。
* 5、自定义等待:自定义等待主要针对于“无论获取锁成功与否均带有自定义/boolean类型返回值”中含有waitTime形参的情况,主要是考虑到网络原因和其他
* 外部因素,如果比较偏向于获取锁成功所要执行的操作,可以在此类方法中设置合理的等待时间,总之自定义等待完全依赖业务逻辑的需求。
*
* @author AntonyCheng
*/
@Slf4j
public class LockUtils {
/**
* 被封装的redisson客户端对象
*/
private static final RedissonClient REDISSON_CLIENT = SpringContextHolder.getBean(RedissonClient.class);
/**
* 无论获取锁成功与否均无返回值,看门狗释放型,同步等待分布式锁
*
* @param key 锁键值
* @param eventFunc 获取锁之后的操作
*/
public static void lockEvent(String key, VoidFunction eventFunc) {
RLock lock = REDISSON_CLIENT.getLock(KeyPrefixConstants.LOCK_PREFIX + key);
try {
lock.lock();
eventFunc.method();
} finally {
if (lock.isLocked()) {
lock.unlock();
}
}
}
/**
* 无论获取锁成功与否均无返回值,自动释放型,同步等待分布式锁
*
* @param key 锁键值
* @param leaseTime 自动释放时间/ms
* @param eventFunc 执行的操作
*/
public static void lockEvent(String key, long leaseTime, VoidFunction eventFunc) {
RLock lock = REDISSON_CLIENT.getLock(KeyPrefixConstants.LOCK_PREFIX + key);
try {
lock.lock(leaseTime, TimeUnit.MILLISECONDS);
eventFunc.method();
} finally {
if (lock.isLocked()) {
lock.unlock();
}
}
}
/**
* 无论获取锁成功与否均带有boolean类型返回值,看门狗释放型,不可等待分布式锁
*
* @param key 锁键值
* @param success 获取锁成功的操作
* @return 返回结果
*/
public static boolean lockEvent(String key, SuccessFunction success) {
RLock lock = REDISSON_CLIENT.getLock(KeyPrefixConstants.LOCK_PREFIX + key);
boolean lockResult = false;
try {
lockResult = lock.tryLock();
if (lockResult) {
success.method();
}
} finally {
if (lockResult) {
if (lock.isLocked()) {
lock.unlock();
}
}
}
return lockResult;
}
/**
* 无论获取锁成功与否均带有boolean类型返回值,看门狗释放型,自定义等待分布式锁
*
* @param key 锁键值
* @param waitTime 最大等待时间/ms
* @param success 获取锁成功的操作
* @return 返回结果
*/
public static boolean lockEvent(String key, long waitTime, SuccessFunction success) {
RLock lock = REDISSON_CLIENT.getLock(KeyPrefixConstants.LOCK_PREFIX + key);
boolean lockResult = false;
try {
lockResult = lock.tryLock(waitTime, TimeUnit.MILLISECONDS);
if (lockResult) {
success.method();
}
} catch (InterruptedException e) { | package top.sharehome.springbootinittemplate.utils.redisson.lock;
/**
* 分布式锁工具类
* 工具类中包含三种情况,在使用时针对同一业务逻辑或线程建议采纳相同的情况:
* 1、无论获取锁成功与否均无返回值
* 2、无论获取锁成功与否均带有boolean类型返回值
* 3、无论获取锁成功与否均带有自定义类型返回值
* 使用该工具类之前需要了解工具类中所设计和涉及的一些概念:
* 1、看门狗释放:看门狗是Redisson分布式锁中设计的一个防宕机死锁机制,宕机死锁指获取锁之后程序没有释放锁就停止运行而导致其他程序拿不到锁的情况,
* 看门狗机制就起到一个监听程序健康状态的作用,默认宕机30秒后自动释放锁。
* 2、自动释放:自动释放需要靠开发者自定义自动释放时间,只要没有设定该时间,那么这个锁就采用看门狗释放,自动释放的存在可提高代码可自定义性,但是
* 容易产生异常,比如A、B线程均需要运行10s,A线程先运行,B线程等待锁,在5s时A线程自动释放了锁,B线程立即拿到锁开始运行,在10s时A结束运行,工
* 具类代码逻辑要求A线程释放锁,但是锁在B线程上,所以就会报出异常,或许一些业务需要以上所描述的逻辑,但是这里为了保持以锁为中心的工具类,强制要
* 求获取锁和释放锁必须在同一线程中操作,即A线程不能释放B线程的锁,如果开发者诚心想实现上述逻辑,请自己编写相关代码,建议使用Redisson缓存或者
* 延迟队列。
* 3、同步等待:同步等待主要针对于“无论获取锁成功与否均无返回值”的情况,因为通过传参没有判断处理该线程是否获取得到锁,所以使用此类方法,多个线程
* 是同步执行的,执行次序取决于线程抢占锁的能力,越强越先执行。
* 4、不可等待:不可等待主要针对于“无论获取锁成功与否均带有自定义/boolean类型返回值”中不含有waitTime形参的情况,其实它是同步等待的一种,只不
* 过此类方法能够处理或者忽略没获取到锁的情况,即拿不到锁就不拿,所以不用等待锁也能执行业务逻辑。
* 5、自定义等待:自定义等待主要针对于“无论获取锁成功与否均带有自定义/boolean类型返回值”中含有waitTime形参的情况,主要是考虑到网络原因和其他
* 外部因素,如果比较偏向于获取锁成功所要执行的操作,可以在此类方法中设置合理的等待时间,总之自定义等待完全依赖业务逻辑的需求。
*
* @author AntonyCheng
*/
@Slf4j
public class LockUtils {
/**
* 被封装的redisson客户端对象
*/
private static final RedissonClient REDISSON_CLIENT = SpringContextHolder.getBean(RedissonClient.class);
/**
* 无论获取锁成功与否均无返回值,看门狗释放型,同步等待分布式锁
*
* @param key 锁键值
* @param eventFunc 获取锁之后的操作
*/
public static void lockEvent(String key, VoidFunction eventFunc) {
RLock lock = REDISSON_CLIENT.getLock(KeyPrefixConstants.LOCK_PREFIX + key);
try {
lock.lock();
eventFunc.method();
} finally {
if (lock.isLocked()) {
lock.unlock();
}
}
}
/**
* 无论获取锁成功与否均无返回值,自动释放型,同步等待分布式锁
*
* @param key 锁键值
* @param leaseTime 自动释放时间/ms
* @param eventFunc 执行的操作
*/
public static void lockEvent(String key, long leaseTime, VoidFunction eventFunc) {
RLock lock = REDISSON_CLIENT.getLock(KeyPrefixConstants.LOCK_PREFIX + key);
try {
lock.lock(leaseTime, TimeUnit.MILLISECONDS);
eventFunc.method();
} finally {
if (lock.isLocked()) {
lock.unlock();
}
}
}
/**
* 无论获取锁成功与否均带有boolean类型返回值,看门狗释放型,不可等待分布式锁
*
* @param key 锁键值
* @param success 获取锁成功的操作
* @return 返回结果
*/
public static boolean lockEvent(String key, SuccessFunction success) {
RLock lock = REDISSON_CLIENT.getLock(KeyPrefixConstants.LOCK_PREFIX + key);
boolean lockResult = false;
try {
lockResult = lock.tryLock();
if (lockResult) {
success.method();
}
} finally {
if (lockResult) {
if (lock.isLocked()) {
lock.unlock();
}
}
}
return lockResult;
}
/**
* 无论获取锁成功与否均带有boolean类型返回值,看门狗释放型,自定义等待分布式锁
*
* @param key 锁键值
* @param waitTime 最大等待时间/ms
* @param success 获取锁成功的操作
* @return 返回结果
*/
public static boolean lockEvent(String key, long waitTime, SuccessFunction success) {
RLock lock = REDISSON_CLIENT.getLock(KeyPrefixConstants.LOCK_PREFIX + key);
boolean lockResult = false;
try {
lockResult = lock.tryLock(waitTime, TimeUnit.MILLISECONDS);
if (lockResult) {
success.method();
}
} catch (InterruptedException e) { | throw new CustomizeLockException(ReturnCode.LOCK_SERVICE_ERROR); | 2 | 2023-11-12 07:49:59+00:00 | 8k |
rmheuer/azalea | azalea-core/src/main/java/com/github/rmheuer/azalea/render2d/VertexBatch.java | [
{
"identifier": "AttribType",
"path": "azalea-core/src/main/java/com/github/rmheuer/azalea/render/mesh/AttribType.java",
"snippet": "public enum AttribType {\n /** GLSL {@code float} */\n FLOAT(1),\n /** GLSL {@code vec2} */\n VEC2(2),\n /** GLSL {@code vec3} */\n VEC3(3),\n /** GLS... | import com.github.rmheuer.azalea.render.mesh.AttribType;
import com.github.rmheuer.azalea.render.mesh.MeshData;
import com.github.rmheuer.azalea.render.mesh.PrimitiveType;
import com.github.rmheuer.azalea.render.mesh.VertexLayout;
import com.github.rmheuer.azalea.render.texture.Texture2D;
import com.github.rmheuer.azalea.render.texture.Texture2DRegion;
import java.util.List; | 4,141 | package com.github.rmheuer.azalea.render2d;
/**
* A batch of vertices to draw.
*/
final class VertexBatch {
/**
* The layout of the generated vertex data.
*/
public static final VertexLayout LAYOUT = new VertexLayout( | package com.github.rmheuer.azalea.render2d;
/**
* A batch of vertices to draw.
*/
final class VertexBatch {
/**
* The layout of the generated vertex data.
*/
public static final VertexLayout LAYOUT = new VertexLayout( | AttribType.VEC3, // Position | 0 | 2023-11-16 04:46:53+00:00 | 8k |
Shushandr/offroad | src/net/osmand/map/WorldRegion.java | [
{
"identifier": "LatLon",
"path": "src/net/osmand/data/LatLon.java",
"snippet": "@XmlRootElement\npublic class LatLon implements Serializable {\n\tpublic void setLongitude(double pLongitude) {\n\t\tlongitude = pLongitude;\n\t}\n\n\tpublic void setLatitude(double pLatitude) {\n\t\tlatitude = pLatitude;\n... | import net.osmand.data.LatLon;
import net.osmand.util.Algorithms;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List; | 5,606 | package net.osmand.map;
public class WorldRegion implements Serializable {
public static final String WORLD_BASEMAP = "world_basemap";
public static final String AFRICA_REGION_ID = "africa";
public static final String ASIA_REGION_ID = "asia";
public static final String AUSTRALIA_AND_OCEANIA_REGION_ID = "australia-oceania";
public static final String CENTRAL_AMERICA_REGION_ID = "centralamerica";
public static final String EUROPE_REGION_ID = "europe";
public static final String NORTH_AMERICA_REGION_ID = "northamerica";
public static final String RUSSIA_REGION_ID = "russia";
public static final String JAPAN_REGION_ID = "japan_asia";
public static final String SOUTH_AMERICA_REGION_ID = "southamerica";
protected static final String WORLD = "world";
// Just a string constant
public static final String UNITED_KINGDOM_REGION_ID = "gb_europe";
// Hierarchy
protected WorldRegion superregion;
protected List<WorldRegion> subregions;
// filled by osmand regions
protected RegionParams params = new RegionParams();
protected String regionFullName;
protected String regionParentFullName;
protected String regionName;
protected String regionNameEn;
protected String regionNameLocale;
protected String regionSearchText;
protected String regionDownloadName;
protected boolean regionMapDownload; | package net.osmand.map;
public class WorldRegion implements Serializable {
public static final String WORLD_BASEMAP = "world_basemap";
public static final String AFRICA_REGION_ID = "africa";
public static final String ASIA_REGION_ID = "asia";
public static final String AUSTRALIA_AND_OCEANIA_REGION_ID = "australia-oceania";
public static final String CENTRAL_AMERICA_REGION_ID = "centralamerica";
public static final String EUROPE_REGION_ID = "europe";
public static final String NORTH_AMERICA_REGION_ID = "northamerica";
public static final String RUSSIA_REGION_ID = "russia";
public static final String JAPAN_REGION_ID = "japan_asia";
public static final String SOUTH_AMERICA_REGION_ID = "southamerica";
protected static final String WORLD = "world";
// Just a string constant
public static final String UNITED_KINGDOM_REGION_ID = "gb_europe";
// Hierarchy
protected WorldRegion superregion;
protected List<WorldRegion> subregions;
// filled by osmand regions
protected RegionParams params = new RegionParams();
protected String regionFullName;
protected String regionParentFullName;
protected String regionName;
protected String regionNameEn;
protected String regionNameLocale;
protected String regionSearchText;
protected String regionDownloadName;
protected boolean regionMapDownload; | protected LatLon regionCenter; | 0 | 2023-11-15 05:04:55+00:00 | 8k |
orijer/IvritInterpreter | src/Evaluation/VariableValueSwapper.java | [
{
"identifier": "UnevenBracketsException",
"path": "src/IvritExceptions/InterpreterExceptions/EvaluatorExceptions/UnevenBracketsException.java",
"snippet": "public class UnevenBracketsException extends UncheckedIOException{\r\n public UnevenBracketsException(String str) {\r\n super(\"נמצאה שגי... | import java.io.IOException;
import java.io.UncheckedIOException;
import IvritExceptions.InterpreterExceptions.EvaluatorExceptions.UnevenBracketsException;
import Variables.BooleanVariable;
import Variables.FloatVariable;
import Variables.IntegerVariable;
import Variables.NumericVariable;
import Variables.VariablesController;
| 5,126 | package Evaluation;
/**
* Handles switching the variables with their values for the evaluation.
*/
public class VariableValueSwapper {
//Contains the variables of the program:
private VariablesController variablesController;
/**
* Constructor.
* @param variablesController - The object that handles the variables of the program.
*/
public VariableValueSwapper(VariablesController variablesController) {
this.variablesController = variablesController;
}
/**
* Reads through a given data string and switches every occurence of a variable with its correct value.
* @param data - The data to process.
* @return a new string that is similar to the given string, but every occurence of a variable is switched with its value.
*/
public String swap(String originalData) {
String data = originalData; //We want to keep the original data to be used when throwing an exception.
StringBuilder swappedLine = new StringBuilder();
int endAt;
while (data.length() > 0) {
char firstChar = data.charAt(0);
if (firstChar == '"') {
data = copyStringLiteral(data, swappedLine, originalData);
} else if (firstChar == ' ' || isBracket(firstChar) || NumericVariable.isNumericOperator(firstChar)) {
//We are reading a space, a bracket, or an operator, just copy it:
swappedLine.append(firstChar);
data = data.substring(1);
} else if ((endAt = BooleanVariable.startsWithBooleanOperator(data)) > 0) {
//We are reading a boolean operator:
swappedLine.append(data.substring(0, endAt));
data = data.substring(endAt);
} else {
//We are reading a literal (non-string) value or a variable:
endAt = dataEndAt(data);
String literalValueOrVariable = data.substring(0, endAt);
if (this.variablesController.isVariable(literalValueOrVariable)) {
//If it is a variable, switch it with its value:
swappedLine.append(this.variablesController.getVariableValue(literalValueOrVariable));
} else {
//If it is literal data, try to copy it:
copyNonStringLiteral(literalValueOrVariable, swappedLine);
}
data = data.substring(endAt);
}
}
return swappedLine.toString();
}
/**
* If given a valid string literal, add its value to the given StringBuilder,
* and return the data without the string literal that was found.
* @param data - The data that should start with a string literal.
* @param swappedLine - The StringBuilder we build the evaluated result in.
* @return a substring of the given data string that starts after the string literal that was found.
*/
private String copyStringLiteral(String data, StringBuilder swappedLine, String originalData) {
int endAt = data.indexOf('"', 1);
if (endAt == -1) {
throw new UnevenBracketsException(originalData);
}
swappedLine.append(data.substring(0, endAt + 1));
return data.substring(endAt + 1);
}
/**
* Copies a non string literal to the given StringBuilder, if it's valid (an actual value of a variable type).
* @param literalData - The data that should be a literal of a certain variable type.
* @param swappedLine - The string Builder we build the evaluaed result in.
*/
private void copyNonStringLiteral(String literalData, StringBuilder swappedLine) {
if (BooleanVariable.isBooleanValue(literalData)
|| IntegerVariable.isIntegerValue(literalData)
| package Evaluation;
/**
* Handles switching the variables with their values for the evaluation.
*/
public class VariableValueSwapper {
//Contains the variables of the program:
private VariablesController variablesController;
/**
* Constructor.
* @param variablesController - The object that handles the variables of the program.
*/
public VariableValueSwapper(VariablesController variablesController) {
this.variablesController = variablesController;
}
/**
* Reads through a given data string and switches every occurence of a variable with its correct value.
* @param data - The data to process.
* @return a new string that is similar to the given string, but every occurence of a variable is switched with its value.
*/
public String swap(String originalData) {
String data = originalData; //We want to keep the original data to be used when throwing an exception.
StringBuilder swappedLine = new StringBuilder();
int endAt;
while (data.length() > 0) {
char firstChar = data.charAt(0);
if (firstChar == '"') {
data = copyStringLiteral(data, swappedLine, originalData);
} else if (firstChar == ' ' || isBracket(firstChar) || NumericVariable.isNumericOperator(firstChar)) {
//We are reading a space, a bracket, or an operator, just copy it:
swappedLine.append(firstChar);
data = data.substring(1);
} else if ((endAt = BooleanVariable.startsWithBooleanOperator(data)) > 0) {
//We are reading a boolean operator:
swappedLine.append(data.substring(0, endAt));
data = data.substring(endAt);
} else {
//We are reading a literal (non-string) value or a variable:
endAt = dataEndAt(data);
String literalValueOrVariable = data.substring(0, endAt);
if (this.variablesController.isVariable(literalValueOrVariable)) {
//If it is a variable, switch it with its value:
swappedLine.append(this.variablesController.getVariableValue(literalValueOrVariable));
} else {
//If it is literal data, try to copy it:
copyNonStringLiteral(literalValueOrVariable, swappedLine);
}
data = data.substring(endAt);
}
}
return swappedLine.toString();
}
/**
* If given a valid string literal, add its value to the given StringBuilder,
* and return the data without the string literal that was found.
* @param data - The data that should start with a string literal.
* @param swappedLine - The StringBuilder we build the evaluated result in.
* @return a substring of the given data string that starts after the string literal that was found.
*/
private String copyStringLiteral(String data, StringBuilder swappedLine, String originalData) {
int endAt = data.indexOf('"', 1);
if (endAt == -1) {
throw new UnevenBracketsException(originalData);
}
swappedLine.append(data.substring(0, endAt + 1));
return data.substring(endAt + 1);
}
/**
* Copies a non string literal to the given StringBuilder, if it's valid (an actual value of a variable type).
* @param literalData - The data that should be a literal of a certain variable type.
* @param swappedLine - The string Builder we build the evaluaed result in.
*/
private void copyNonStringLiteral(String literalData, StringBuilder swappedLine) {
if (BooleanVariable.isBooleanValue(literalData)
|| IntegerVariable.isIntegerValue(literalData)
| || FloatVariable.isFloatValue(literalData)) {
| 2 | 2023-11-17 09:15:07+00:00 | 8k |
WuKongOpenSource/Wukong_HRM | hrm/hrm-web/src/main/java/com/kakarote/hrm/controller/HrmAchievementEmployeeAppraisalController.java | [
{
"identifier": "Result",
"path": "common/common-web/src/main/java/com/kakarote/core/common/Result.java",
"snippet": "public class Result<T> implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n @ApiModelProperty(value = \"code\", required = true, example = \"0\")\n ... | import com.kakarote.core.common.Result;
import com.kakarote.core.entity.BasePage;
import com.kakarote.hrm.common.EmployeeHolder;
import com.kakarote.hrm.constant.achievement.EmployeeAppraisalStatus;
import com.kakarote.hrm.entity.BO.*;
import com.kakarote.hrm.entity.VO.*;
import com.kakarote.hrm.service.IHrmAchievementEmployeeAppraisalService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map; | 4,882 | package com.kakarote.hrm.controller;
/**
* <p>
* 员工绩效考核 前端控制器
* </p>
*
* @author huangmingbo
* @since 2020-05-12
*/
@RestController
@RequestMapping("/hrmAchievementEmployeeAppraisal")
@Api(tags = "绩效考核-员工端")
public class HrmAchievementEmployeeAppraisalController {
@Autowired
private IHrmAchievementEmployeeAppraisalService employeeAppraisalService;
@PostMapping("/queryAppraisalNum")
@ApiOperation("查询员工绩效数量")
public Result<Map<Integer, Integer>> queryAppraisalNum() {
Map<Integer, Integer> map = employeeAppraisalService.queryAppraisalNum();
return Result.ok(map);
}
@PostMapping("/queryMyAppraisal")
@ApiOperation("查询我的绩效")
public Result<BasePage<QueryMyAppraisalVO>> queryMyAppraisal(@RequestBody BasePageBO basePageBO) {
BasePage<QueryMyAppraisalVO> list = employeeAppraisalService.queryMyAppraisal(basePageBO);
return Result.ok(list);
}
@PostMapping("/queryTargetConfirmList")
@ApiOperation("查询目标确认列表")
public Result<BasePage<TargetConfirmListVO>> queryTargetConfirmList(@RequestBody BasePageBO basePageBO) {
BasePage<TargetConfirmListVO> page = employeeAppraisalService.queryTargetConfirmList(basePageBO);
return Result.ok(page);
}
@PostMapping("/queryEvaluatoList")
@ApiOperation("查询结果评定列表")
public Result<BasePage<EvaluatoListVO>> queryEvaluatoList(@RequestBody EvaluatoListBO evaluatoListBO) {
BasePage<EvaluatoListVO> page = employeeAppraisalService.queryEvaluatoList(evaluatoListBO);
return Result.ok(page);
}
@PostMapping("/queryResultConfirmList")
@ApiOperation("查询结果确认列表")
public Result<BasePage<ResultConfirmListVO>> queryResultConfirmList(@RequestBody BasePageBO basePageBO) {
BasePage<ResultConfirmListVO> page = employeeAppraisalService.queryResultConfirmList(basePageBO);
return Result.ok(page);
}
@PostMapping("/queryEmployeeAppraisalDetail/{employeeAppraisalId}")
@ApiOperation("查询考核详情")
public Result<EmployeeAppraisalDetailVO> queryEmployeeAppraisalDetail(@PathVariable("employeeAppraisalId") Long employeeAppraisalId) {
EmployeeAppraisalDetailVO employeeAppraisalDetailVO = employeeAppraisalService.queryEmployeeAppraisalDetail(employeeAppraisalId);
return Result.ok(employeeAppraisalDetailVO);
}
@PostMapping("/writeAppraisal")
@ApiOperation("填写绩效")
public Result writeAppraisal(@RequestBody WriteAppraisalBO writeAppraisalBO) {
employeeAppraisalService.writeAppraisal(writeAppraisalBO);
return Result.ok();
}
@PostMapping("/targetConfirm")
@ApiOperation("目标确认")
public Result targetConfirm(@RequestBody TargetConfirmBO targetConfirmBO) {
employeeAppraisalService.targetConfirm(targetConfirmBO);
return Result.ok();
}
@PostMapping("/resultEvaluato")
@ApiOperation("结果评定")
public Result resultEvaluato(@RequestBody ResultEvaluatoBO resultEvaluatoBO) {
employeeAppraisalService.resultEvaluato(resultEvaluatoBO);
return Result.ok();
}
@PostMapping("/queryResultConfirmByAppraisalId/{appraisalId}")
@ApiOperation("绩效结果确认")
public Result<ResultConfirmByAppraisalIdVO> queryResultConfirmByAppraisalId(@PathVariable("appraisalId") Long appraisalId) {
ResultConfirmByAppraisalIdVO resultConfirmByAppraisalIdVO = employeeAppraisalService.queryResultConfirmByAppraisalId(appraisalId);
return Result.ok(resultConfirmByAppraisalIdVO);
}
@PostMapping("/updateScoreLevel")
@ApiOperation("修改考评分数")
public Result updateScoreLevel(@RequestBody UpdateScoreLevelBO updateScoreLevelBO) {
employeeAppraisalService.updateScoreLevel(updateScoreLevelBO);
return Result.ok();
}
@PostMapping("/resultConfirm/{appraisalId}")
@ApiOperation("结果确认")
public Result resultConfirm(@PathVariable("appraisalId") Long appraisalId) {
employeeAppraisalService.resultConfirm(appraisalId);
return Result.ok();
}
@PostMapping("/updateSchedule")
@ApiOperation("修改目标进度")
public Result updateSchedule(@RequestBody UpdateScheduleBO updateScheduleBO) {
employeeAppraisalService.updateSchedule(updateScheduleBO);
return Result.ok();
}
@PostMapping("/queryTargetConfirmScreen")
@ApiOperation("查询目标确认列表的绩效筛选条件")
public Result<List<AchievementAppraisalVO>> queryTargetConfirmScreen() { | package com.kakarote.hrm.controller;
/**
* <p>
* 员工绩效考核 前端控制器
* </p>
*
* @author huangmingbo
* @since 2020-05-12
*/
@RestController
@RequestMapping("/hrmAchievementEmployeeAppraisal")
@Api(tags = "绩效考核-员工端")
public class HrmAchievementEmployeeAppraisalController {
@Autowired
private IHrmAchievementEmployeeAppraisalService employeeAppraisalService;
@PostMapping("/queryAppraisalNum")
@ApiOperation("查询员工绩效数量")
public Result<Map<Integer, Integer>> queryAppraisalNum() {
Map<Integer, Integer> map = employeeAppraisalService.queryAppraisalNum();
return Result.ok(map);
}
@PostMapping("/queryMyAppraisal")
@ApiOperation("查询我的绩效")
public Result<BasePage<QueryMyAppraisalVO>> queryMyAppraisal(@RequestBody BasePageBO basePageBO) {
BasePage<QueryMyAppraisalVO> list = employeeAppraisalService.queryMyAppraisal(basePageBO);
return Result.ok(list);
}
@PostMapping("/queryTargetConfirmList")
@ApiOperation("查询目标确认列表")
public Result<BasePage<TargetConfirmListVO>> queryTargetConfirmList(@RequestBody BasePageBO basePageBO) {
BasePage<TargetConfirmListVO> page = employeeAppraisalService.queryTargetConfirmList(basePageBO);
return Result.ok(page);
}
@PostMapping("/queryEvaluatoList")
@ApiOperation("查询结果评定列表")
public Result<BasePage<EvaluatoListVO>> queryEvaluatoList(@RequestBody EvaluatoListBO evaluatoListBO) {
BasePage<EvaluatoListVO> page = employeeAppraisalService.queryEvaluatoList(evaluatoListBO);
return Result.ok(page);
}
@PostMapping("/queryResultConfirmList")
@ApiOperation("查询结果确认列表")
public Result<BasePage<ResultConfirmListVO>> queryResultConfirmList(@RequestBody BasePageBO basePageBO) {
BasePage<ResultConfirmListVO> page = employeeAppraisalService.queryResultConfirmList(basePageBO);
return Result.ok(page);
}
@PostMapping("/queryEmployeeAppraisalDetail/{employeeAppraisalId}")
@ApiOperation("查询考核详情")
public Result<EmployeeAppraisalDetailVO> queryEmployeeAppraisalDetail(@PathVariable("employeeAppraisalId") Long employeeAppraisalId) {
EmployeeAppraisalDetailVO employeeAppraisalDetailVO = employeeAppraisalService.queryEmployeeAppraisalDetail(employeeAppraisalId);
return Result.ok(employeeAppraisalDetailVO);
}
@PostMapping("/writeAppraisal")
@ApiOperation("填写绩效")
public Result writeAppraisal(@RequestBody WriteAppraisalBO writeAppraisalBO) {
employeeAppraisalService.writeAppraisal(writeAppraisalBO);
return Result.ok();
}
@PostMapping("/targetConfirm")
@ApiOperation("目标确认")
public Result targetConfirm(@RequestBody TargetConfirmBO targetConfirmBO) {
employeeAppraisalService.targetConfirm(targetConfirmBO);
return Result.ok();
}
@PostMapping("/resultEvaluato")
@ApiOperation("结果评定")
public Result resultEvaluato(@RequestBody ResultEvaluatoBO resultEvaluatoBO) {
employeeAppraisalService.resultEvaluato(resultEvaluatoBO);
return Result.ok();
}
@PostMapping("/queryResultConfirmByAppraisalId/{appraisalId}")
@ApiOperation("绩效结果确认")
public Result<ResultConfirmByAppraisalIdVO> queryResultConfirmByAppraisalId(@PathVariable("appraisalId") Long appraisalId) {
ResultConfirmByAppraisalIdVO resultConfirmByAppraisalIdVO = employeeAppraisalService.queryResultConfirmByAppraisalId(appraisalId);
return Result.ok(resultConfirmByAppraisalIdVO);
}
@PostMapping("/updateScoreLevel")
@ApiOperation("修改考评分数")
public Result updateScoreLevel(@RequestBody UpdateScoreLevelBO updateScoreLevelBO) {
employeeAppraisalService.updateScoreLevel(updateScoreLevelBO);
return Result.ok();
}
@PostMapping("/resultConfirm/{appraisalId}")
@ApiOperation("结果确认")
public Result resultConfirm(@PathVariable("appraisalId") Long appraisalId) {
employeeAppraisalService.resultConfirm(appraisalId);
return Result.ok();
}
@PostMapping("/updateSchedule")
@ApiOperation("修改目标进度")
public Result updateSchedule(@RequestBody UpdateScheduleBO updateScheduleBO) {
employeeAppraisalService.updateSchedule(updateScheduleBO);
return Result.ok();
}
@PostMapping("/queryTargetConfirmScreen")
@ApiOperation("查询目标确认列表的绩效筛选条件")
public Result<List<AchievementAppraisalVO>> queryTargetConfirmScreen() { | List<AchievementAppraisalVO> list = employeeAppraisalService.queryTargetConfirmScreen(EmployeeHolder.getEmployeeId(), EmployeeAppraisalStatus.PENDING_CONFIRMATION.getValue()); | 3 | 2023-10-17 05:49:52+00:00 | 8k |
WisdomShell/codeshell-intellij | src/main/java/com/codeshell/intellij/widget/CodeShellWidget.java | [
{
"identifier": "CodeShellStatus",
"path": "src/main/java/com/codeshell/intellij/enums/CodeShellStatus.java",
"snippet": "public enum CodeShellStatus {\n UNKNOWN(0, \"Unknown\"),\n OK(200, \"OK\"),\n BAD_REQUEST(400, \"Bad request/token\"),\n NOT_FOUND(404, \"404 Not found\"),\n TOO_MANY_... | import com.codeshell.intellij.enums.CodeShellStatus;
import com.codeshell.intellij.services.CodeShellCompleteService;
import com.codeshell.intellij.settings.CodeShellSettings;
import com.codeshell.intellij.utils.CodeGenHintRenderer;
import com.codeshell.intellij.utils.CodeShellIcons;
import com.codeshell.intellij.utils.CodeShellUtils;
import com.codeshell.intellij.utils.EditorUtils;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.event.*;
import com.intellij.openapi.editor.impl.EditorComponentImpl;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.NlsContexts;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.openapi.wm.StatusBar;
import com.intellij.openapi.wm.StatusBarWidget;
import com.intellij.openapi.wm.impl.status.EditorBasedWidget;
import com.intellij.util.Consumer;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Arrays;
import java.util.Objects;
import java.util.concurrent.CompletableFuture; | 6,754 | package com.codeshell.intellij.widget;
public class CodeShellWidget extends EditorBasedWidget
implements StatusBarWidget.Multiframe, StatusBarWidget.IconPresentation,
CaretListener, SelectionListener, BulkAwareDocumentListener.Simple, PropertyChangeListener {
public static final String ID = "CodeShellWidget";
public static final Key<String[]> SHELL_CODER_CODE_SUGGESTION = new Key<>("CodeShell Code Suggestion");
public static final Key<Integer> SHELL_CODER_POSITION = new Key<>("CodeShell Position");
public static boolean enableSuggestion = false;
protected CodeShellWidget(@NotNull Project project) {
super(project);
}
@Override
public @NonNls @NotNull String ID() {
return ID;
}
@Override
public StatusBarWidget copy() {
return new CodeShellWidget(getProject());
}
@Override
public @Nullable Icon getIcon() {
CodeShellCompleteService codeShell = ApplicationManager.getApplication().getService(CodeShellCompleteService.class);
CodeShellStatus status = CodeShellStatus.getStatusByCode(codeShell.getStatus());
if (status == CodeShellStatus.OK) {
return CodeShellSettings.getInstance().isSaytEnabled() ? CodeShellIcons.WidgetEnabled : CodeShellIcons.WidgetDisabled;
} else {
return CodeShellIcons.WidgetError;
}
}
@Override
public WidgetPresentation getPresentation() {
return this;
}
@Override
public @Nullable @NlsContexts.Tooltip String getTooltipText() {
StringBuilder toolTipText = new StringBuilder("CodeShell");
if (CodeShellSettings.getInstance().isSaytEnabled()) {
toolTipText.append(" enabled");
} else {
toolTipText.append(" disabled");
}
CodeShellCompleteService codeShell = ApplicationManager.getApplication().getService(CodeShellCompleteService.class);
int statusCode = codeShell.getStatus();
CodeShellStatus status = CodeShellStatus.getStatusByCode(statusCode);
switch (status) {
case OK:
if (CodeShellSettings.getInstance().isSaytEnabled()) {
toolTipText.append(" (Click to disable)");
} else {
toolTipText.append(" (Click to enable)");
}
break;
case UNKNOWN:
toolTipText.append(" (http error ");
toolTipText.append(statusCode);
toolTipText.append(")");
break;
default:
toolTipText.append(" (");
toolTipText.append(status.getDisplayValue());
toolTipText.append(")");
}
return toolTipText.toString();
}
@Override
public @Nullable Consumer<MouseEvent> getClickConsumer() {
return mouseEvent -> {
CodeShellSettings.getInstance().toggleSaytEnabled();
if (Objects.nonNull(myStatusBar)) {
myStatusBar.updateWidget(ID);
}
};
}
@Override
public void install(@NotNull StatusBar statusBar) {
super.install(statusBar);
EditorEventMulticaster multicaster = EditorFactory.getInstance().getEventMulticaster();
multicaster.addCaretListener(this, this);
multicaster.addSelectionListener(this, this);
multicaster.addDocumentListener(this, this);
KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener("focusOwner", this);
Disposer.register(this,
() -> KeyboardFocusManager.getCurrentKeyboardFocusManager().removePropertyChangeListener("focusOwner",
this)
);
}
private Editor getFocusOwnerEditor() {
Component component = getFocusOwnerComponent();
Editor editor = component instanceof EditorComponentImpl ? ((EditorComponentImpl) component).getEditor() : getEditor(); | package com.codeshell.intellij.widget;
public class CodeShellWidget extends EditorBasedWidget
implements StatusBarWidget.Multiframe, StatusBarWidget.IconPresentation,
CaretListener, SelectionListener, BulkAwareDocumentListener.Simple, PropertyChangeListener {
public static final String ID = "CodeShellWidget";
public static final Key<String[]> SHELL_CODER_CODE_SUGGESTION = new Key<>("CodeShell Code Suggestion");
public static final Key<Integer> SHELL_CODER_POSITION = new Key<>("CodeShell Position");
public static boolean enableSuggestion = false;
protected CodeShellWidget(@NotNull Project project) {
super(project);
}
@Override
public @NonNls @NotNull String ID() {
return ID;
}
@Override
public StatusBarWidget copy() {
return new CodeShellWidget(getProject());
}
@Override
public @Nullable Icon getIcon() {
CodeShellCompleteService codeShell = ApplicationManager.getApplication().getService(CodeShellCompleteService.class);
CodeShellStatus status = CodeShellStatus.getStatusByCode(codeShell.getStatus());
if (status == CodeShellStatus.OK) {
return CodeShellSettings.getInstance().isSaytEnabled() ? CodeShellIcons.WidgetEnabled : CodeShellIcons.WidgetDisabled;
} else {
return CodeShellIcons.WidgetError;
}
}
@Override
public WidgetPresentation getPresentation() {
return this;
}
@Override
public @Nullable @NlsContexts.Tooltip String getTooltipText() {
StringBuilder toolTipText = new StringBuilder("CodeShell");
if (CodeShellSettings.getInstance().isSaytEnabled()) {
toolTipText.append(" enabled");
} else {
toolTipText.append(" disabled");
}
CodeShellCompleteService codeShell = ApplicationManager.getApplication().getService(CodeShellCompleteService.class);
int statusCode = codeShell.getStatus();
CodeShellStatus status = CodeShellStatus.getStatusByCode(statusCode);
switch (status) {
case OK:
if (CodeShellSettings.getInstance().isSaytEnabled()) {
toolTipText.append(" (Click to disable)");
} else {
toolTipText.append(" (Click to enable)");
}
break;
case UNKNOWN:
toolTipText.append(" (http error ");
toolTipText.append(statusCode);
toolTipText.append(")");
break;
default:
toolTipText.append(" (");
toolTipText.append(status.getDisplayValue());
toolTipText.append(")");
}
return toolTipText.toString();
}
@Override
public @Nullable Consumer<MouseEvent> getClickConsumer() {
return mouseEvent -> {
CodeShellSettings.getInstance().toggleSaytEnabled();
if (Objects.nonNull(myStatusBar)) {
myStatusBar.updateWidget(ID);
}
};
}
@Override
public void install(@NotNull StatusBar statusBar) {
super.install(statusBar);
EditorEventMulticaster multicaster = EditorFactory.getInstance().getEventMulticaster();
multicaster.addCaretListener(this, this);
multicaster.addSelectionListener(this, this);
multicaster.addDocumentListener(this, this);
KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener("focusOwner", this);
Disposer.register(this,
() -> KeyboardFocusManager.getCurrentKeyboardFocusManager().removePropertyChangeListener("focusOwner",
this)
);
}
private Editor getFocusOwnerEditor() {
Component component = getFocusOwnerComponent();
Editor editor = component instanceof EditorComponentImpl ? ((EditorComponentImpl) component).getEditor() : getEditor(); | return Objects.nonNull(editor) && !editor.isDisposed() && EditorUtils.isMainEditor(editor) ? editor : null; | 6 | 2023-10-18 06:29:13+00:00 | 8k |
djkcyl/Shamrock | qqinterface/src/main/java/tencent/im/oidb/cmd0x5eb/oidb_0x5eb.java | [
{
"identifier": "ByteStringMicro",
"path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/ByteStringMicro.java",
"snippet": "public class ByteStringMicro {\n public static final ByteStringMicro EMPTY = null;\n\n public static ByteStringMicro copyFrom(String str, String str2) {\n return ... | import com.tencent.mobileqq.pb.ByteStringMicro;
import com.tencent.mobileqq.pb.MessageMicro;
import com.tencent.mobileqq.pb.PBBytesField;
import com.tencent.mobileqq.pb.PBField;
import com.tencent.mobileqq.pb.PBStringField;
import com.tencent.mobileqq.pb.PBUInt32Field;
import com.tencent.mobileqq.pb.PBUInt64Field; | 4,324 | public final PBUInt32Field uint32_input_status_flag;
public final PBUInt32Field uint32_lang1;
public final PBUInt32Field uint32_lang2;
public final PBUInt32Field uint32_lang3;
public final PBUInt32Field uint32_lflag;
public final PBUInt32Field uint32_lightalk_switch;
public final PBUInt32Field uint32_love_status;
public final PBUInt32Field uint32_mss_update_time;
public final PBUInt32Field uint32_music_ring_autoplay;
public final PBUInt32Field uint32_music_ring_redpoint;
public final PBUInt32Field uint32_music_ring_visible;
public final PBUInt32Field uint32_normal_night_mode_flag;
public final PBUInt32Field uint32_notify_on_like_ranking_list_flag;
public final PBUInt32Field uint32_notify_partake_like_ranking_list_flag;
public final PBUInt32Field uint32_oin;
public final PBUInt32Field uint32_online_status_avatar_switch;
public final PBUInt32Field uint32_plate_of_king_dan;
public final PBUInt32Field uint32_plate_of_king_dan_display_switch;
public final PBUInt32Field uint32_posterfont_id;
public final PBUInt32Field uint32_preload_disable_flag;
public final PBUInt32Field uint32_profession;
public final PBUInt32Field uint32_profile_age_visible;
public final PBUInt32Field uint32_profile_anonymous_answer_switch;
public final PBUInt32Field uint32_profile_birthday_visible;
public final PBUInt32Field uint32_profile_college_visible;
public final PBUInt32Field uint32_profile_company_visible;
public final PBUInt32Field uint32_profile_constellation_visible;
public final PBUInt32Field uint32_profile_dressup_switch;
public final PBUInt32Field uint32_profile_email_visible;
public final PBUInt32Field uint32_profile_hometown_visible;
public final PBUInt32Field uint32_profile_interest_switch;
public final PBUInt32Field uint32_profile_life_achievement_switch;
public final PBUInt32Field uint32_profile_location_visible;
public final PBUInt32Field uint32_profile_membership_and_rank;
public final PBUInt32Field uint32_profile_miniapp_switch;
public final PBUInt32Field uint32_profile_music_switch;
public final PBUInt32Field uint32_profile_musicbox_switch;
public final PBUInt32Field uint32_profile_personal_note_visible;
public final PBUInt32Field uint32_profile_personality_label_switch;
public final PBUInt32Field uint32_profile_present_switch;
public final PBUInt32Field uint32_profile_privilege;
public final PBUInt32Field uint32_profile_profession_visible;
public final PBUInt32Field uint32_profile_qqcard_switch;
public final PBUInt32Field uint32_profile_qqcircle_switch;
public final PBUInt32Field uint32_profile_sex_visible;
public final PBUInt32Field uint32_profile_show_idol_switch;
public final PBUInt32Field uint32_profile_splendid_switch;
public final PBUInt32Field uint32_profile_sticky_note_offline;
public final PBUInt32Field uint32_profile_sticky_note_switch;
public final PBUInt32Field uint32_profile_weishi_switch;
public final PBUInt32Field uint32_profile_wz_game_card_switch;
public final PBUInt32Field uint32_profile_wz_game_skin_switch;
public final PBUInt32Field uint32_pstn_c2c_call_time;
public final PBUInt32Field uint32_pstn_c2c_last_guide_recharge_time;
public final PBUInt32Field uint32_pstn_c2c_try_flag;
public final PBUInt32Field uint32_pstn_c2c_vip;
public final PBUInt32Field uint32_pstn_ever_c2c_vip;
public final PBUInt32Field uint32_pstn_ever_multi_vip;
public final PBUInt32Field uint32_pstn_multi_call_time;
public final PBUInt32Field uint32_pstn_multi_last_guide_recharge_time;
public final PBUInt32Field uint32_pstn_multi_try_flag;
public final PBUInt32Field uint32_pstn_multi_vip;
public final PBUInt32Field uint32_qq_assistant_switch;
public final PBUInt32Field uint32_req_font_effect_id;
public final PBUInt32Field uint32_req_global_ring_id;
public final PBUInt32Field uint32_req_invite2group_auto_agree_flag;
public final PBUInt32Field uint32_req_medalwall_flag;
public final PBUInt32Field uint32_req_push_notice_flag;
public final PBUInt32Field uint32_req_small_world_head_flag;
public final PBUInt32Field uint32_rsp_connections_switch_id;
public final PBUInt32Field uint32_rsp_listen_together_player_id;
public final PBUInt32Field uint32_rsp_qq_level_icon_type;
public final PBUInt32Field uint32_rsp_theme_font_id;
public final PBUInt32Field uint32_school_status_flag;
public final PBUInt32Field uint32_simple_ui_pref;
public final PBUInt32Field uint32_simple_ui_switch;
public final PBUInt32Field uint32_simple_update_time;
public final PBUInt32Field uint32_stranger_vote_switch;
public final PBUInt32Field uint32_subaccount_display_third_qq_flag;
public final PBUInt32Field uint32_subscribe_nearbyassistant_switch;
public final PBUInt32Field uint32_suspend_effect_id;
public final PBUInt32Field uint32_sync_C2C_message_switch;
public final PBUInt32Field uint32_torch_disable_flag;
public final PBUInt32Field uint32_torchbearer_flag;
public final PBUInt32Field uint32_troop_honor_rich_flag;
public final PBUInt32Field uint32_troop_lucky_character_switch;
public final PBUInt32Field uint32_troophonor_switch;
public final PBUInt32Field uint32_vas_colorring_id;
public final PBUInt32Field uint32_vas_diy_font_timestamp;
public final PBUInt32Field uint32_vas_emoticon_usage_info;
public final PBUInt32Field uint32_vas_face_id;
public final PBUInt32Field uint32_vas_font_id;
public final PBUInt32Field uint32_vas_magicfont_flag;
public final PBUInt32Field uint32_vas_pendant_diy_id;
public final PBUInt32Field uint32_vas_praise_id;
public final PBUInt32Field uint32_vas_voicebubble_id;
public final PBUInt32Field uint32_vip_flag;
public final PBUInt32Field uint32_zplan_add_frd;
public final PBUInt32Field uint32_zplan_cmshow_month_active_user;
public final PBUInt32Field uint32_zplan_master_show;
public final PBUInt32Field uint32_zplan_message_notice_switch;
public final PBUInt32Field uint32_zplan_open;
public final PBUInt32Field uint32_zplan_operators_network_switch;
public final PBUInt32Field uint32_zplan_profile_card_show;
public final PBUInt32Field uint32_zplan_qzone_show;
public final PBUInt32Field uint32_zplan_samestyle_asset_switch;
public final PBUInt32Field uint32_zplan_samestyle_package_switch;
public final PBUInt64Field uint64_face_addon_id;
public final PBUInt64Field uint64_game_appid;
public final PBUInt64Field uint64_game_last_login_time;
public final PBUInt64Field uint64_uin = PBField.initUInt64(0);
public final PBUInt32Field unit32_concise_mode_flag;
public final PBUInt32Field unit32_hide_camera_emoticon_flag;
public final PBUInt32Field unit32_hide_cm_show_emoticon_flag;
public final PBUInt32Field unit32_online_state_praise_notify;
public final PBBytesField zplan_appearanceKey;
public final PBUInt32Field zplan_appearanceKey_time;
public final PBUInt32Field zplan_avatar_gender;
public UdcUinData() { | package tencent.im.oidb.cmd0x5eb;
public class oidb_0x5eb {
public static final class UdcUinData extends MessageMicro<UdcUinData> {
public final PBBytesField bytes_basic_cli_flag;
public final PBBytesField bytes_basic_svr_flag;
public final PBBytesField bytes_birthday;
public final PBBytesField bytes_city;
public final PBBytesField bytes_city_id;
public final PBBytesField bytes_country;
public final PBBytesField bytes_full_age;
public final PBBytesField bytes_full_birthday;
public final PBBytesField bytes_mss1_service;
public final PBBytesField bytes_mss2_identity;
public final PBBytesField bytes_mss3_bitmapextra;
public final PBBytesField bytes_music_gene;
public final PBBytesField bytes_nick;
public final PBBytesField bytes_openid;
public final PBBytesField bytes_province;
public final PBBytesField bytes_req_vip_ext_id;
public final PBBytesField bytes_stranger_declare;
public final PBBytesField bytes_stranger_nick;
public final PBUInt32Field int32_history_num_flag;
public final PBUInt32Field roam_flag_qq_7day;
public final PBUInt32Field roam_flag_svip_2year;
public final PBUInt32Field roam_flag_svip_5year;
public final PBUInt32Field roam_flag_svip_forever;
public final PBUInt32Field roam_flag_vip_30day;
public final PBStringField str_zplanphoto_url;
public final PBUInt32Field uint32_400_flag;
public final PBUInt32Field uint32_age;
public final PBUInt32Field uint32_allow;
public final PBUInt32Field uint32_alphabetic_font_flag;
public final PBUInt32Field uint32_apollo_status;
public final PBUInt32Field uint32_apollo_timestamp;
public final PBUInt32Field uint32_apollo_vip_flag;
public final PBUInt32Field uint32_apollo_vip_level;
public final PBUInt32Field uint32_auth_flag;
public final PBUInt32Field uint32_auto_to_text_flag;
public final PBUInt32Field uint32_bubble_id;
public final PBUInt32Field uint32_bubble_unread_switch;
public final PBUInt32Field uint32_business_user;
public final PBUInt32Field uint32_c2c_aio_shortcut_switch;
public final PBUInt32Field uint32_charm;
public final PBUInt32Field uint32_charm_level;
public final PBUInt32Field uint32_charm_shown;
public final PBUInt32Field uint32_city_zone_id;
public final PBUInt32Field uint32_cmshow_3d_flag;
public final PBUInt32Field uint32_common_place1;
public final PBUInt32Field uint32_constellation;
public final PBUInt32Field uint32_dance_max_score;
public final PBUInt32Field uint32_default_cover_in_use;
public final PBUInt32Field uint32_do_not_disturb_mode_time;
public final PBUInt32Field uint32_elder_mode_flag;
public final PBUInt32Field uint32_ext_flag;
public final PBUInt32Field uint32_extend_friend_card_shown;
public final PBUInt32Field uint32_extend_friend_flag;
public final PBUInt32Field uint32_extend_friend_switch;
public final PBUInt32Field uint32_face_id;
public final PBUInt32Field uint32_file_assist_top;
public final PBUInt32Field uint32_flag_color_note_recent_switch;
public final PBUInt32Field uint32_flag_hide_pretty_group_owner_identity;
public final PBUInt32Field uint32_flag_is_pretty_group_owner;
public final PBUInt32Field uint32_flag_kid_mode_can_pull_group;
public final PBUInt32Field uint32_flag_kid_mode_can_search_by_strangers;
public final PBUInt32Field uint32_flag_kid_mode_can_search_friends;
public final PBUInt32Field uint32_flag_kid_mode_need_phone_verify;
public final PBUInt32Field uint32_flag_kid_mode_switch;
public final PBUInt32Field uint32_flag_qcircle_cover_switch;
public final PBUInt32Field uint32_flag_school_verified;
public final PBUInt32Field uint32_flag_study_mode_student;
public final PBUInt32Field uint32_flag_study_mode_switch;
public final PBUInt32Field uint32_flag_super_yellow_diamond;
public final PBUInt32Field uint32_flag_use_mobile_net_switch;
public final PBUInt32Field uint32_flag_zplan_edit_avatar;
public final PBUInt32Field uint32_forbid_flag;
public final PBUInt32Field uint32_freshnews_notify_flag;
public final PBUInt32Field uint32_gender;
public final PBUInt32Field uint32_global_group_level;
public final PBUInt32Field uint32_god_flag;
public final PBUInt32Field uint32_god_forbid;
public final PBUInt32Field uint32_group_mem_credit_flag;
public final PBUInt32Field uint32_guild_gray_flag;
public final PBUInt32Field uint32_has_close_leba_youth_mode_plugin;
public final PBUInt32Field uint32_hidden_session_switch;
public final PBUInt32Field uint32_hidden_session_video_switch;
public final PBUInt32Field uint32_input_status_flag;
public final PBUInt32Field uint32_lang1;
public final PBUInt32Field uint32_lang2;
public final PBUInt32Field uint32_lang3;
public final PBUInt32Field uint32_lflag;
public final PBUInt32Field uint32_lightalk_switch;
public final PBUInt32Field uint32_love_status;
public final PBUInt32Field uint32_mss_update_time;
public final PBUInt32Field uint32_music_ring_autoplay;
public final PBUInt32Field uint32_music_ring_redpoint;
public final PBUInt32Field uint32_music_ring_visible;
public final PBUInt32Field uint32_normal_night_mode_flag;
public final PBUInt32Field uint32_notify_on_like_ranking_list_flag;
public final PBUInt32Field uint32_notify_partake_like_ranking_list_flag;
public final PBUInt32Field uint32_oin;
public final PBUInt32Field uint32_online_status_avatar_switch;
public final PBUInt32Field uint32_plate_of_king_dan;
public final PBUInt32Field uint32_plate_of_king_dan_display_switch;
public final PBUInt32Field uint32_posterfont_id;
public final PBUInt32Field uint32_preload_disable_flag;
public final PBUInt32Field uint32_profession;
public final PBUInt32Field uint32_profile_age_visible;
public final PBUInt32Field uint32_profile_anonymous_answer_switch;
public final PBUInt32Field uint32_profile_birthday_visible;
public final PBUInt32Field uint32_profile_college_visible;
public final PBUInt32Field uint32_profile_company_visible;
public final PBUInt32Field uint32_profile_constellation_visible;
public final PBUInt32Field uint32_profile_dressup_switch;
public final PBUInt32Field uint32_profile_email_visible;
public final PBUInt32Field uint32_profile_hometown_visible;
public final PBUInt32Field uint32_profile_interest_switch;
public final PBUInt32Field uint32_profile_life_achievement_switch;
public final PBUInt32Field uint32_profile_location_visible;
public final PBUInt32Field uint32_profile_membership_and_rank;
public final PBUInt32Field uint32_profile_miniapp_switch;
public final PBUInt32Field uint32_profile_music_switch;
public final PBUInt32Field uint32_profile_musicbox_switch;
public final PBUInt32Field uint32_profile_personal_note_visible;
public final PBUInt32Field uint32_profile_personality_label_switch;
public final PBUInt32Field uint32_profile_present_switch;
public final PBUInt32Field uint32_profile_privilege;
public final PBUInt32Field uint32_profile_profession_visible;
public final PBUInt32Field uint32_profile_qqcard_switch;
public final PBUInt32Field uint32_profile_qqcircle_switch;
public final PBUInt32Field uint32_profile_sex_visible;
public final PBUInt32Field uint32_profile_show_idol_switch;
public final PBUInt32Field uint32_profile_splendid_switch;
public final PBUInt32Field uint32_profile_sticky_note_offline;
public final PBUInt32Field uint32_profile_sticky_note_switch;
public final PBUInt32Field uint32_profile_weishi_switch;
public final PBUInt32Field uint32_profile_wz_game_card_switch;
public final PBUInt32Field uint32_profile_wz_game_skin_switch;
public final PBUInt32Field uint32_pstn_c2c_call_time;
public final PBUInt32Field uint32_pstn_c2c_last_guide_recharge_time;
public final PBUInt32Field uint32_pstn_c2c_try_flag;
public final PBUInt32Field uint32_pstn_c2c_vip;
public final PBUInt32Field uint32_pstn_ever_c2c_vip;
public final PBUInt32Field uint32_pstn_ever_multi_vip;
public final PBUInt32Field uint32_pstn_multi_call_time;
public final PBUInt32Field uint32_pstn_multi_last_guide_recharge_time;
public final PBUInt32Field uint32_pstn_multi_try_flag;
public final PBUInt32Field uint32_pstn_multi_vip;
public final PBUInt32Field uint32_qq_assistant_switch;
public final PBUInt32Field uint32_req_font_effect_id;
public final PBUInt32Field uint32_req_global_ring_id;
public final PBUInt32Field uint32_req_invite2group_auto_agree_flag;
public final PBUInt32Field uint32_req_medalwall_flag;
public final PBUInt32Field uint32_req_push_notice_flag;
public final PBUInt32Field uint32_req_small_world_head_flag;
public final PBUInt32Field uint32_rsp_connections_switch_id;
public final PBUInt32Field uint32_rsp_listen_together_player_id;
public final PBUInt32Field uint32_rsp_qq_level_icon_type;
public final PBUInt32Field uint32_rsp_theme_font_id;
public final PBUInt32Field uint32_school_status_flag;
public final PBUInt32Field uint32_simple_ui_pref;
public final PBUInt32Field uint32_simple_ui_switch;
public final PBUInt32Field uint32_simple_update_time;
public final PBUInt32Field uint32_stranger_vote_switch;
public final PBUInt32Field uint32_subaccount_display_third_qq_flag;
public final PBUInt32Field uint32_subscribe_nearbyassistant_switch;
public final PBUInt32Field uint32_suspend_effect_id;
public final PBUInt32Field uint32_sync_C2C_message_switch;
public final PBUInt32Field uint32_torch_disable_flag;
public final PBUInt32Field uint32_torchbearer_flag;
public final PBUInt32Field uint32_troop_honor_rich_flag;
public final PBUInt32Field uint32_troop_lucky_character_switch;
public final PBUInt32Field uint32_troophonor_switch;
public final PBUInt32Field uint32_vas_colorring_id;
public final PBUInt32Field uint32_vas_diy_font_timestamp;
public final PBUInt32Field uint32_vas_emoticon_usage_info;
public final PBUInt32Field uint32_vas_face_id;
public final PBUInt32Field uint32_vas_font_id;
public final PBUInt32Field uint32_vas_magicfont_flag;
public final PBUInt32Field uint32_vas_pendant_diy_id;
public final PBUInt32Field uint32_vas_praise_id;
public final PBUInt32Field uint32_vas_voicebubble_id;
public final PBUInt32Field uint32_vip_flag;
public final PBUInt32Field uint32_zplan_add_frd;
public final PBUInt32Field uint32_zplan_cmshow_month_active_user;
public final PBUInt32Field uint32_zplan_master_show;
public final PBUInt32Field uint32_zplan_message_notice_switch;
public final PBUInt32Field uint32_zplan_open;
public final PBUInt32Field uint32_zplan_operators_network_switch;
public final PBUInt32Field uint32_zplan_profile_card_show;
public final PBUInt32Field uint32_zplan_qzone_show;
public final PBUInt32Field uint32_zplan_samestyle_asset_switch;
public final PBUInt32Field uint32_zplan_samestyle_package_switch;
public final PBUInt64Field uint64_face_addon_id;
public final PBUInt64Field uint64_game_appid;
public final PBUInt64Field uint64_game_last_login_time;
public final PBUInt64Field uint64_uin = PBField.initUInt64(0);
public final PBUInt32Field unit32_concise_mode_flag;
public final PBUInt32Field unit32_hide_camera_emoticon_flag;
public final PBUInt32Field unit32_hide_cm_show_emoticon_flag;
public final PBUInt32Field unit32_online_state_praise_notify;
public final PBBytesField zplan_appearanceKey;
public final PBUInt32Field zplan_appearanceKey_time;
public final PBUInt32Field zplan_avatar_gender;
public UdcUinData() { | ByteStringMicro byteStringMicro = ByteStringMicro.EMPTY; | 0 | 2023-10-20 10:43:47+00:00 | 8k |
zhaoeryu/eu-backend | eu-admin/src/main/java/cn/eu/system/controller/SysUserController.java | [
{
"identifier": "EuBaseController",
"path": "eu-common-core/src/main/java/cn/eu/common/base/controller/EuBaseController.java",
"snippet": "public abstract class EuBaseController {\n}"
},
{
"identifier": "BusinessType",
"path": "eu-common-core/src/main/java/cn/eu/common/enums/BusinessType.jav... | import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import cn.eu.common.annotation.Log;
import cn.eu.common.base.controller.EuBaseController;
import cn.eu.common.enums.BusinessType;
import cn.eu.common.model.PageResult;
import cn.eu.common.model.ResultBody;
import cn.eu.common.utils.EasyExcelHelper;
import cn.eu.common.utils.SpringContextHolder;
import cn.eu.event.LoginCacheRefreshEvent;
import cn.eu.security.PasswordEncoder;
import cn.eu.system.domain.SysUser;
import cn.eu.system.model.dto.*;
import cn.eu.system.model.pojo.UpdatePasswordBody;
import cn.eu.system.model.query.AssignRoleQuery;
import cn.eu.system.model.query.SysUserQueryCriteria;
import cn.eu.system.service.ISysPostService;
import cn.eu.system.service.ISysRoleService;
import cn.eu.system.service.ISysUserService;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*; | 5,376 | package cn.eu.system.controller;
/**
* @author zhaoeryu
* @since 2023/5/31
*/
@Slf4j
@RequestMapping("/system/user")
@RestController
public class SysUserController extends EuBaseController {
@Autowired
ISysUserService sysUserService;
@Autowired
ISysRoleService roleService;
@Autowired
ISysPostService postService;
@Log(title = "查看用户列表", businessType = BusinessType.QUERY, isSaveResponseData = false)
@SaCheckPermission("system:user:list")
@GetMapping("/page") | package cn.eu.system.controller;
/**
* @author zhaoeryu
* @since 2023/5/31
*/
@Slf4j
@RequestMapping("/system/user")
@RestController
public class SysUserController extends EuBaseController {
@Autowired
ISysUserService sysUserService;
@Autowired
ISysRoleService roleService;
@Autowired
ISysPostService postService;
@Log(title = "查看用户列表", businessType = BusinessType.QUERY, isSaveResponseData = false)
@SaCheckPermission("system:user:list")
@GetMapping("/page") | public ResultBody page(SysUserQueryCriteria criteria, @PageableDefault(page = 1) Pageable pageable) { | 11 | 2023-10-20 07:08:37+00:00 | 8k |
Nxer/Twist-Space-Technology-Mod | src/main/java/com/Nxer/TwistSpaceTechnology/common/block/BasicBlocks.java | [
{
"identifier": "BlockBase01",
"path": "src/main/java/com/Nxer/TwistSpaceTechnology/common/block/blockClass/BlockBase01.java",
"snippet": "public class BlockBase01 extends Block {\n\n // region Constructors\n protected BlockBase01(Material materialIn) {\n super(materialIn);\n }\n\n pu... | import net.minecraft.block.Block;
import com.Nxer.TwistSpaceTechnology.common.block.blockClass.BlockBase01;
import com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.BlockNuclearReactor;
import com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.PhotonControllerUpgradeCasing;
import com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.spaceStation.SpaceStationAntiGravityCasing;
import com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.spaceStation.SpaceStationStructureCasing; | 4,490 | package com.Nxer.TwistSpaceTechnology.common.block;
public class BasicBlocks {
public static final Block MetaBlock01 = new BlockBase01("MetaBlock01", "MetaBlock01");
public static final Block PhotonControllerUpgrade = new PhotonControllerUpgradeCasing(
"PhotonControllerUpgrades",
"Photon Controller Upgrade");
public static final Block spaceStationStructureBlock = new SpaceStationStructureCasing(
"SpaceStationStructureBlock",
"Space Station Structure Block");
| package com.Nxer.TwistSpaceTechnology.common.block;
public class BasicBlocks {
public static final Block MetaBlock01 = new BlockBase01("MetaBlock01", "MetaBlock01");
public static final Block PhotonControllerUpgrade = new PhotonControllerUpgradeCasing(
"PhotonControllerUpgrades",
"Photon Controller Upgrade");
public static final Block spaceStationStructureBlock = new SpaceStationStructureCasing(
"SpaceStationStructureBlock",
"Space Station Structure Block");
| public static final Block SpaceStationAntiGravityBlock = new SpaceStationAntiGravityCasing( | 3 | 2023-10-16 09:57:15+00:00 | 8k |
wyjsonGo/GoRouter | GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/processor/GenerateRouteModuleProcessor.java | [
{
"identifier": "ACTIVITY",
"path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java",
"snippet": "public static final String ACTIVITY = \"android.app.Activity\";"
},
{
"identifier": "BOOLEAN_PACKAGE",
"path": "GoRouter-Compiler/src/main/java/com/wyjson/router... | import static com.wyjson.router.compiler.utils.Constants.ACTIVITY;
import static com.wyjson.router.compiler.utils.Constants.BOOLEAN_PACKAGE;
import static com.wyjson.router.compiler.utils.Constants.BOOLEAN_PRIMITIVE;
import static com.wyjson.router.compiler.utils.Constants.BYTE_PACKAGE;
import static com.wyjson.router.compiler.utils.Constants.BYTE_PRIMITIVE;
import static com.wyjson.router.compiler.utils.Constants.CHAR_PACKAGE;
import static com.wyjson.router.compiler.utils.Constants.CHAR_PRIMITIVE;
import static com.wyjson.router.compiler.utils.Constants.DOUBLE_PACKAGE;
import static com.wyjson.router.compiler.utils.Constants.DOUBLE_PRIMITIVE;
import static com.wyjson.router.compiler.utils.Constants.FLOAT_PACKAGE;
import static com.wyjson.router.compiler.utils.Constants.FLOAT_PRIMITIVE;
import static com.wyjson.router.compiler.utils.Constants.FRAGMENT;
import static com.wyjson.router.compiler.utils.Constants.GOROUTER;
import static com.wyjson.router.compiler.utils.Constants.INTEGER_PACKAGE;
import static com.wyjson.router.compiler.utils.Constants.INTEGER_PRIMITIVE;
import static com.wyjson.router.compiler.utils.Constants.I_ROUTE_MODULE;
import static com.wyjson.router.compiler.utils.Constants.I_ROUTE_MODULE_GROUP;
import static com.wyjson.router.compiler.utils.Constants.I_ROUTE_MODULE_GROUP_METHOD_NAME_LOAD;
import static com.wyjson.router.compiler.utils.Constants.LONG_PACKAGE;
import static com.wyjson.router.compiler.utils.Constants.LONG_PRIMITIVE;
import static com.wyjson.router.compiler.utils.Constants.METHOD_NAME_LOAD;
import static com.wyjson.router.compiler.utils.Constants.METHOD_NAME_LOAD_ROUTE_FOR_x_GROUP;
import static com.wyjson.router.compiler.utils.Constants.METHOD_NAME_LOAD_ROUTE_GROUP;
import static com.wyjson.router.compiler.utils.Constants.PARAM_NAME_ROUTE_GROUPS;
import static com.wyjson.router.compiler.utils.Constants.PARCELABLE_PACKAGE;
import static com.wyjson.router.compiler.utils.Constants.PREFIX_OF_LOGGER;
import static com.wyjson.router.compiler.utils.Constants.ROUTE_CENTER;
import static com.wyjson.router.compiler.utils.Constants.ROUTE_CENTER_METHOD_NAME_GET_ROUTE_GROUPS;
import static com.wyjson.router.compiler.utils.Constants.ROUTE_MODULE;
import static com.wyjson.router.compiler.utils.Constants.ROUTE_MODULE_GENERATE_CLASS_NAME_SUFFIX;
import static com.wyjson.router.compiler.utils.Constants.SERIALIZABLE_PACKAGE;
import static com.wyjson.router.compiler.utils.Constants.SHORT_PACKAGE;
import static com.wyjson.router.compiler.utils.Constants.SHORT_PRIMITIVE;
import static com.wyjson.router.compiler.utils.Constants.STRING_PACKAGE;
import static com.wyjson.router.compiler.utils.Constants.WARNING_TIPS;
import static javax.lang.model.element.Modifier.PRIVATE;
import static javax.lang.model.element.Modifier.PUBLIC;
import com.google.auto.service.AutoService;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeSpec;
import com.wyjson.router.annotation.Interceptor;
import com.wyjson.router.annotation.Param;
import com.wyjson.router.annotation.Route;
import com.wyjson.router.annotation.Service;
import com.wyjson.router.compiler.doc.DocumentUtils;
import com.wyjson.router.compiler.doc.model.RouteModel;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror; | 4,764 | package com.wyjson.router.compiler.processor;
@AutoService(Processor.class)
public class GenerateRouteModuleProcessor extends BaseProcessor {
TypeElement mGoRouter;
TypeElement mIRouteModule;
TypeElement mRouteCenter;
TypeElement mIRouteModuleGroup;
TypeMirror serializableType;
TypeMirror parcelableType;
TypeMirror activityType;
TypeMirror fragmentType;
private final Map<String, Set<Element>> routeGroupMap = new HashMap<>();
@Override
public Set<String> getSupportedAnnotationTypes() {
Set<String> set = new LinkedHashSet<>();
set.add(Service.class.getCanonicalName());
set.add(Interceptor.class.getCanonicalName());
set.add(Route.class.getCanonicalName());
return set;
}
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
logger.info(moduleName + " >>> GenerateRouteModuleProcessor init. <<<");
mGoRouter = elementUtils.getTypeElement(GOROUTER);
mIRouteModule = elementUtils.getTypeElement(I_ROUTE_MODULE);
}
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
if (CollectionUtils.isEmpty(set))
return false;
DocumentUtils.createDoc(mFiler, moduleName, logger, isGenerateDoc);
String className = generateClassName + ROUTE_MODULE_GENERATE_CLASS_NAME_SUFFIX;
MethodSpec.Builder loadIntoMethod = MethodSpec.methodBuilder(METHOD_NAME_LOAD)
.addModifiers(PUBLIC)
.addAnnotation(Override.class);
loadIntoMethod.addJavadoc("load the $S route", moduleName);
addService(roundEnvironment, loadIntoMethod);
addInterceptor(roundEnvironment, loadIntoMethod);
LinkedHashSet<MethodSpec> routeGroupMethods = addRouteGroup(roundEnvironment, loadIntoMethod);
try {
JavaFile.builder(ROUTE_MODULE,
TypeSpec.classBuilder(className)
.addModifiers(PUBLIC)
.addSuperinterface(ClassName.get(mIRouteModule)) | package com.wyjson.router.compiler.processor;
@AutoService(Processor.class)
public class GenerateRouteModuleProcessor extends BaseProcessor {
TypeElement mGoRouter;
TypeElement mIRouteModule;
TypeElement mRouteCenter;
TypeElement mIRouteModuleGroup;
TypeMirror serializableType;
TypeMirror parcelableType;
TypeMirror activityType;
TypeMirror fragmentType;
private final Map<String, Set<Element>> routeGroupMap = new HashMap<>();
@Override
public Set<String> getSupportedAnnotationTypes() {
Set<String> set = new LinkedHashSet<>();
set.add(Service.class.getCanonicalName());
set.add(Interceptor.class.getCanonicalName());
set.add(Route.class.getCanonicalName());
return set;
}
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
logger.info(moduleName + " >>> GenerateRouteModuleProcessor init. <<<");
mGoRouter = elementUtils.getTypeElement(GOROUTER);
mIRouteModule = elementUtils.getTypeElement(I_ROUTE_MODULE);
}
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
if (CollectionUtils.isEmpty(set))
return false;
DocumentUtils.createDoc(mFiler, moduleName, logger, isGenerateDoc);
String className = generateClassName + ROUTE_MODULE_GENERATE_CLASS_NAME_SUFFIX;
MethodSpec.Builder loadIntoMethod = MethodSpec.methodBuilder(METHOD_NAME_LOAD)
.addModifiers(PUBLIC)
.addAnnotation(Override.class);
loadIntoMethod.addJavadoc("load the $S route", moduleName);
addService(roundEnvironment, loadIntoMethod);
addInterceptor(roundEnvironment, loadIntoMethod);
LinkedHashSet<MethodSpec> routeGroupMethods = addRouteGroup(roundEnvironment, loadIntoMethod);
try {
JavaFile.builder(ROUTE_MODULE,
TypeSpec.classBuilder(className)
.addModifiers(PUBLIC)
.addSuperinterface(ClassName.get(mIRouteModule)) | .addJavadoc(WARNING_TIPS) | 34 | 2023-10-18 13:52:07+00:00 | 8k |
trpc-group/trpc-java | trpc-core/src/main/java/com/tencent/trpc/core/serialization/support/JSONSerialization.java | [
{
"identifier": "SerializationType",
"path": "trpc-core/src/main/java/com/tencent/trpc/core/serialization/SerializationType.java",
"snippet": "public interface SerializationType {\n\n /**\n * Protocol Buffers format.\n */\n int PB = 0;\n /**\n * JCE format.\n */\n int JCE = 1... | import com.fasterxml.jackson.core.type.TypeReference;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.google.protobuf.Message;
import com.tencent.trpc.core.extension.Extension;
import com.tencent.trpc.core.serialization.SerializationType;
import com.tencent.trpc.core.serialization.spi.Serialization;
import com.tencent.trpc.core.utils.ClassUtils;
import com.tencent.trpc.core.utils.JsonUtils;
import com.tencent.trpc.core.utils.ProtoJsonConverter;
import java.io.IOException;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects; | 5,405 | /*
* Tencent is pleased to support the open source community by making tRPC available.
*
* Copyright (C) 2023 THL A29 Limited, a Tencent company.
* All rights reserved.
*
* If you have downloaded a copy of the tRPC source code from Tencent,
* please note that tRPC source code is licensed under the Apache 2.0 License,
* A copy of the Apache 2.0 License can be found in the LICENSE file.
*/
package com.tencent.trpc.core.serialization.support;
@Extension(JSONSerialization.NAME)
@SuppressWarnings("unchecked")
public class JSONSerialization implements Serialization {
public static final String NAME = "json";
/**
* PB class method information cache. One class per method, initial cache size 20, maximum 500.
*/
private static final Cache<Class, Method> CLASS_METHOD_CACHE = Caffeine.newBuilder()
.initialCapacity(20)
.maximumSize(500)
.build();
/**
* Default UTF-8 serialize.
*
* @param obj the object to be serialized
* @return the serialized byte array
* @throws IOException IO exception
*/
@Override
public byte[] serialize(Object obj) throws IOException {
try {
// pb to bytes
if (obj instanceof Message) { | /*
* Tencent is pleased to support the open source community by making tRPC available.
*
* Copyright (C) 2023 THL A29 Limited, a Tencent company.
* All rights reserved.
*
* If you have downloaded a copy of the tRPC source code from Tencent,
* please note that tRPC source code is licensed under the Apache 2.0 License,
* A copy of the Apache 2.0 License can be found in the LICENSE file.
*/
package com.tencent.trpc.core.serialization.support;
@Extension(JSONSerialization.NAME)
@SuppressWarnings("unchecked")
public class JSONSerialization implements Serialization {
public static final String NAME = "json";
/**
* PB class method information cache. One class per method, initial cache size 20, maximum 500.
*/
private static final Cache<Class, Method> CLASS_METHOD_CACHE = Caffeine.newBuilder()
.initialCapacity(20)
.maximumSize(500)
.build();
/**
* Default UTF-8 serialize.
*
* @param obj the object to be serialized
* @return the serialized byte array
* @throws IOException IO exception
*/
@Override
public byte[] serialize(Object obj) throws IOException {
try {
// pb to bytes
if (obj instanceof Message) { | return JsonUtils.toBytes(ProtoJsonConverter.messageToMap((Message) obj)); | 3 | 2023-10-19 10:54:11+00:00 | 8k |
freedom-introvert/YouTubeSendCommentAntiFraud | YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/xposed/XposedInit.java | [
{
"identifier": "CopyUrlHook",
"path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/xposed/hooks/CopyUrlHook.java",
"snippet": "public class CopyUrlHook extends BaseHook {\r\n @Override\r\n public void startHook(int appVersionCode, ClassLoader classLoader) throws... | import android.content.Context;
import java.util.Arrays;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodReplacement;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage;
import icu.freedomintrovert.YTSendCommAntiFraud.xposed.hooks.CopyUrlHook;
import icu.freedomintrovert.YTSendCommAntiFraud.xposed.hooks.OpenLinkHook;
import icu.freedomintrovert.YTSendCommAntiFraud.xposed.hooks.PostCommentHook;
import icu.freedomintrovert.YTSendCommAntiFraud.xposed.hooks.SetOrientationHook;
| 4,264 | package icu.freedomintrovert.YTSendCommAntiFraud.xposed;
public class XposedInit implements IXposedHookLoadPackage {
@Override
public void handleLoadPackage(XC_LoadPackage.LoadPackageParam loadPackageParam) throws Throwable {
if (loadPackageParam.packageName.equals("com.google.android.youtube") || loadPackageParam.packageName.equals("app.rvx.android.youtube")) {
InHookXConfig config = InHookXConfig.getInstance();
ClassLoader classLoader = loadPackageParam.classLoader;
int appVersionCode = systemContext().getPackageManager().getPackageInfo(loadPackageParam.packageName, 0).versionCode;
XposedBridge.log("YouTube version code:" + appVersionCode);
HookStater hookStater = new HookStater(appVersionCode,classLoader);
hookStater.startHook(new PostCommentHook());//因有时候要抓取请求头,所以若关闭该选项仅不打开activity,保留记录请求头
if (config.getShareUrlAntiTrackingEnabled()) {
| package icu.freedomintrovert.YTSendCommAntiFraud.xposed;
public class XposedInit implements IXposedHookLoadPackage {
@Override
public void handleLoadPackage(XC_LoadPackage.LoadPackageParam loadPackageParam) throws Throwable {
if (loadPackageParam.packageName.equals("com.google.android.youtube") || loadPackageParam.packageName.equals("app.rvx.android.youtube")) {
InHookXConfig config = InHookXConfig.getInstance();
ClassLoader classLoader = loadPackageParam.classLoader;
int appVersionCode = systemContext().getPackageManager().getPackageInfo(loadPackageParam.packageName, 0).versionCode;
XposedBridge.log("YouTube version code:" + appVersionCode);
HookStater hookStater = new HookStater(appVersionCode,classLoader);
hookStater.startHook(new PostCommentHook());//因有时候要抓取请求头,所以若关闭该选项仅不打开activity,保留记录请求头
if (config.getShareUrlAntiTrackingEnabled()) {
| hookStater.startHook(new CopyUrlHook());
| 0 | 2023-10-15 01:18:28+00:00 | 8k |
New-Barams/This-Year-Ajaja-BE | src/main/java/com/newbarams/ajaja/module/plan/presentation/PlanController.java | [
{
"identifier": "AjajaResponse",
"path": "src/main/java/com/newbarams/ajaja/global/common/AjajaResponse.java",
"snippet": "@Getter\n@JsonPropertyOrder({\"success\", \"data\"})\n@JsonInclude(JsonInclude.Include.NON_NULL)\npublic class AjajaResponse<T> {\n\tprivate final Boolean success;\n\tprivate final ... | import static org.springframework.http.HttpHeaders.*;
import static org.springframework.http.HttpStatus.*;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.newbarams.ajaja.global.common.AjajaResponse;
import com.newbarams.ajaja.global.exception.ErrorResponse;
import com.newbarams.ajaja.global.security.common.UserId;
import com.newbarams.ajaja.global.security.jwt.util.JwtParser;
import com.newbarams.ajaja.global.util.BearerUtils;
import com.newbarams.ajaja.module.ajaja.application.SwitchAjajaService;
import com.newbarams.ajaja.module.plan.application.CreatePlanService;
import com.newbarams.ajaja.module.plan.application.DeletePlanService;
import com.newbarams.ajaja.module.plan.application.LoadPlanInfoService;
import com.newbarams.ajaja.module.plan.application.LoadPlanService;
import com.newbarams.ajaja.module.plan.application.UpdatePlanService;
import com.newbarams.ajaja.module.plan.application.UpdateRemindInfoService;
import com.newbarams.ajaja.module.plan.dto.PlanRequest;
import com.newbarams.ajaja.module.plan.dto.PlanResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import lombok.RequiredArgsConstructor; | 4,669 | package com.newbarams.ajaja.module.plan.presentation;
@Tag(name = "plan")
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("/plans")
public class PlanController {
private final CreatePlanService createPlanService;
private final LoadPlanService getPlanService;
private final DeletePlanService deletePlanService;
private final UpdatePlanService updatePlanService;
private final LoadPlanInfoService loadPlanInfoService;
private final UpdateRemindInfoService updateRemindInfoService;
private final SwitchAjajaService switchAjajaService;
private final JwtParser jwtParser; // todo: delete when authentication filtering update
@PostMapping("/{id}/ajaja")
public AjajaResponse<Void> switchAjaja(@UserId Long userId, @PathVariable Long id) {
switchAjajaService.switchOrAddIfNotExist(userId, id);
return AjajaResponse.ok();
}
@Operation(summary = "계획 단건 조회 API", description = "토큰을 추가해서 보내면 계획 작성자인지, 아좌좌를 눌렀는지 추가적으로 판별합니다.")
@GetMapping("/{id}")
@ResponseStatus(OK)
public AjajaResponse<PlanResponse.Detail> getPlanWithOptionalUser(
@RequestHeader(value = AUTHORIZATION, required = false) String accessToken,
@PathVariable Long id
) {
Long userId = accessToken == null ? null : parseUserId(accessToken);
PlanResponse.Detail response = getPlanService.loadByIdAndOptionalUser(userId, id);
return AjajaResponse.ok(response);
}
private Long parseUserId(String accessToken) {
BearerUtils.validate(accessToken);
return jwtParser.parseId(BearerUtils.resolve(accessToken));
}
@Operation(summary = "[토큰 필요] 계획 생성 API")
@PostMapping
@ResponseStatus(CREATED)
public AjajaResponse<PlanResponse.Create> createPlan(
@UserId Long userId, | package com.newbarams.ajaja.module.plan.presentation;
@Tag(name = "plan")
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("/plans")
public class PlanController {
private final CreatePlanService createPlanService;
private final LoadPlanService getPlanService;
private final DeletePlanService deletePlanService;
private final UpdatePlanService updatePlanService;
private final LoadPlanInfoService loadPlanInfoService;
private final UpdateRemindInfoService updateRemindInfoService;
private final SwitchAjajaService switchAjajaService;
private final JwtParser jwtParser; // todo: delete when authentication filtering update
@PostMapping("/{id}/ajaja")
public AjajaResponse<Void> switchAjaja(@UserId Long userId, @PathVariable Long id) {
switchAjajaService.switchOrAddIfNotExist(userId, id);
return AjajaResponse.ok();
}
@Operation(summary = "계획 단건 조회 API", description = "토큰을 추가해서 보내면 계획 작성자인지, 아좌좌를 눌렀는지 추가적으로 판별합니다.")
@GetMapping("/{id}")
@ResponseStatus(OK)
public AjajaResponse<PlanResponse.Detail> getPlanWithOptionalUser(
@RequestHeader(value = AUTHORIZATION, required = false) String accessToken,
@PathVariable Long id
) {
Long userId = accessToken == null ? null : parseUserId(accessToken);
PlanResponse.Detail response = getPlanService.loadByIdAndOptionalUser(userId, id);
return AjajaResponse.ok(response);
}
private Long parseUserId(String accessToken) {
BearerUtils.validate(accessToken);
return jwtParser.parseId(BearerUtils.resolve(accessToken));
}
@Operation(summary = "[토큰 필요] 계획 생성 API")
@PostMapping
@ResponseStatus(CREATED)
public AjajaResponse<PlanResponse.Create> createPlan(
@UserId Long userId, | @RequestBody PlanRequest.Create request, | 10 | 2023-10-23 07:24:17+00:00 | 8k |
eclipse-jgit/jgit | org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/file/PackReverseIndex.java | [
{
"identifier": "CorruptObjectException",
"path": "org.eclipse.jgit/src/org/eclipse/jgit/errors/CorruptObjectException.java",
"snippet": "public class CorruptObjectException extends IOException {\n\tprivate static final long serialVersionUID = 1L;\n\n\tprivate ObjectChecker.ErrorType errorType;\n\n\t/**... | import org.eclipse.jgit.errors.CorruptObjectException;
import org.eclipse.jgit.errors.PackMismatchException;
import org.eclipse.jgit.lib.ObjectId; | 3,911 | /*
* Copyright (C) 2008, Marek Zawirski <marek.zawirski@gmail.com> and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0 which is available at
* https://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package org.eclipse.jgit.internal.storage.file;
/**
* <p>
* Reverse index for forward pack index. Provides operations based on offset
* instead of object id. Such offset-based reverse lookups are performed in
* O(log n) time.
* </p>
*
* @see PackIndex
* @see Pack
*/
public interface PackReverseIndex {
/**
* Magic bytes that uniquely identify git reverse index files.
*/
byte[] MAGIC = { 'R', 'I', 'D', 'X' };
/**
* The first reverse index file version.
*/
int VERSION_1 = 1;
/**
* Verify that the pack checksum found in the reverse index matches that
* from the pack file.
*
* @param packFilePath
* the path to display in event of a mismatch
* @throws PackMismatchException
* if the checksums do not match
*/
void verifyPackChecksum(String packFilePath) throws PackMismatchException;
/**
* Search for object id with the specified start offset in this pack
* (reverse) index.
*
* @param offset
* start offset of object to find.
* @return object id for this offset, or null if no object was found.
*/ | /*
* Copyright (C) 2008, Marek Zawirski <marek.zawirski@gmail.com> and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0 which is available at
* https://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package org.eclipse.jgit.internal.storage.file;
/**
* <p>
* Reverse index for forward pack index. Provides operations based on offset
* instead of object id. Such offset-based reverse lookups are performed in
* O(log n) time.
* </p>
*
* @see PackIndex
* @see Pack
*/
public interface PackReverseIndex {
/**
* Magic bytes that uniquely identify git reverse index files.
*/
byte[] MAGIC = { 'R', 'I', 'D', 'X' };
/**
* The first reverse index file version.
*/
int VERSION_1 = 1;
/**
* Verify that the pack checksum found in the reverse index matches that
* from the pack file.
*
* @param packFilePath
* the path to display in event of a mismatch
* @throws PackMismatchException
* if the checksums do not match
*/
void verifyPackChecksum(String packFilePath) throws PackMismatchException;
/**
* Search for object id with the specified start offset in this pack
* (reverse) index.
*
* @param offset
* start offset of object to find.
* @return object id for this offset, or null if no object was found.
*/ | ObjectId findObject(long offset); | 2 | 2023-10-20 15:09:17+00:00 | 8k |
starfish-studios/Naturalist | common/src/main/java/com/starfish_studios/naturalist/client/model/HippoModel.java | [
{
"identifier": "Naturalist",
"path": "common/src/main/java/com/starfish_studios/naturalist/Naturalist.java",
"snippet": "public class Naturalist {\n public static final String MOD_ID = \"naturalist\";\n public static final CreativeModeTab TAB = CommonPlatformHelper.registerCreativeModeTab(new Res... | import com.starfish_studios.naturalist.Naturalist;
import com.starfish_studios.naturalist.common.entity.Hippo;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.Mth;
import org.jetbrains.annotations.Nullable;
import software.bernie.geckolib3.core.event.predicate.AnimationEvent;
import software.bernie.geckolib3.core.processor.IBone;
import software.bernie.geckolib3.model.AnimatedGeoModel;
import software.bernie.geckolib3.model.provider.data.EntityModelData;
import java.util.List; | 5,118 | package com.starfish_studios.naturalist.client.model;
@Environment(EnvType.CLIENT)
public class HippoModel extends AnimatedGeoModel<Hippo> {
@Override
public ResourceLocation getModelResource(Hippo hippo) { | package com.starfish_studios.naturalist.client.model;
@Environment(EnvType.CLIENT)
public class HippoModel extends AnimatedGeoModel<Hippo> {
@Override
public ResourceLocation getModelResource(Hippo hippo) { | return new ResourceLocation(Naturalist.MOD_ID, "geo/hippo.geo.json"); | 0 | 2023-10-16 21:54:32+00:00 | 8k |
wangqi060934/MyAndroidToolsPro | app/src/main/java/cn/wq/myandroidtoolspro/helper/IfwUtil.java | [
{
"identifier": "BackupEntry",
"path": "app/src/main/java/cn/wq/myandroidtoolspro/model/BackupEntry.java",
"snippet": "public class BackupEntry extends ComponentEntry {\n public String appName;\n /**\n * @see cn.wq.myandroidtoolspro.helper.IfwUtil#COMPONENT_FLAG_ACTIVITY\n */\n public i... | import android.content.ComponentName;
import android.content.Context;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.util.Xml;
import com.tencent.mars.xlog.Log;
import org.xmlpull.v1.XmlPullParser;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import cn.wq.myandroidtoolspro.model.BackupEntry;
import cn.wq.myandroidtoolspro.model.ComponentEntry;
import cn.wq.myandroidtoolspro.recyclerview.adapter.AbstractComponentAdapter;
import cn.wq.myandroidtoolspro.recyclerview.fragment.AppInfoForManageFragment2; | 4,091 | package cn.wq.myandroidtoolspro.helper;
public class IfwUtil {
private static final String TAG = "IfwUtil";
private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
public static final int COMPONENT_FLAG_EMPTY = 0x00;
public static final int COMPONENT_FLAG_ACTIVITY = 0x01;
public static final int COMPONENT_FLAG_RECEIVER = 0x10;
public static final int COMPONENT_FLAG_SERVICE = 0x100;
public static final int COMPONENT_FLAG_ALL = 0x111;
public static final String BACKUP_LOCAL_FILE_EXT = ".ifw";
public static final String BACKUP_SYSTEM_FILE_EXT_OF_STANDARD = ".xml"; //标准ifw备份后缀
public static final String BACKUP_SYSTEM_FILE_EXT_OF_MINE = "$" + BACKUP_SYSTEM_FILE_EXT_OF_STANDARD; //本App备份ifw使用的后缀
/**
* 组件列表中修改选中位置component的ifw状态,并保存所有component到ifw文件<br>
* 每个类型的list中(例如ServiceRecyclerListFragment)的修改都需要完整保存整个ifw内容
*
* @param positions 某一类component的位置
*/
public static boolean saveComponentIfw(Context context,
@NonNull String packageName,
IfwEntry ifwEntry, | package cn.wq.myandroidtoolspro.helper;
public class IfwUtil {
private static final String TAG = "IfwUtil";
private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
public static final int COMPONENT_FLAG_EMPTY = 0x00;
public static final int COMPONENT_FLAG_ACTIVITY = 0x01;
public static final int COMPONENT_FLAG_RECEIVER = 0x10;
public static final int COMPONENT_FLAG_SERVICE = 0x100;
public static final int COMPONENT_FLAG_ALL = 0x111;
public static final String BACKUP_LOCAL_FILE_EXT = ".ifw";
public static final String BACKUP_SYSTEM_FILE_EXT_OF_STANDARD = ".xml"; //标准ifw备份后缀
public static final String BACKUP_SYSTEM_FILE_EXT_OF_MINE = "$" + BACKUP_SYSTEM_FILE_EXT_OF_STANDARD; //本App备份ifw使用的后缀
/**
* 组件列表中修改选中位置component的ifw状态,并保存所有component到ifw文件<br>
* 每个类型的list中(例如ServiceRecyclerListFragment)的修改都需要完整保存整个ifw内容
*
* @param positions 某一类component的位置
*/
public static boolean saveComponentIfw(Context context,
@NonNull String packageName,
IfwEntry ifwEntry, | @NonNull AbstractComponentAdapter<? extends ComponentEntry> adapter, | 1 | 2023-10-18 14:32:49+00:00 | 8k |
instana/otel-dc | host/src/main/java/com/instana/dc/host/impl/SimpHostDc.java | [
{
"identifier": "AbstractHostDc",
"path": "host/src/main/java/com/instana/dc/host/AbstractHostDc.java",
"snippet": "public abstract class AbstractHostDc extends AbstractDc implements IDc {\n private static final Logger logger = Logger.getLogger(AbstractHostDc.class.getName());\n\n private final St... | import com.instana.dc.host.AbstractHostDc;
import com.instana.dc.host.HostDcUtil;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.sdk.resources.Resource;
import io.opentelemetry.semconv.ResourceAttributes;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import static com.instana.dc.DcUtil.mergeResourceAttributesFromEnv;
import static com.instana.dc.host.HostDcUtil.*; | 4,739 | /*
* (c) Copyright IBM Corp. 2023
* (c) Copyright Instana Inc.
*/
package com.instana.dc.host.impl;
public class SimpHostDc extends AbstractHostDc {
private static final Logger logger = Logger.getLogger(SimpHostDc.class.getName());
public SimpHostDc(Map<String, String> properties, String hostSystem) {
super(properties, hostSystem);
}
public String getHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "UnknownName";
}
}
public String getHostId() {
try { | /*
* (c) Copyright IBM Corp. 2023
* (c) Copyright Instana Inc.
*/
package com.instana.dc.host.impl;
public class SimpHostDc extends AbstractHostDc {
private static final Logger logger = Logger.getLogger(SimpHostDc.class.getName());
public SimpHostDc(Map<String, String> properties, String hostSystem) {
super(properties, hostSystem);
}
public String getHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "UnknownName";
}
}
public String getHostId() {
try { | return HostDcUtil.readFileText("/etc/machine-id"); | 3 | 2023-10-23 01:16:38+00:00 | 8k |
A1anSong/jd_unidbg | unidbg-ios/src/main/java/com/github/unidbg/ios/file/JarEntryFileIO.java | [
{
"identifier": "Emulator",
"path": "unidbg-api/src/main/java/com/github/unidbg/Emulator.java",
"snippet": "public interface Emulator<T extends NewFileIO> extends Closeable, ArmDisassembler, Serializable {\n\n int getPointerSize();\n\n boolean is64Bit();\n boolean is32Bit();\n\n int getPageA... | import com.github.unidbg.Emulator;
import com.github.unidbg.arm.backend.Backend;
import com.github.unidbg.file.ios.BaseDarwinFileIO;
import com.github.unidbg.file.ios.StatStructure;
import com.github.unidbg.ios.struct.kernel.StatFS;
import com.github.unidbg.unix.IO;
import com.sun.jna.Pointer;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.jar.JarEntry;
import java.util.jar.JarFile; | 7,158 | package com.github.unidbg.ios.file;
public class JarEntryFileIO extends BaseDarwinFileIO {
private final String path;
private final File jarFile;
private final JarEntry entry;
public JarEntryFileIO(int oflags, String path, File jarFile, JarEntry entry) {
super(oflags);
this.path = path;
this.jarFile = jarFile;
this.entry = entry;
}
private int pos;
private JarFile openedJarFile;
@Override
public void close() {
pos = 0;
if (openedJarFile != null) {
com.alibaba.fastjson.util.IOUtils.close(openedJarFile);
openedJarFile = null;
}
}
@Override
public int read(Backend backend, Pointer buffer, int count) {
try {
if (pos >= entry.getSize()) {
return 0;
}
if (openedJarFile == null) {
openedJarFile = new JarFile(this.jarFile);
}
int remain = (int) entry.getSize() - pos;
if (count > remain) {
count = remain;
}
try (InputStream inputStream = openedJarFile.getInputStream(entry)) {
if (inputStream.skip(pos) != pos) {
throw new IllegalStateException();
}
buffer.write(0, IOUtils.toByteArray(inputStream, count), 0, count);
}
pos += count;
return count;
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public int write(byte[] data) {
throw new UnsupportedOperationException();
}
@Override
public int lseek(int offset, int whence) {
switch (whence) {
case SEEK_SET:
pos = offset;
return pos;
case SEEK_CUR:
pos += offset;
return pos;
case SEEK_END:
pos = (int) entry.getSize() + offset;
return pos;
}
return super.lseek(offset, whence);
}
@Override
protected byte[] getMmapData(long addr, int offset, int length) {
try (JarFile jarFile = new JarFile(this.jarFile); InputStream inputStream = jarFile.getInputStream(entry)) {
if (offset == 0 && length == entry.getSize()) {
return IOUtils.toByteArray(inputStream);
} else {
if (inputStream.skip(offset) != offset) {
throw new IllegalStateException();
}
return IOUtils.toByteArray(inputStream, length);
}
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override | package com.github.unidbg.ios.file;
public class JarEntryFileIO extends BaseDarwinFileIO {
private final String path;
private final File jarFile;
private final JarEntry entry;
public JarEntryFileIO(int oflags, String path, File jarFile, JarEntry entry) {
super(oflags);
this.path = path;
this.jarFile = jarFile;
this.entry = entry;
}
private int pos;
private JarFile openedJarFile;
@Override
public void close() {
pos = 0;
if (openedJarFile != null) {
com.alibaba.fastjson.util.IOUtils.close(openedJarFile);
openedJarFile = null;
}
}
@Override
public int read(Backend backend, Pointer buffer, int count) {
try {
if (pos >= entry.getSize()) {
return 0;
}
if (openedJarFile == null) {
openedJarFile = new JarFile(this.jarFile);
}
int remain = (int) entry.getSize() - pos;
if (count > remain) {
count = remain;
}
try (InputStream inputStream = openedJarFile.getInputStream(entry)) {
if (inputStream.skip(pos) != pos) {
throw new IllegalStateException();
}
buffer.write(0, IOUtils.toByteArray(inputStream, count), 0, count);
}
pos += count;
return count;
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public int write(byte[] data) {
throw new UnsupportedOperationException();
}
@Override
public int lseek(int offset, int whence) {
switch (whence) {
case SEEK_SET:
pos = offset;
return pos;
case SEEK_CUR:
pos += offset;
return pos;
case SEEK_END:
pos = (int) entry.getSize() + offset;
return pos;
}
return super.lseek(offset, whence);
}
@Override
protected byte[] getMmapData(long addr, int offset, int length) {
try (JarFile jarFile = new JarFile(this.jarFile); InputStream inputStream = jarFile.getInputStream(entry)) {
if (offset == 0 && length == entry.getSize()) {
return IOUtils.toByteArray(inputStream);
} else {
if (inputStream.skip(offset) != offset) {
throw new IllegalStateException();
}
return IOUtils.toByteArray(inputStream, length);
}
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override | public int ioctl(Emulator<?> emulator, long request, long argp) { | 0 | 2023-10-17 06:13:28+00:00 | 8k |
EyeOfDarkness/FlameOut | src/flame/effects/Severation.java | [
{
"identifier": "Utils",
"path": "src/flame/Utils.java",
"snippet": "public class Utils{\n public static Rect r = new Rect(), r2 = new Rect();\n static Vec2 v2 = new Vec2(), v3 = new Vec2(), v4 = new Vec2();\n static BasicPool<Hit> hpool = new BasicPool<>(Hit::new);\n static Seq<Hit> hseq = ... | import arc.*;
import arc.func.*;
import arc.graphics.*;
import arc.graphics.g2d.*;
import arc.math.*;
import arc.math.geom.*;
import arc.math.geom.QuadTree.*;
import arc.struct.*;
import arc.util.*;
import arc.util.pooling.*;
import arc.util.pooling.Pool.*;
import flame.*;
import flame.Utils.*;
import flame.entities.*;
import flame.entities.RenderGroupEntity.*;
import mindustry.entities.*;
import mindustry.game.*;
import mindustry.game.EventType.*;
import mindustry.graphics.*;
import mindustry.type.*;
import static arc.math.geom.Intersector.*;
import static arc.math.geom.Geometry.*;
import static mindustry.Vars.*; | 7,171 |
/*
float cwx = centerX * width, cwy = centerY * height;
tmpVec.set(x1, y1).sub(x + cwx, y + cwy).rotate(-rotation);
x1 = tmpVec.x / width;
y1 = tmpVec.y / height;
tmpVec.set(x2, y2).sub(x + cwx, y + cwy).rotate(-rotation);
x2 = tmpVec.x / width;
y2 = tmpVec.y / height;
*/
/*
Effect eff = Fx.hitBulletColor;
Color col = Tmp.c1.rand();
Vec2 v = unproject(x1, y1);
eff.at(v.x, v.y, 0, col);
unproject(x2, y2);
eff.at(v.x, v.y, 0, col);
col.rand();
eff.at(ox, oy, 0, col);
*/
/*
Tmp.v1.set(v.x, v.y).sub(x, y).rotate(-rotation);
float vx = Tmp.v1.x / width + centerX;
float vy = Tmp.v1.y / height + centerY;
unproject(vx, vy);
eff.at(v.x, v.y, 0, col.rand());
*/
Seq<Severation> s = cut(x1, y1, x2, y2);
if(!s.isEmpty()){
for(Severation c : s){
//if(c.area < 4f * 4f) continue;
c.explosionEffect = explosionEffect;
float dx = c.centerX - centerX;
float dy = c.centerY - centerY;
tmpVec.set(dx, dy).scl(width, height).rotate(rotation).add(x, y);
c.rotation = rotation;
c.x = tmpVec.x;
c.y = tmpVec.y;
c.vx += vx;
c.vy += vy;
force.get(c);
c.add();
}
wasCut = true;
remove();
}
}
@Override
public void update(){
x += vx * Time.delta;
y += vy * Time.delta;
rotation += vr * Time.delta;
zTime = Mathf.clamp(zTime + Time.delta / 40f);
float drg = zTime < 1 ? drag : 0.2f;
vx *= 1f - drg * Time.delta;
vy *= 1f - drg * Time.delta;
vr *= 1f - drg * Time.delta;
if(time >= lifetime){
float b = Mathf.sqrt(area / 4f);
explosionEffect.at(x, y, b);
float shake = b / 3f;
Effect.shake(shake, shake, x, y);
remove();
}
float speed = area < minArea ? 2f : 1f;
time += Time.delta * speed;
}
@Override
public void hitbox(Rect out){
out.setCentered(x, y, bounds);
}
Vec2 unproject(float x, float y){
return Tmp.v1.set((x - centerX) * width, (y - centerY) * height).rotate(rotation).add(this.x, this.y);
}
public void drawRender(){
//return tmpVerts;
//return null;
float sin = Mathf.sinDeg(rotation);
float cos = Mathf.cosDeg(rotation);
float col = color, mcol = Color.clearFloatBits;
TextureRegion r = region;
for(CutTri t : tris){
float[] pos = t.pos, verts = tmpVerts;
int vertI = 0;
for(int i = 0; i < 8; i += 2){
int mi = Math.min(i, 4);
float vx = (pos[mi] - centerX) * width;
float vy = (pos[mi + 1] - centerY) * height;
float tx = (vx * cos - vy * sin) + x;
float ty = (vx * sin + vy * cos) + y;
verts[vertI] = tx;
verts[vertI + 1] = ty;
verts[vertI + 2] = col;
verts[vertI + 3] = Mathf.lerp(r.u, r.u2, pos[mi]);
verts[vertI + 4] = Mathf.lerp(r.v2, r.v, pos[mi + 1]);
verts[vertI + 5] = mcol;
vertI += 6;
}
//Draw.z(trueZ);
//Draw.vert(region.texture, verts, 0, 24); | package flame.effects;
/**
* @author EyeOfDarkness
*/
public class Severation extends DrawEntity implements QuadTreeObject{
static FloatSeq intersections = new FloatSeq(), side1 = new FloatSeq(), side2 = new FloatSeq();
static Seq<CutTri> returnTri = new Seq<>(), tmpTris = new Seq<>(), tmpTris2 = new Seq<>();
static Seq<Severation> tmpCuts = new Seq<>();
static Vec2 tmpVec = new Vec2(), tmpVec2 = new Vec2(), tmpVec3 = new Vec2();
static float[] tmpVerts = new float[24];
static float minArea = 4f * 4f;
static int slashIDs = 0;
static QuadTree<Severation> cutTree;
static Seq<Severation> cutsSeq = new Seq<>();
static Seq<Slash> slashes = new Seq<>();
static Pool<Slash> slashPool = new BasicPool<>(Slash::new);
Seq<CutTri> tris = new Seq<>();
float bounds = 0f, area = 0f;
float centerX, centerY;
float rotation;
float width, height;
TextureRegion region;
IntSet collided = new IntSet();
public float color = Color.whiteFloatBits;
public float z = Layer.flyingUnit, shadowZ, zTime;
public Effect explosionEffect = FlameFX.fragmentExplosion;
float time = 0f, lifetime = 3f * 60f;
public float vx, vy, vr;
public float drag = 0.05f;
public boolean wasCut = false;
public static void init(){
Events.on(ResetEvent.class, e -> {
slashes.clear();
cutsSeq.clear();
});
Events.on(EventType.WorldLoadEvent.class, e -> cutTree = new QuadTree<>(new Rect(-finalWorldBounds, -finalWorldBounds, world.width() * tilesize + finalWorldBounds * 2, world.height() * tilesize + finalWorldBounds * 2)));
}
public static void updateStatic(){
if(state.isGame()){
if(cutTree != null){
cutTree.clear();
for(Severation cuts : cutsSeq){
cutTree.insert(cuts);
}
}
if(!slashes.isEmpty()){
slashes.removeAll(s -> {
Utils.intersectLine(cutTree, 1f, s.x1, s.y1, s.x2, s.y2, (c, x, y) -> {
Rect b = Tmp.r3;
c.hitbox(b);
if(!b.contains(s.x1, s.y1) && !b.contains(s.x2, s.y2) && c.collided.add(s.id)){
//float len = Mathf.random(0.8f, 1.2f);
c.cutWorld(s.x1, s.y1, s.x2, s.y2, cc -> {
Vec2 n = nearestSegmentPoint(s.x1, s.y1, s.x2, s.y2, cc.x, cc.y, tmpVec3);
int side = pointLineSide(s.x1, s.y1, s.x2, s.y2, cc.x, cc.y);
//float len = Mathf.rand
//n.sub(cc.x, cc.y).nor().scl(-1.5f * len);
float dst = n.dst(cc.x, cc.y);
n.sub(cc.x, cc.y).scl((-2.5f) / 20f).limit(3f);
cc.vx /= 1.5f;
cc.vy /= 1.5f;
cc.vr /= 1.5f;
cc.vx += n.x;
cc.vy += n.y;
//cc.vr += -2f * side;
cc.vr += (-5f * side) / (1f + dst / 5f);
});
}
});
s.time += Time.delta;
if(s.time >= 4f) slashPool.free(s);
return s.time >= 4f;
});
}
}
}
public static void slash(float x1, float y1, float x2, float y2){
Slash s = slashPool.obtain();
s.x1 = x1;
s.y1 = y1;
s.x2 = x2;
s.y2 = y2;
slashes.add(s);
}
public static Severation generate(TextureRegion region, float x, float y, float width, float height, float rotation){
Severation c = new Severation();
c.region = region;
c.width = width;
c.height = height;
c.rotation = rotation;
c.x = x;
c.y = y;
for(int i = 0; i < 2; i++){
CutTri tr = new CutTri();
float[] p = tr.pos;
p[0] = i == 0 ? 0f : 1f;
p[1] = i == 0 ? 0f : 1f;
p[2] = 1f;
p[3] = 0f;
p[4] = 0f;
p[5] = 1f;
c.tris.add(tr);
}
c.updateBounds();
c.add();
return c;
}
public void cutWorld(float x1, float y1, float x2, float y2, Cons<Severation> force){
if(!added || area < minArea) return;
if(force == null){
float fx1 = x1, fy1 = y1, fx2 = x2, fy2 = y2;
force = cc -> {
Vec2 n = nearestSegmentPoint(fx1, fy1, fx2, fy2, cc.x, cc.y, tmpVec2);
int side = pointLineSide(fx1, fy1, fx2, fy2, cc.x, cc.y);
//float len = Mathf.rand
//n.sub(cc.x, cc.y).nor().scl(-1.5f * len);
float dst = n.dst(cc.x, cc.y);
n.sub(cc.x, cc.y).scl((-2.5f) / 20f).limit(3f);
cc.vx /= 1.5f;
cc.vy /= 1.5f;
cc.vr /= 1.5f;
cc.vx += n.x;
cc.vy += n.y;
//cc.vr += -2f * side;
cc.vr += (-5f * side) / (1f + dst / 5f);
};
}
tmpVec.set(x1, y1).sub(x, y).rotate(-rotation);
x1 = tmpVec.x / width + centerX;
y1 = tmpVec.y / height + centerY;
tmpVec.set(x2, y2).sub(x, y).rotate(-rotation);
x2 = tmpVec.x / width + centerX;
y2 = tmpVec.y / height + centerY;
/*
float cwx = centerX * width, cwy = centerY * height;
tmpVec.set(x1, y1).sub(x + cwx, y + cwy).rotate(-rotation);
x1 = tmpVec.x / width;
y1 = tmpVec.y / height;
tmpVec.set(x2, y2).sub(x + cwx, y + cwy).rotate(-rotation);
x2 = tmpVec.x / width;
y2 = tmpVec.y / height;
*/
/*
Effect eff = Fx.hitBulletColor;
Color col = Tmp.c1.rand();
Vec2 v = unproject(x1, y1);
eff.at(v.x, v.y, 0, col);
unproject(x2, y2);
eff.at(v.x, v.y, 0, col);
col.rand();
eff.at(ox, oy, 0, col);
*/
/*
Tmp.v1.set(v.x, v.y).sub(x, y).rotate(-rotation);
float vx = Tmp.v1.x / width + centerX;
float vy = Tmp.v1.y / height + centerY;
unproject(vx, vy);
eff.at(v.x, v.y, 0, col.rand());
*/
Seq<Severation> s = cut(x1, y1, x2, y2);
if(!s.isEmpty()){
for(Severation c : s){
//if(c.area < 4f * 4f) continue;
c.explosionEffect = explosionEffect;
float dx = c.centerX - centerX;
float dy = c.centerY - centerY;
tmpVec.set(dx, dy).scl(width, height).rotate(rotation).add(x, y);
c.rotation = rotation;
c.x = tmpVec.x;
c.y = tmpVec.y;
c.vx += vx;
c.vy += vy;
force.get(c);
c.add();
}
wasCut = true;
remove();
}
}
@Override
public void update(){
x += vx * Time.delta;
y += vy * Time.delta;
rotation += vr * Time.delta;
zTime = Mathf.clamp(zTime + Time.delta / 40f);
float drg = zTime < 1 ? drag : 0.2f;
vx *= 1f - drg * Time.delta;
vy *= 1f - drg * Time.delta;
vr *= 1f - drg * Time.delta;
if(time >= lifetime){
float b = Mathf.sqrt(area / 4f);
explosionEffect.at(x, y, b);
float shake = b / 3f;
Effect.shake(shake, shake, x, y);
remove();
}
float speed = area < minArea ? 2f : 1f;
time += Time.delta * speed;
}
@Override
public void hitbox(Rect out){
out.setCentered(x, y, bounds);
}
Vec2 unproject(float x, float y){
return Tmp.v1.set((x - centerX) * width, (y - centerY) * height).rotate(rotation).add(this.x, this.y);
}
public void drawRender(){
//return tmpVerts;
//return null;
float sin = Mathf.sinDeg(rotation);
float cos = Mathf.cosDeg(rotation);
float col = color, mcol = Color.clearFloatBits;
TextureRegion r = region;
for(CutTri t : tris){
float[] pos = t.pos, verts = tmpVerts;
int vertI = 0;
for(int i = 0; i < 8; i += 2){
int mi = Math.min(i, 4);
float vx = (pos[mi] - centerX) * width;
float vy = (pos[mi + 1] - centerY) * height;
float tx = (vx * cos - vy * sin) + x;
float ty = (vx * sin + vy * cos) + y;
verts[vertI] = tx;
verts[vertI + 1] = ty;
verts[vertI + 2] = col;
verts[vertI + 3] = Mathf.lerp(r.u, r.u2, pos[mi]);
verts[vertI + 4] = Mathf.lerp(r.v2, r.v, pos[mi + 1]);
verts[vertI + 5] = mcol;
vertI += 6;
}
//Draw.z(trueZ);
//Draw.vert(region.texture, verts, 0, 24); | DrawnRegion reg = RenderGroupEntity.draw(Blending.normal, z, r.texture, verts, 0); | 1 | 2023-10-18 08:41:59+00:00 | 8k |
ItzGreenCat/SkyImprover | src/main/java/me/greencat/skyimprover/SkyImprover.java | [
{
"identifier": "Config",
"path": "src/main/java/me/greencat/skyimprover/config/Config.java",
"snippet": "public class Config extends MidnightConfig {\n @Comment(category = \"render\")\n public static Comment damageSplash;\n @Entry(category = \"render\")\n public static boolean damageSplashE... | import eu.midnightdust.lib.config.MidnightConfig;
import me.greencat.skyimprover.config.Config;
import me.greencat.skyimprover.feature.FeatureLoader;
import me.greencat.skyimprover.feature.damageSplash.DamageSplash;
import me.greencat.skyimprover.feature.dungeonDeathMessage.DungeonDeathMessage;
import me.greencat.skyimprover.feature.kuudraHelper.KuudraHelper;
import me.greencat.skyimprover.feature.m3Freeze.M3FreezeHelper;
import me.greencat.skyimprover.feature.rainTimer.RainTimer;
import me.greencat.skyimprover.utils.LocationUtils;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; | 4,757 | package me.greencat.skyimprover;
public class SkyImprover implements ClientModInitializer {
public static final String MODID = "skyimprover";
@Override
public void onInitializeClient() { | package me.greencat.skyimprover;
public class SkyImprover implements ClientModInitializer {
public static final String MODID = "skyimprover";
@Override
public void onInitializeClient() { | MidnightConfig.init(MODID, Config.class); | 0 | 2023-10-19 09:19:09+00:00 | 8k |
histevehu/12306 | business/src/main/java/com/steve/train/business/mapper/StationMapper.java | [
{
"identifier": "Station",
"path": "business/src/main/java/com/steve/train/business/domain/Station.java",
"snippet": "public class Station {\n private Long id;\n\n private String name;\n\n private String namePinyin;\n\n private String namePy;\n\n private Date createTime;\n\n private Da... | import com.steve.train.business.domain.Station;
import com.steve.train.business.domain.StationExample;
import org.apache.ibatis.annotations.Param;
import java.util.List; | 4,788 | package com.steve.train.business.mapper;
public interface StationMapper {
long countByExample(StationExample example);
int deleteByExample(StationExample example);
int deleteByPrimaryKey(Long id);
| package com.steve.train.business.mapper;
public interface StationMapper {
long countByExample(StationExample example);
int deleteByExample(StationExample example);
int deleteByPrimaryKey(Long id);
| int insert(Station record); | 0 | 2023-10-23 01:20:56+00:00 | 8k |
team-moabam/moabam-BE | src/test/java/com/moabam/api/domain/coupon/repository/CouponWalletSearchRepositoryTest.java | [
{
"identifier": "CouponFixture",
"path": "src/test/java/com/moabam/support/fixture/CouponFixture.java",
"snippet": "public final class CouponFixture {\n\n\tpublic static final String DISCOUNT_1000_COUPON_NAME = \"황금벌레 1000원 할인\";\n\tpublic static final String DISCOUNT_10000_COUPON_NAME = \"황금벌레 10000원 할... | import static com.moabam.support.fixture.CouponFixture.*;
import static org.assertj.core.api.Assertions.*;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.springframework.beans.factory.annotation.Autowired;
import com.moabam.api.domain.coupon.Coupon;
import com.moabam.api.domain.coupon.CouponWallet;
import com.moabam.global.error.exception.NotFoundException;
import com.moabam.global.error.model.ErrorMessage;
import com.moabam.support.annotation.QuerydslRepositoryTest;
import com.moabam.support.fixture.CouponFixture; | 6,338 | package com.moabam.api.domain.coupon.repository;
@QuerydslRepositoryTest
class CouponWalletSearchRepositoryTest {
@Autowired
private CouponRepository couponRepository;
@Autowired
private CouponWalletRepository couponWalletRepository;
@Autowired
private CouponWalletSearchRepository couponWalletSearchRepository;
@DisplayName("나의 쿠폰함의 특정 쿠폰을 조회한다. - List<CouponWallet>")
@Test
void findAllByIdAndMemberId_success() {
// Given
Coupon coupon = couponRepository.save(CouponFixture.coupon()); | package com.moabam.api.domain.coupon.repository;
@QuerydslRepositoryTest
class CouponWalletSearchRepositoryTest {
@Autowired
private CouponRepository couponRepository;
@Autowired
private CouponWalletRepository couponWalletRepository;
@Autowired
private CouponWalletSearchRepository couponWalletSearchRepository;
@DisplayName("나의 쿠폰함의 특정 쿠폰을 조회한다. - List<CouponWallet>")
@Test
void findAllByIdAndMemberId_success() {
// Given
Coupon coupon = couponRepository.save(CouponFixture.coupon()); | CouponWallet couponWallet = couponWalletRepository.save(CouponWallet.create(1L, coupon)); | 2 | 2023-10-20 06:15:43+00:00 | 8k |
liukanshan1/PrivateTrace-Core | src/main/java/Priloc/protocol/TestEncode.java | [
{
"identifier": "TimeLocationData",
"path": "src/main/java/Priloc/data/TimeLocationData.java",
"snippet": "public class TimeLocationData implements Serializable {\n private Location loc;\n private Date date;\n private double accuracy = Constant.RADIUS;\n private TimeLocationData nTLD = null;... | import Priloc.data.TimeLocationData;
import Priloc.data.Trajectory;
import Priloc.data.TrajectoryReader;
import Priloc.geo.Location;
import Priloc.utils.Constant;
import java.util.List;
import static java.lang.System.exit; | 3,969 | package Priloc.protocol;
public class TestEncode {
// public static void main(String[] args) throws Exception {
// String[] negativePath = new String[]{
// "./Geolife Trajectories 1.3/Data/000/Trajectory/20090503033926.plt",
// "./Geolife Trajectories 1.3/Data/000/Trajectory/20090705025307.plt"
// };
// TrajectoryReader[] negativeReaders = new TrajectoryReader[negativePath.length];
// for (int i = 0; i < negativePath.length; i++) {
// negativeReaders[i] = new TrajectoryReader(negativePath[i]);
// }
// Trajectory[] negativeTrajectories = new Trajectory[negativePath.length];
// for (int i = 0; i < negativePath.length; i++) {
// negativeTrajectories[i] = negativeReaders[i].load();
// }
// double maxError = 0;
// for (int i = 0; i < negativeTrajectories.length; i++) {
// List<TimeLocationData> tlds = negativeTrajectories[i].getTLDs();
// for(int j = 0; j < tlds.size() - 1; j++) {
// Location l1 = tlds.get(j).getLoc();
// Location l2 = tlds.get(j + 1).getLoc();
// double expect = l1.distance(l2);
// if (expect > 2 * Constant.RADIUS) {
// continue;
// }
// double actual = l1.encodeDistance(l2);
// //System.out.println(Math.abs(expect - actual));
// if (Math.abs(expect - actual) > maxError) {
// maxError = Math.abs(expect - actual);
// System.out.println(maxError);
// }
//// if (Math.abs(expect - actual) > 1) {
//// System.out.println(l1);
//// System.out.println(l2);
//// System.out.println(expect);
//// System.out.println(actual);
//// }
// }
// }
// }
public static void main(String[] args) throws Exception {
String[] negativePath = new String[]{
"./C++/dataset",
};
TrajectoryReader[] negativeReaders = new TrajectoryReader[negativePath.length];
for (int i = 0; i < negativePath.length; i++) {
negativeReaders[i] = new TrajectoryReader(negativePath[i]);
}
Trajectory[] negativeTrajectories = new Trajectory[negativePath.length];
for (int i = 0; i < negativePath.length; i++) {
negativeTrajectories[i] = negativeReaders[i].load();
}
double maxError = 0;
for (int i = 0; i < negativeTrajectories.length; i++) { | package Priloc.protocol;
public class TestEncode {
// public static void main(String[] args) throws Exception {
// String[] negativePath = new String[]{
// "./Geolife Trajectories 1.3/Data/000/Trajectory/20090503033926.plt",
// "./Geolife Trajectories 1.3/Data/000/Trajectory/20090705025307.plt"
// };
// TrajectoryReader[] negativeReaders = new TrajectoryReader[negativePath.length];
// for (int i = 0; i < negativePath.length; i++) {
// negativeReaders[i] = new TrajectoryReader(negativePath[i]);
// }
// Trajectory[] negativeTrajectories = new Trajectory[negativePath.length];
// for (int i = 0; i < negativePath.length; i++) {
// negativeTrajectories[i] = negativeReaders[i].load();
// }
// double maxError = 0;
// for (int i = 0; i < negativeTrajectories.length; i++) {
// List<TimeLocationData> tlds = negativeTrajectories[i].getTLDs();
// for(int j = 0; j < tlds.size() - 1; j++) {
// Location l1 = tlds.get(j).getLoc();
// Location l2 = tlds.get(j + 1).getLoc();
// double expect = l1.distance(l2);
// if (expect > 2 * Constant.RADIUS) {
// continue;
// }
// double actual = l1.encodeDistance(l2);
// //System.out.println(Math.abs(expect - actual));
// if (Math.abs(expect - actual) > maxError) {
// maxError = Math.abs(expect - actual);
// System.out.println(maxError);
// }
//// if (Math.abs(expect - actual) > 1) {
//// System.out.println(l1);
//// System.out.println(l2);
//// System.out.println(expect);
//// System.out.println(actual);
//// }
// }
// }
// }
public static void main(String[] args) throws Exception {
String[] negativePath = new String[]{
"./C++/dataset",
};
TrajectoryReader[] negativeReaders = new TrajectoryReader[negativePath.length];
for (int i = 0; i < negativePath.length; i++) {
negativeReaders[i] = new TrajectoryReader(negativePath[i]);
}
Trajectory[] negativeTrajectories = new Trajectory[negativePath.length];
for (int i = 0; i < negativePath.length; i++) {
negativeTrajectories[i] = negativeReaders[i].load();
}
double maxError = 0;
for (int i = 0; i < negativeTrajectories.length; i++) { | List<TimeLocationData> tlds = negativeTrajectories[i].getTLDs(); | 0 | 2023-10-22 06:28:51+00:00 | 8k |
tuxming/xmfx | BaseUI/src/main/java/com/xm2013/jfx/control/listview/XmCheckBoxListCell.java | [
{
"identifier": "ColorType",
"path": "BaseUI/src/main/java/com/xm2013/jfx/control/base/ColorType.java",
"snippet": "public class ColorType {\n /**\n * 主要颜色\n */\n public static String PRIMARY = \"#4c14c1ff\";\n public static String SECONDARY=\"#585858ff\";\n public static String DANG... | import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.SetChangeListener;
import javafx.css.PseudoClass;
import javafx.geometry.Pos;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.util.Callback;
import javafx.util.StringConverter;
import com.xm2013.jfx.control.base.ColorType;
import com.xm2013.jfx.control.checkbox.XmCheckBox;
import com.xm2013.jfx.control.base.CellUtils;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty; | 6,822 | /*
* Copyright (c) 2012, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.xm2013.jfx.control.listview;
/**
* A class containing a {@link ListCell} implementation that draws a
* {@link CheckBox} node inside the cell, optionally with a label to indicate
* what the checkbox represents.
*
* <p>The CheckBoxListCell is rendered with a CheckBox on the left-hand side of
* the {@link ListView}, and the text related to the list item taking up all
* remaining horizontal space.
*
* <p>To construct an instance of this class, it is necessary to provide a
* {@link Callback} that, given an object of type T, will return a
* {@code ObservableValue<Boolean>} that represents whether the given item is
* selected or not. This ObservableValue will be bound bidirectionally (meaning
* that the CheckBox in the cell will set/unset this property based on user
* interactions, and the CheckBox will reflect the state of the
* {@code ObservableValue<Boolean>}, if it changes externally).
*
* <p>Note that the CheckBoxListCell renders the CheckBox 'live', meaning that
* the CheckBox is always interactive and can be directly toggled by the user.
* This means that it is not necessary that the cell enter its
* {@link #editingProperty() editing state} (usually by the user double-clicking
* on the cell). A side-effect of this is that the usual editing callbacks
* (such as {@link ListView#onEditCommitProperty() on edit commit})
* will <strong>not</strong> be called. If you want to be notified of changes,
* it is recommended to directly observe the boolean properties that are
* manipulated by the CheckBox.</p>
*
* @see CheckBox
* @see ListCell
* @param <T> The type of the elements contained within the ListView.
* @since JavaFX 2.2
*/
public class XmCheckBoxListCell<T> extends XmListCell<T> {
/* *************************************************************************
* *
* Static cell factories *
* *
**************************************************************************/
/**
* Creates a cell factory for use in ListView controls. When used in a
* ListView, the {@link XmCheckBoxListCell} is rendered with a CheckBox on the
* left-hand side of the ListView, with the text related to the list item
* taking up all remaining horizontal space.
*
* @param <T> The type of the elements contained within the ListView.
* @param getSelectedProperty A {@link Callback} that, given an object of
* type T (which is a value taken out of the
* {@code ListView<T>.items} list),
* will return an {@code ObservableValue<Boolean>} that represents
* whether the given item is selected or not. This ObservableValue will
* be bound bidirectionally (meaning that the CheckBox in the cell will
* set/unset this property based on user interactions, and the CheckBox
* will reflect the state of the ObservableValue, if it changes
* externally).
* @return A {@link Callback} that will return a ListCell that is able to
* work on the type of element contained within the ListView items list.
*/
public static <T> Callback<ListView<T>, ListCell<T>> forListView(
final Callback<T, ObservableValue<Boolean>> getSelectedProperty) {
return forListView(getSelectedProperty, CellUtils.<T>defaultStringConverter());
}
/**
* Creates a cell factory for use in ListView controls. When used in a
* ListView, the {@link XmCheckBoxListCell} is rendered with a CheckBox on the
* left-hand side of the ListView, with the text related to the list item
* taking up all remaining horizontal space.
*
* @param <T> The type of the elements contained within the ListView.
* @param getSelectedProperty A {@link Callback} that, given an object
* of type T (which is a value taken out of the
* {@code ListView<T>.items} list),
* will return an {@code ObservableValue<Boolean>} that represents
* whether the given item is selected or not. This ObservableValue will
* be bound bidirectionally (meaning that the CheckBox in the cell will
* set/unset this property based on user interactions, and the CheckBox
* will reflect the state of the ObservableValue, if it changes
* externally).
* @param converter A StringConverter that, give an object of type T, will
* return a String that can be used to represent the object visually.
* @return A {@link Callback} that will return a ListCell that is able to
* work on the type of element contained within the ListView.
*/
public static <T> Callback<ListView<T>, ListCell<T>> forListView(
final Callback<T, ObservableValue<Boolean>> getSelectedProperty,
final StringConverter<T> converter) {
return list -> new XmCheckBoxListCell<T>(getSelectedProperty, converter);
}
/* *************************************************************************
* *
* Fields *
* *
**************************************************************************/
private final XmCheckBox checkBox;
private static PseudoClass selected = PseudoClass.getPseudoClass("selected");
private ObservableValue<Boolean> booleanProperty = new SimpleBooleanProperty();
/* *************************************************************************
* *
* Constructors *
* *
**************************************************************************/
/**
* Creates a default CheckBoxListCell.
*/
public XmCheckBoxListCell() {
this(null);
}
/**
* Creates a default CheckBoxListCell.
*
* @param getSelectedProperty A {@link Callback} that will return an
* {@code ObservableValue<Boolean>} given an item from the ListView.
*/
public XmCheckBoxListCell(
final Callback<T, ObservableValue<Boolean>> getSelectedProperty) {
this(getSelectedProperty, CellUtils.<T>defaultStringConverter());
}
/**
* Creates a CheckBoxListCell with a custom string converter.
*
* @param getSelectedProperty A {@link Callback} that will return an
* {@code ObservableValue<Boolean>} given an item from the ListView.
* @param converter A StringConverter that, given an object of type T, will
* return a String that can be used to represent the object visually.
*/
public XmCheckBoxListCell(
Callback<T, ObservableValue<Boolean>> getSelectedProperty,
final StringConverter<T> converter) {
this.getStyleClass().add("check-box-list-cell");
setSelectedStateCallback(getSelectedProperty);
setConverter(converter);
this.checkBox = new XmCheckBox();
this.checkBox.setMouseTransparent(true);
setAlignment(Pos.CENTER_LEFT);
setContentDisplay(ContentDisplay.LEFT);
addEventFilter(MouseEvent.MOUSE_CLICKED, e -> {
checkBox.setSelected(!checkBox.isSelected());
});
checkBox.selectedProperty().addListener((ob, ov, nv)->{
T item = getItem();
XmListView listView = (XmListView) getListView();
if(nv){
boolean contains = listView.getCheckedValues().contains(item);
if(!contains){
listView.addCheckedValue(item);
}
}else{
listView.getCheckedValues().remove(item);
}
});
getPseudoClassStates().addListener((SetChangeListener<PseudoClass>) change -> setCheckBoxColor());
listViewProperty().addListener((observable, oldValue, newValue) -> setCheckBoxColor());
itemProperty().addListener((observable, oldValue, newValue) -> {
boolean checked = ((XmListView)getListView()).getCheckedValues().contains(newValue);
if(checked){
checkBox.setSelected(true);
}else{
checkBox.setSelected(false);
}
});
// by default the graphic is null until the cell stops being empty
setGraphic(null);
}
private void setCheckBoxColor(){
if(getPseudoClassStates().contains(selected)){ | /*
* Copyright (c) 2012, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.xm2013.jfx.control.listview;
/**
* A class containing a {@link ListCell} implementation that draws a
* {@link CheckBox} node inside the cell, optionally with a label to indicate
* what the checkbox represents.
*
* <p>The CheckBoxListCell is rendered with a CheckBox on the left-hand side of
* the {@link ListView}, and the text related to the list item taking up all
* remaining horizontal space.
*
* <p>To construct an instance of this class, it is necessary to provide a
* {@link Callback} that, given an object of type T, will return a
* {@code ObservableValue<Boolean>} that represents whether the given item is
* selected or not. This ObservableValue will be bound bidirectionally (meaning
* that the CheckBox in the cell will set/unset this property based on user
* interactions, and the CheckBox will reflect the state of the
* {@code ObservableValue<Boolean>}, if it changes externally).
*
* <p>Note that the CheckBoxListCell renders the CheckBox 'live', meaning that
* the CheckBox is always interactive and can be directly toggled by the user.
* This means that it is not necessary that the cell enter its
* {@link #editingProperty() editing state} (usually by the user double-clicking
* on the cell). A side-effect of this is that the usual editing callbacks
* (such as {@link ListView#onEditCommitProperty() on edit commit})
* will <strong>not</strong> be called. If you want to be notified of changes,
* it is recommended to directly observe the boolean properties that are
* manipulated by the CheckBox.</p>
*
* @see CheckBox
* @see ListCell
* @param <T> The type of the elements contained within the ListView.
* @since JavaFX 2.2
*/
public class XmCheckBoxListCell<T> extends XmListCell<T> {
/* *************************************************************************
* *
* Static cell factories *
* *
**************************************************************************/
/**
* Creates a cell factory for use in ListView controls. When used in a
* ListView, the {@link XmCheckBoxListCell} is rendered with a CheckBox on the
* left-hand side of the ListView, with the text related to the list item
* taking up all remaining horizontal space.
*
* @param <T> The type of the elements contained within the ListView.
* @param getSelectedProperty A {@link Callback} that, given an object of
* type T (which is a value taken out of the
* {@code ListView<T>.items} list),
* will return an {@code ObservableValue<Boolean>} that represents
* whether the given item is selected or not. This ObservableValue will
* be bound bidirectionally (meaning that the CheckBox in the cell will
* set/unset this property based on user interactions, and the CheckBox
* will reflect the state of the ObservableValue, if it changes
* externally).
* @return A {@link Callback} that will return a ListCell that is able to
* work on the type of element contained within the ListView items list.
*/
public static <T> Callback<ListView<T>, ListCell<T>> forListView(
final Callback<T, ObservableValue<Boolean>> getSelectedProperty) {
return forListView(getSelectedProperty, CellUtils.<T>defaultStringConverter());
}
/**
* Creates a cell factory for use in ListView controls. When used in a
* ListView, the {@link XmCheckBoxListCell} is rendered with a CheckBox on the
* left-hand side of the ListView, with the text related to the list item
* taking up all remaining horizontal space.
*
* @param <T> The type of the elements contained within the ListView.
* @param getSelectedProperty A {@link Callback} that, given an object
* of type T (which is a value taken out of the
* {@code ListView<T>.items} list),
* will return an {@code ObservableValue<Boolean>} that represents
* whether the given item is selected or not. This ObservableValue will
* be bound bidirectionally (meaning that the CheckBox in the cell will
* set/unset this property based on user interactions, and the CheckBox
* will reflect the state of the ObservableValue, if it changes
* externally).
* @param converter A StringConverter that, give an object of type T, will
* return a String that can be used to represent the object visually.
* @return A {@link Callback} that will return a ListCell that is able to
* work on the type of element contained within the ListView.
*/
public static <T> Callback<ListView<T>, ListCell<T>> forListView(
final Callback<T, ObservableValue<Boolean>> getSelectedProperty,
final StringConverter<T> converter) {
return list -> new XmCheckBoxListCell<T>(getSelectedProperty, converter);
}
/* *************************************************************************
* *
* Fields *
* *
**************************************************************************/
private final XmCheckBox checkBox;
private static PseudoClass selected = PseudoClass.getPseudoClass("selected");
private ObservableValue<Boolean> booleanProperty = new SimpleBooleanProperty();
/* *************************************************************************
* *
* Constructors *
* *
**************************************************************************/
/**
* Creates a default CheckBoxListCell.
*/
public XmCheckBoxListCell() {
this(null);
}
/**
* Creates a default CheckBoxListCell.
*
* @param getSelectedProperty A {@link Callback} that will return an
* {@code ObservableValue<Boolean>} given an item from the ListView.
*/
public XmCheckBoxListCell(
final Callback<T, ObservableValue<Boolean>> getSelectedProperty) {
this(getSelectedProperty, CellUtils.<T>defaultStringConverter());
}
/**
* Creates a CheckBoxListCell with a custom string converter.
*
* @param getSelectedProperty A {@link Callback} that will return an
* {@code ObservableValue<Boolean>} given an item from the ListView.
* @param converter A StringConverter that, given an object of type T, will
* return a String that can be used to represent the object visually.
*/
public XmCheckBoxListCell(
Callback<T, ObservableValue<Boolean>> getSelectedProperty,
final StringConverter<T> converter) {
this.getStyleClass().add("check-box-list-cell");
setSelectedStateCallback(getSelectedProperty);
setConverter(converter);
this.checkBox = new XmCheckBox();
this.checkBox.setMouseTransparent(true);
setAlignment(Pos.CENTER_LEFT);
setContentDisplay(ContentDisplay.LEFT);
addEventFilter(MouseEvent.MOUSE_CLICKED, e -> {
checkBox.setSelected(!checkBox.isSelected());
});
checkBox.selectedProperty().addListener((ob, ov, nv)->{
T item = getItem();
XmListView listView = (XmListView) getListView();
if(nv){
boolean contains = listView.getCheckedValues().contains(item);
if(!contains){
listView.addCheckedValue(item);
}
}else{
listView.getCheckedValues().remove(item);
}
});
getPseudoClassStates().addListener((SetChangeListener<PseudoClass>) change -> setCheckBoxColor());
listViewProperty().addListener((observable, oldValue, newValue) -> setCheckBoxColor());
itemProperty().addListener((observable, oldValue, newValue) -> {
boolean checked = ((XmListView)getListView()).getCheckedValues().contains(newValue);
if(checked){
checkBox.setSelected(true);
}else{
checkBox.setSelected(false);
}
});
// by default the graphic is null until the cell stops being empty
setGraphic(null);
}
private void setCheckBoxColor(){
if(getPseudoClassStates().contains(selected)){ | checkBox.setColorType(ColorType.other(Color.WHITE)); | 0 | 2023-10-17 08:57:08+00:00 | 8k |
Dwight-Studio/JArmEmu | src/main/java/fr/dwightstudio/jarmemu/asm/inst/STRExecutor.java | [
{
"identifier": "DataMode",
"path": "src/main/java/fr/dwightstudio/jarmemu/asm/DataMode.java",
"snippet": "public enum DataMode {\n HALF_WORD,\n BYTE;\n\n @Override\n public String toString() {\n return name().substring(0,1);\n }\n\n public static DataMode customValueOf(String n... | import fr.dwightstudio.jarmemu.sim.parse.args.ShiftParser;
import fr.dwightstudio.jarmemu.asm.DataMode;
import fr.dwightstudio.jarmemu.asm.UpdateMode;
import fr.dwightstudio.jarmemu.sim.exceptions.IllegalDataWritingASMException;
import fr.dwightstudio.jarmemu.sim.exceptions.MemoryAccessMisalignedASMException;
import fr.dwightstudio.jarmemu.sim.obj.Register;
import fr.dwightstudio.jarmemu.sim.obj.StateContainer;
import fr.dwightstudio.jarmemu.sim.parse.args.AddressParser; | 6,094 | /*
* ____ _ __ __ _____ __ ___
* / __ \_ __(_)___ _/ /_ / /_ / ___// /___ ______/ (_)___
* / / / / | /| / / / __ `/ __ \/ __/ \__ \/ __/ / / / __ / / __ \
* / /_/ /| |/ |/ / / /_/ / / / / /_ ___/ / /_/ /_/ / /_/ / / /_/ /
* /_____/ |__/|__/_/\__, /_/ /_/\__/ /____/\__/\__,_/\__,_/_/\____/
* /____/
* Copyright (C) 2023 Dwight Studio
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package fr.dwightstudio.jarmemu.asm.inst;
public class STRExecutor implements InstructionExecutor<Register, AddressParser.UpdatableInteger, Integer, ShiftParser.ShiftFunction> {
@Override | /*
* ____ _ __ __ _____ __ ___
* / __ \_ __(_)___ _/ /_ / /_ / ___// /___ ______/ (_)___
* / / / / | /| / / / __ `/ __ \/ __/ \__ \/ __/ / / / __ / / __ \
* / /_/ /| |/ |/ / / /_/ / / / / /_ ___/ / /_/ /_/ / /_/ / / /_/ /
* /_____/ |__/|__/_/\__, /_/ /_/\__/ /____/\__/\__,_/\__,_/_/\____/
* /____/
* Copyright (C) 2023 Dwight Studio
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package fr.dwightstudio.jarmemu.asm.inst;
public class STRExecutor implements InstructionExecutor<Register, AddressParser.UpdatableInteger, Integer, ShiftParser.ShiftFunction> {
@Override | public void execute(StateContainer stateContainer, boolean forceExecution, boolean updateFlags, DataMode dataMode, UpdateMode updateMode, Register arg1, AddressParser.UpdatableInteger arg2, Integer arg3, ShiftParser.ShiftFunction arg4) { | 1 | 2023-10-17 18:22:09+00:00 | 8k |
GTNewHorizons/FarmingForEngineers | src/main/java/com/guigs44/farmingforengineers/block/BlockMarket.java | [
{
"identifier": "FarmingForEngineers",
"path": "src/main/java/com/guigs44/farmingforengineers/FarmingForEngineers.java",
"snippet": "@Mod(\n modid = FarmingForEngineers.MOD_ID,\n name = \"Farming for Engineers\",\n dependencies = \"after:mousetweaks[2.8,);after:forestry;after:agricr... | 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.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.IIcon;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import com.guigs44.farmingforengineers.FarmingForEngineers;
import com.guigs44.farmingforengineers.client.render.block.MarketBlockRenderer;
import com.guigs44.farmingforengineers.entity.EntityMerchant;
import com.guigs44.farmingforengineers.network.GuiHandler;
import com.guigs44.farmingforengineers.tile.TileMarket; | 5,189 | package com.guigs44.farmingforengineers.block;
/**
* A good chunk of the code in this file has been based on Jason Mitchell's (@mitchej123) work. Specifically:
* https://github.com/GTNewHorizons/CookingForBlockheads/blob/master/src/main/java/net/blay09/mods/cookingforblockheads/block/BlockBaseKitchen.java
* https://github.com/GTNewHorizons/CookingForBlockheads/blob/master/src/main/java/net/blay09/mods/cookingforblockheads/block/BlockOven.java
*
* Licensed under LGPL-3.0
*/
public class BlockMarket extends BlockContainer {
public EntityMerchant merchant;
// public static final PropertyDirection FACING = BlockHorizontal.FACING;
public BlockMarket() {
super(Material.wood);
setBlockName(FarmingForEngineers.MOD_ID + ":market"); // TODO: Fix the name
setStepSound(soundTypeWood);
setHardness(2f);
setResistance(10f);
setCreativeTab(FarmingForEngineers.creativeTab);
}
@Override
public void registerBlockIcons(IIconRegister reg) {}
@Override
public IIcon getIcon(int side, int meta) {
return Blocks.log.getIcon(side, 1);
}
@Override
public TileEntity createNewTileEntity(World world, int meta) {
return new TileMarket();
}
@Override
public boolean isOpaqueCube() {
return false;
}
@Override
public boolean renderAsNormalBlock() {
return false;
}
@Override
public void onBlockAdded(World worldIn, int x, int y, int z) {
super.onBlockAdded(worldIn, x, y, z);
findOrientation(worldIn, x, y, z);
}
@Override
public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase placer, ItemStack itemStack) {
int facing = MathHelper.floor_double(placer.rotationYaw * 4.0F / 360.0F + 0.5D) & 3;
switch (facing) {
case 0:
world.setBlockMetadataWithNotify(x, y, z, 2, 2);
break;
case 1:
world.setBlockMetadataWithNotify(x, y, z, 5, 2);
break;
case 2:
world.setBlockMetadataWithNotify(x, y, z, 3, 2);
break;
case 3:
world.setBlockMetadataWithNotify(x, y, z, 4, 2);
break;
}
// EnumFacing facing = EnumFacing.NORTH;
// BlockPos entityPos = pos.offset(facing.getOpposite());
EntityMerchant.SpawnAnimationType spawnAnimationType = EntityMerchant.SpawnAnimationType.MAGIC;
if (world.canBlockSeeTheSky(x, y, z)) {
spawnAnimationType = EntityMerchant.SpawnAnimationType.FALLING;
} else if (!world.isAirBlock(x, y - 1, z)) {
spawnAnimationType = EntityMerchant.SpawnAnimationType.DIGGING;
}
if (!world.isRemote) {
merchant = new EntityMerchant(world);
merchant.setMarket(x, y, z, EnumFacing.NORTH);
merchant.setToFacingAngle();
merchant.setSpawnAnimation(spawnAnimationType);
if (world.canBlockSeeTheSky(x, y, z)) {
merchant.setPosition(x + 0.5, y + 172, z + 0.5);
} else if (!world.isAirBlock(x, y, z - 1)) {
merchant.setPosition(x + 0.5, y + 0.5, z + 0.5);
} else {
merchant.setPosition(x + 0.5, y, z + 0.5);
}
world.spawnEntityInWorld(merchant);
merchant.onInitialSpawn(null);
}
if (spawnAnimationType == EntityMerchant.SpawnAnimationType.FALLING) {
world.playSound(x + 0.5, y + 1, z + 0.5, "sounds.falling", 1f, 1f, false);
} else if (spawnAnimationType == EntityMerchant.SpawnAnimationType.DIGGING) {
world.playSound(x + 0.5, y + 1, z, "sounds.falling", 1f, 1f, false);
} else {
world.playSound(x + 0.5, y + 1, z + 0.5, "item.firecharge.use", 1f, 1f, false);
for (int i = 0; i < 50; i++) {
world.spawnParticle(
"firework",
x + 0.5,
y + 1,
z + 0.5,
(Math.random() - 0.5) * 0.5f,
(Math.random() - 0.5) * 0.5f,
(Math.random() - 0.5) * 0.5f);
}
world.spawnParticle("explosion", x + 0.5, y + 1, z + 0.5, 0, 0, 0);
}
}
@Override
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float hitX,
float hitY, float hitZ) {
if (!world.isRemote) { | package com.guigs44.farmingforengineers.block;
/**
* A good chunk of the code in this file has been based on Jason Mitchell's (@mitchej123) work. Specifically:
* https://github.com/GTNewHorizons/CookingForBlockheads/blob/master/src/main/java/net/blay09/mods/cookingforblockheads/block/BlockBaseKitchen.java
* https://github.com/GTNewHorizons/CookingForBlockheads/blob/master/src/main/java/net/blay09/mods/cookingforblockheads/block/BlockOven.java
*
* Licensed under LGPL-3.0
*/
public class BlockMarket extends BlockContainer {
public EntityMerchant merchant;
// public static final PropertyDirection FACING = BlockHorizontal.FACING;
public BlockMarket() {
super(Material.wood);
setBlockName(FarmingForEngineers.MOD_ID + ":market"); // TODO: Fix the name
setStepSound(soundTypeWood);
setHardness(2f);
setResistance(10f);
setCreativeTab(FarmingForEngineers.creativeTab);
}
@Override
public void registerBlockIcons(IIconRegister reg) {}
@Override
public IIcon getIcon(int side, int meta) {
return Blocks.log.getIcon(side, 1);
}
@Override
public TileEntity createNewTileEntity(World world, int meta) {
return new TileMarket();
}
@Override
public boolean isOpaqueCube() {
return false;
}
@Override
public boolean renderAsNormalBlock() {
return false;
}
@Override
public void onBlockAdded(World worldIn, int x, int y, int z) {
super.onBlockAdded(worldIn, x, y, z);
findOrientation(worldIn, x, y, z);
}
@Override
public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase placer, ItemStack itemStack) {
int facing = MathHelper.floor_double(placer.rotationYaw * 4.0F / 360.0F + 0.5D) & 3;
switch (facing) {
case 0:
world.setBlockMetadataWithNotify(x, y, z, 2, 2);
break;
case 1:
world.setBlockMetadataWithNotify(x, y, z, 5, 2);
break;
case 2:
world.setBlockMetadataWithNotify(x, y, z, 3, 2);
break;
case 3:
world.setBlockMetadataWithNotify(x, y, z, 4, 2);
break;
}
// EnumFacing facing = EnumFacing.NORTH;
// BlockPos entityPos = pos.offset(facing.getOpposite());
EntityMerchant.SpawnAnimationType spawnAnimationType = EntityMerchant.SpawnAnimationType.MAGIC;
if (world.canBlockSeeTheSky(x, y, z)) {
spawnAnimationType = EntityMerchant.SpawnAnimationType.FALLING;
} else if (!world.isAirBlock(x, y - 1, z)) {
spawnAnimationType = EntityMerchant.SpawnAnimationType.DIGGING;
}
if (!world.isRemote) {
merchant = new EntityMerchant(world);
merchant.setMarket(x, y, z, EnumFacing.NORTH);
merchant.setToFacingAngle();
merchant.setSpawnAnimation(spawnAnimationType);
if (world.canBlockSeeTheSky(x, y, z)) {
merchant.setPosition(x + 0.5, y + 172, z + 0.5);
} else if (!world.isAirBlock(x, y, z - 1)) {
merchant.setPosition(x + 0.5, y + 0.5, z + 0.5);
} else {
merchant.setPosition(x + 0.5, y, z + 0.5);
}
world.spawnEntityInWorld(merchant);
merchant.onInitialSpawn(null);
}
if (spawnAnimationType == EntityMerchant.SpawnAnimationType.FALLING) {
world.playSound(x + 0.5, y + 1, z + 0.5, "sounds.falling", 1f, 1f, false);
} else if (spawnAnimationType == EntityMerchant.SpawnAnimationType.DIGGING) {
world.playSound(x + 0.5, y + 1, z, "sounds.falling", 1f, 1f, false);
} else {
world.playSound(x + 0.5, y + 1, z + 0.5, "item.firecharge.use", 1f, 1f, false);
for (int i = 0; i < 50; i++) {
world.spawnParticle(
"firework",
x + 0.5,
y + 1,
z + 0.5,
(Math.random() - 0.5) * 0.5f,
(Math.random() - 0.5) * 0.5f,
(Math.random() - 0.5) * 0.5f);
}
world.spawnParticle("explosion", x + 0.5, y + 1, z + 0.5, 0, 0, 0);
}
}
@Override
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float hitX,
float hitY, float hitZ) {
if (!world.isRemote) { | player.openGui(FarmingForEngineers.instance, GuiHandler.MARKET, world, x, y, z); | 3 | 2023-10-17 00:25:50+00:00 | 8k |
clclab/pcfg-lm | src/berkeley_parser/edu/berkeley/nlp/syntax/RichLabel.java | [
{
"identifier": "CollinsHeadFinder",
"path": "src/berkeley_parser/edu/berkeley/nlp/ling/CollinsHeadFinder.java",
"snippet": "public class CollinsHeadFinder extends AbstractCollinsHeadFinder {\n\n\tpublic CollinsHeadFinder() {\n\t\tthis(new PennTreebankLanguagePack());\n\t}\n\n\tprotected int postOperati... | import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import edu.berkeley.nlp.ling.CollinsHeadFinder;
import edu.berkeley.nlp.ling.HeadFinder;
import edu.berkeley.nlp.util.Pair; | 3,848 | package edu.berkeley.nlp.syntax;
/**
* Created by IntelliJ IDEA. User: aria42 Date: Oct 25, 2008 Time: 4:04:53 PM
*/
public class RichLabel {
private String headWord;
private String headTag;
private int start;
private int stop;
private int headIndex;
private String label;
private Tree<String> origNode;
public int getSpanSize() {
return stop - start;
}
public int getHeadIndex() {
return headIndex;
}
public void setHeadIndex(int headIndex) {
this.headIndex = headIndex;
}
public String getHeadWord() {
return headWord;
}
public void setHeadWord(String headWord) {
this.headWord = headWord;
}
public String getHeadTag() {
return headTag;
}
public void setHeadTag(String headTag) {
this.headTag = headTag;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getStop() {
return stop;
}
public void setStop(int stop) {
this.stop = stop;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public Tree<String> getOriginalNode() {
return origNode;
}
public void setOriginalNode(Tree<String> origNode) {
this.origNode = origNode;
}
@Override
public String toString() {
return String.format("%s(%s[%d]-%s)[%d,%d]", label, headWord,
headIndex, headTag, start, stop);
}
private static final CollinsHeadFinder cf = new CollinsHeadFinder();
public static Tree<RichLabel> getRichTree(Tree<String> tree) {
return getRichTree(tree, cf);
}
public static Tree<RichLabel> getRichTree(Tree<String> tree, | package edu.berkeley.nlp.syntax;
/**
* Created by IntelliJ IDEA. User: aria42 Date: Oct 25, 2008 Time: 4:04:53 PM
*/
public class RichLabel {
private String headWord;
private String headTag;
private int start;
private int stop;
private int headIndex;
private String label;
private Tree<String> origNode;
public int getSpanSize() {
return stop - start;
}
public int getHeadIndex() {
return headIndex;
}
public void setHeadIndex(int headIndex) {
this.headIndex = headIndex;
}
public String getHeadWord() {
return headWord;
}
public void setHeadWord(String headWord) {
this.headWord = headWord;
}
public String getHeadTag() {
return headTag;
}
public void setHeadTag(String headTag) {
this.headTag = headTag;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getStop() {
return stop;
}
public void setStop(int stop) {
this.stop = stop;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public Tree<String> getOriginalNode() {
return origNode;
}
public void setOriginalNode(Tree<String> origNode) {
this.origNode = origNode;
}
@Override
public String toString() {
return String.format("%s(%s[%d]-%s)[%d,%d]", label, headWord,
headIndex, headTag, start, stop);
}
private static final CollinsHeadFinder cf = new CollinsHeadFinder();
public static Tree<RichLabel> getRichTree(Tree<String> tree) {
return getRichTree(tree, cf);
}
public static Tree<RichLabel> getRichTree(Tree<String> tree, | HeadFinder headFinder) { | 1 | 2023-10-22 13:13:22+00:00 | 8k |
UZ9/cs-1331-drivers | src/StartMenuTests.java | [
{
"identifier": "TestFailedException",
"path": "src/com/cs1331/drivers/exception/TestFailedException.java",
"snippet": "public class TestFailedException extends Exception {\n public TestFailedException() {\n }\n\n public TestFailedException(String message) {\n super(message);\n }\n}"
... | import java.io.File;
import com.cs1331.drivers.annotations.AfterTest;
import com.cs1331.drivers.annotations.InjectData;
import com.cs1331.drivers.annotations.TestCase;
import com.cs1331.drivers.annotations.Tip;
import com.cs1331.drivers.exception.TestFailedException;
import com.cs1331.drivers.javafx.RecursiveSearch;
import com.cs1331.drivers.testing.TestFunction;
import com.cs1331.drivers.testing.TestManager;
import javafx.application.Platform;
import javafx.event.Event;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.Pane;
import javafx.stage.Stage; | 4,376 |
public class StartMenuTests {
@TestCase(name = "valid title property")
@Tip(description = "Make sure you're setting your stage title correctly!")
public void checkApplicationTitle() throws TestFailedException { |
public class StartMenuTests {
@TestCase(name = "valid title property")
@Tip(description = "Make sure you're setting your stage title correctly!")
public void checkApplicationTitle() throws TestFailedException { | TestFunction.assertEqual(StageData.stage.getTitle(), "Battleship"); | 2 | 2023-10-20 03:06:59+00:00 | 8k |
AkramLZ/ServerSync | serversync-bungee/src/main/java/me/akraml/serversync/bungee/BungeeServerSyncPlugin.java | [
{
"identifier": "ServerSync",
"path": "serversync-common/src/main/java/me/akraml/serversync/ServerSync.java",
"snippet": "@Getter\npublic class ServerSync {\n\n private static ServerSync INSTANCE;\n\n private final ServersManager serversManager;\n private final MessageBrokerService messageBroke... | import me.akraml.serversync.connection.auth.ConnectionCredentials;
import me.akraml.serversync.connection.auth.credentials.RedisCredentialsKeys;
import me.akraml.serversync.server.ServersManager;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.config.Configuration;
import net.md_5.bungee.config.ConfigurationProvider;
import net.md_5.bungee.config.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import lombok.Getter;
import me.akraml.serversync.ServerSync;
import me.akraml.serversync.VersionInfo;
import me.akraml.serversync.broker.RedisMessageBrokerService;
import me.akraml.serversync.connection.ConnectionResult;
import me.akraml.serversync.connection.ConnectionType; | 3,787 | /*
* MIT License
*
* Copyright (c) 2023 Akram Louze
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.akraml.serversync.bungee;
/**
* An implementation for ServerSync in BungeeCord platform.
*/
@Getter
public final class BungeeServerSyncPlugin extends Plugin {
private Configuration config;
@SuppressWarnings("ResultOfMethodCallIgnored")
@Override
public void onLoad() {
if (!getDataFolder().exists()) {
getDataFolder().mkdir();
}
try {
loadConfig();
} catch (Exception exception) {
exception.printStackTrace(System.err);
}
}
@Override
public void onEnable() {
final long start = System.currentTimeMillis();
getLogger().info("\n" +
" __ __ \n" +
"/ _\\ ___ _ ____ _____ _ __/ _\\_ _ _ __ ___ \n" +
"\\ \\ / _ \\ '__\\ \\ / / _ \\ '__\\ \\| | | | '_ \\ / __|\n" +
"_\\ \\ __/ | \\ V / __/ | _\\ \\ |_| | | | | (__ \n" +
"\\__/\\___|_| \\_/ \\___|_| \\__/\\__, |_| |_|\\___|\n" +
" |___/ \n");
getLogger().info("This server is running ServerSync " + VersionInfo.VERSION + " by AkramL.");
final ServersManager serversManager = new BungeeServersManager(this);
// Initialize message broker service.
final ConnectionType connectionType = ConnectionType.valueOf(config.getString("message-broker-service"));
switch (connectionType) {
case REDIS: {
getLogger().info("ServerSync will run under Redis message broker...");
long redisStartTime = System.currentTimeMillis();
final Configuration redisSection = config.getSection("redis");
final ConnectionCredentials credentials = ConnectionCredentials.newBuilder()
.addKey(RedisCredentialsKeys.HOST, redisSection.getString("host"))
.addKey(RedisCredentialsKeys.PORT, redisSection.getInt("port"))
.addKey(RedisCredentialsKeys.PASSWORD, redisSection.getString("password"))
.addKey(RedisCredentialsKeys.TIMEOUT, redisSection.getInt("timeout"))
.addKey(RedisCredentialsKeys.MAX_TOTAL, redisSection.getInt("max-total"))
.addKey(RedisCredentialsKeys.MAX_IDLE, redisSection.getInt("max-idle"))
.addKey(RedisCredentialsKeys.MIN_IDLE, redisSection.getInt("min-idle"))
.addKey(RedisCredentialsKeys.MIN_EVICTABLE_IDLE_TIME, redisSection.getLong("min-evictable-idle-time"))
.addKey(RedisCredentialsKeys.TIME_BETWEEN_EVICTION_RUNS, redisSection.getLong("time-between-eviction-runs"))
.addKey(RedisCredentialsKeys.BLOCK_WHEN_EXHAUSTED, redisSection.getBoolean("block-when-exhausted"))
.build();
final RedisMessageBrokerService messageBrokerService = new RedisMessageBrokerService(
serversManager,
credentials
);
final ConnectionResult connectionResult = messageBrokerService.connect();
if (connectionResult == ConnectionResult.FAILURE) {
getLogger().severe("Failed to connect into redis, please check credentials!");
return;
}
getLogger().info("Successfully connected to redis, process took " + (System.currentTimeMillis() - redisStartTime) + "ms!");
messageBrokerService.startHandler(); | /*
* MIT License
*
* Copyright (c) 2023 Akram Louze
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.akraml.serversync.bungee;
/**
* An implementation for ServerSync in BungeeCord platform.
*/
@Getter
public final class BungeeServerSyncPlugin extends Plugin {
private Configuration config;
@SuppressWarnings("ResultOfMethodCallIgnored")
@Override
public void onLoad() {
if (!getDataFolder().exists()) {
getDataFolder().mkdir();
}
try {
loadConfig();
} catch (Exception exception) {
exception.printStackTrace(System.err);
}
}
@Override
public void onEnable() {
final long start = System.currentTimeMillis();
getLogger().info("\n" +
" __ __ \n" +
"/ _\\ ___ _ ____ _____ _ __/ _\\_ _ _ __ ___ \n" +
"\\ \\ / _ \\ '__\\ \\ / / _ \\ '__\\ \\| | | | '_ \\ / __|\n" +
"_\\ \\ __/ | \\ V / __/ | _\\ \\ |_| | | | | (__ \n" +
"\\__/\\___|_| \\_/ \\___|_| \\__/\\__, |_| |_|\\___|\n" +
" |___/ \n");
getLogger().info("This server is running ServerSync " + VersionInfo.VERSION + " by AkramL.");
final ServersManager serversManager = new BungeeServersManager(this);
// Initialize message broker service.
final ConnectionType connectionType = ConnectionType.valueOf(config.getString("message-broker-service"));
switch (connectionType) {
case REDIS: {
getLogger().info("ServerSync will run under Redis message broker...");
long redisStartTime = System.currentTimeMillis();
final Configuration redisSection = config.getSection("redis");
final ConnectionCredentials credentials = ConnectionCredentials.newBuilder()
.addKey(RedisCredentialsKeys.HOST, redisSection.getString("host"))
.addKey(RedisCredentialsKeys.PORT, redisSection.getInt("port"))
.addKey(RedisCredentialsKeys.PASSWORD, redisSection.getString("password"))
.addKey(RedisCredentialsKeys.TIMEOUT, redisSection.getInt("timeout"))
.addKey(RedisCredentialsKeys.MAX_TOTAL, redisSection.getInt("max-total"))
.addKey(RedisCredentialsKeys.MAX_IDLE, redisSection.getInt("max-idle"))
.addKey(RedisCredentialsKeys.MIN_IDLE, redisSection.getInt("min-idle"))
.addKey(RedisCredentialsKeys.MIN_EVICTABLE_IDLE_TIME, redisSection.getLong("min-evictable-idle-time"))
.addKey(RedisCredentialsKeys.TIME_BETWEEN_EVICTION_RUNS, redisSection.getLong("time-between-eviction-runs"))
.addKey(RedisCredentialsKeys.BLOCK_WHEN_EXHAUSTED, redisSection.getBoolean("block-when-exhausted"))
.build();
final RedisMessageBrokerService messageBrokerService = new RedisMessageBrokerService(
serversManager,
credentials
);
final ConnectionResult connectionResult = messageBrokerService.connect();
if (connectionResult == ConnectionResult.FAILURE) {
getLogger().severe("Failed to connect into redis, please check credentials!");
return;
}
getLogger().info("Successfully connected to redis, process took " + (System.currentTimeMillis() - redisStartTime) + "ms!");
messageBrokerService.startHandler(); | ServerSync.initializeInstance(serversManager, messageBrokerService); | 0 | 2023-10-21 12:47:58+00:00 | 8k |
neftalito/R-Info-Plus | arbol/Cuerpo.java | [
{
"identifier": "Robot",
"path": "form/Robot.java",
"snippet": "public class Robot {\n private int ciclos;\n private ArrayList<Coord> misCalles;\n private DeclaracionProcesos procAST;\n private Cuerpo cueAST;\n private DeclaracionVariable varAST;\n private ImageIcon robotImage;\n pr... | import form.Robot;
import arbol.sentencia.Sentencia;
import java.util.ArrayList; | 6,508 |
package arbol;
public class Cuerpo extends AST {
private ArrayList<Sentencia> S;
DeclaracionVariable varAST; |
package arbol;
public class Cuerpo extends AST {
private ArrayList<Sentencia> S;
DeclaracionVariable varAST; | Robot rob; | 0 | 2023-10-20 15:45:37+00:00 | 8k |
wevez/ClientCoderPack | src/tech/tenamen/Main.java | [
{
"identifier": "Client",
"path": "src/tech/tenamen/client/Client.java",
"snippet": "public class Client implements Downloadable {\n\n private String VERSION_NAME;\n private File JSON_FILE, JAR_FILE;\n\n private final List<Library> LIBRARIES = new ArrayList<>();\n public Asset asset;\n\n ... | import tech.tenamen.client.Client;
import tech.tenamen.ide.IDE;
import tech.tenamen.ide.InteliJIDE;
import tech.tenamen.property.OS;
import java.io.File;
import java.util.Scanner; | 4,323 | package tech.tenamen;
public class Main {
public static IDE IDE = new InteliJIDE(); | package tech.tenamen;
public class Main {
public static IDE IDE = new InteliJIDE(); | public static Client client; | 0 | 2023-10-20 06:56:19+00:00 | 8k |
Invadermonky/Omniwand | src/main/java/com/invadermonky/omniwand/network/MessageRevertWand.java | [
{
"identifier": "Omniwand",
"path": "src/main/java/com/invadermonky/omniwand/Omniwand.java",
"snippet": "@Mod(\n modid = Omniwand.MOD_ID,\n name = Omniwand.MOD_NAME,\n version = Omniwand.MOD_VERSION,\n acceptedMinecraftVersions = Omniwand.MC_VERSION,\n guiFactory = Omn... | import com.invadermonky.omniwand.Omniwand;
import com.invadermonky.omniwand.handlers.TransformHandler;
import com.invadermonky.omniwand.init.RegistryOW;
import com.invadermonky.omniwand.util.References;
import io.netty.buffer.ByteBuf;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumHand;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; | 4,104 | package com.invadermonky.omniwand.network;
public class MessageRevertWand implements IMessage {
public MessageRevertWand() {}
@Override
public void fromBytes(ByteBuf buf) {}
@Override
public void toBytes(ByteBuf buf) {}
public static class MsgHandler implements IMessageHandler<MessageRevertWand,IMessage> {
@Override
public IMessage onMessage(MessageRevertWand message, MessageContext ctx) {
EntityPlayer player = ctx.getServerHandler().player;
ItemStack stack = player.getHeldItemMainhand();
if(stack != null && TransformHandler.isOmniwand(stack) && stack.getItem() != RegistryOW.OMNIWAND) { | package com.invadermonky.omniwand.network;
public class MessageRevertWand implements IMessage {
public MessageRevertWand() {}
@Override
public void fromBytes(ByteBuf buf) {}
@Override
public void toBytes(ByteBuf buf) {}
public static class MsgHandler implements IMessageHandler<MessageRevertWand,IMessage> {
@Override
public IMessage onMessage(MessageRevertWand message, MessageContext ctx) {
EntityPlayer player = ctx.getServerHandler().player;
ItemStack stack = player.getHeldItemMainhand();
if(stack != null && TransformHandler.isOmniwand(stack) && stack.getItem() != RegistryOW.OMNIWAND) { | ItemStack newStack = TransformHandler.getTransformStackForMod(stack, References.MINECRAFT); | 3 | 2023-10-16 00:48:26+00:00 | 8k |
hmcts/opal-fines-service | src/test/java/uk/gov/hmcts/opal/controllers/DefendantAccountControllerTest.java | [
{
"identifier": "AccountDetailsDto",
"path": "src/main/java/uk/gov/hmcts/opal/dto/AccountDetailsDto.java",
"snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class AccountDetailsDto implements ToJsonString {\n\n //defendant_accounts.account_number\n private String account... | import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import uk.gov.hmcts.opal.dto.AccountDetailsDto;
import uk.gov.hmcts.opal.dto.AccountEnquiryDto;
import uk.gov.hmcts.opal.dto.AccountSearchDto;
import uk.gov.hmcts.opal.dto.AccountSearchResultsDto;
import uk.gov.hmcts.opal.entity.DefendantAccountEntity;
import uk.gov.hmcts.opal.service.DefendantAccountService;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | 4,646 | package uk.gov.hmcts.opal.controllers;
@ExtendWith(MockitoExtension.class)
class DefendantAccountControllerTest {
@Mock
private DefendantAccountService defendantAccountService;
@InjectMocks
private DefendantAccountController defendantAccountController;
@Test
public void testGetDefendantAccount_Success() {
// Arrange | package uk.gov.hmcts.opal.controllers;
@ExtendWith(MockitoExtension.class)
class DefendantAccountControllerTest {
@Mock
private DefendantAccountService defendantAccountService;
@InjectMocks
private DefendantAccountController defendantAccountController;
@Test
public void testGetDefendantAccount_Success() {
// Arrange | DefendantAccountEntity mockResponse = new DefendantAccountEntity(); | 4 | 2023-10-23 14:12:11+00:00 | 8k |
IronRiders/MockSeason23-24 | src/main/java/org/ironriders/robot/RobotContainer.java | [
{
"identifier": "DriveCommands",
"path": "src/main/java/org/ironriders/commands/DriveCommands.java",
"snippet": "public class DriveCommands {\n private final DriveSubsystem drive;\n private final SwerveDrive swerve;\n private final VisionSubsystem vision;\n\n public DriveCommands(DriveSubsys... | import com.pathplanner.lib.auto.AutoBuilder;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj2.command.Command;
import edu.wpi.first.wpilibj2.command.Commands;
import edu.wpi.first.wpilibj2.command.button.CommandJoystick;
import edu.wpi.first.wpilibj2.command.button.CommandXboxController;
import org.ironriders.commands.DriveCommands;
import org.ironriders.commands.RobotCommands;
import org.ironriders.constants.Ports;
import org.ironriders.constants.Teleop;
import org.ironriders.lib.Utils;
import org.ironriders.subsystems.ArmSubsystem;
import org.ironriders.subsystems.DriveSubsystem;
import org.ironriders.subsystems.ManipulatorSubsystem;
import static org.ironriders.constants.Auto.DEFAULT_AUTO;
import static org.ironriders.constants.Teleop.Controllers.Joystick;
import static org.ironriders.constants.Teleop.Speed.DEADBAND;
import static org.ironriders.constants.Teleop.Speed.MIN_MULTIPLIER; | 6,521 | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package org.ironriders.robot;
/**
* This class is where the bulk of the robot should be declared. Since Command-based is a
* "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot}
* periodic methods (other than the scheduler calls). Instead, the structure of the robot (including
* subsystems, commands, and trigger mappings) should be declared here.
*/
public class RobotContainer {
private final DriveSubsystem drive = new DriveSubsystem();
private final ManipulatorSubsystem manipulator = new ManipulatorSubsystem();
private final ArmSubsystem arm = new ArmSubsystem();
private final CommandXboxController primaryController =
new CommandXboxController(Ports.Controllers.PRIMARY_CONTROLLER);
private final CommandJoystick secondaryController =
new CommandJoystick(Ports.Controllers.SECONDARY_CONTROLLER);
private final RobotCommands commands = new RobotCommands(arm, drive, manipulator);
private final DriveCommands driveCommands = drive.getCommands();
private final SendableChooser<String> autoOptionSelector = new SendableChooser<>();
/**
* The container for the robot. Contains subsystems, IO devices, and commands.
*/
public RobotContainer() {
for (String auto : AutoBuilder.getAllAutoNames()) {
if (auto.equals("REGISTERED_COMMANDS")) continue;
autoOptionSelector.addOption(auto, auto);
}
autoOptionSelector.setDefaultOption(DEFAULT_AUTO, DEFAULT_AUTO);
SmartDashboard.putData("auto/Auto Option", autoOptionSelector);
configureBindings();
}
private void configureBindings() {
Command switchDropOff = commands.switchDropOff();
Command exchange = commands.exchange();
Command exchangeReturn = commands.exchangeReturn();
Command portal = commands.portal();
Command cancelAuto = Commands.runOnce(() -> {
switchDropOff.cancel();
exchange.cancel();
exchangeReturn.cancel();
portal.cancel();
});
// Primary Driver
drive.setDefaultCommand(
driveCommands.teleopCommand(
() -> -controlCurve(primaryController.getLeftY()),
() -> -controlCurve(primaryController.getLeftX()),
() -> -controlCurve(primaryController.getRightX())
)
);
primaryController.rightBumper().onTrue(cancelAuto);
primaryController.leftBumper().onTrue(cancelAuto);
primaryController.a().onTrue(commands.groundPickup());
primaryController.b().onTrue(switchDropOff);
primaryController.x().onTrue(portal);
primaryController.y().onTrue(exchange);
primaryController.leftStick().onTrue(commands.driving());
primaryController.rightStick().onTrue(commands.driving());
// Secondary Driver
secondaryController.button(6).onTrue(exchange);
secondaryController.button(7).onTrue(exchangeReturn);
secondaryController.button(8).onTrue(portal);
secondaryController.button(9).onTrue(switchDropOff);
secondaryController.button(10).onTrue(commands.groundPickup());
secondaryController.button(11).onTrue(commands.resting());
secondaryController.button(12).onTrue(commands.driving());
}
private double controlCurve(double input) {
// Multiplier based on trigger axis (whichever one is larger) then scaled to start at 0.35
return Utils.controlCurve(input, Joystick.EXPONENT, Joystick.DEADBAND) * (
Utils.controlCurve(
Math.max(primaryController.getLeftTriggerAxis(), primaryController.getRightTriggerAxis()), | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package org.ironriders.robot;
/**
* This class is where the bulk of the robot should be declared. Since Command-based is a
* "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot}
* periodic methods (other than the scheduler calls). Instead, the structure of the robot (including
* subsystems, commands, and trigger mappings) should be declared here.
*/
public class RobotContainer {
private final DriveSubsystem drive = new DriveSubsystem();
private final ManipulatorSubsystem manipulator = new ManipulatorSubsystem();
private final ArmSubsystem arm = new ArmSubsystem();
private final CommandXboxController primaryController =
new CommandXboxController(Ports.Controllers.PRIMARY_CONTROLLER);
private final CommandJoystick secondaryController =
new CommandJoystick(Ports.Controllers.SECONDARY_CONTROLLER);
private final RobotCommands commands = new RobotCommands(arm, drive, manipulator);
private final DriveCommands driveCommands = drive.getCommands();
private final SendableChooser<String> autoOptionSelector = new SendableChooser<>();
/**
* The container for the robot. Contains subsystems, IO devices, and commands.
*/
public RobotContainer() {
for (String auto : AutoBuilder.getAllAutoNames()) {
if (auto.equals("REGISTERED_COMMANDS")) continue;
autoOptionSelector.addOption(auto, auto);
}
autoOptionSelector.setDefaultOption(DEFAULT_AUTO, DEFAULT_AUTO);
SmartDashboard.putData("auto/Auto Option", autoOptionSelector);
configureBindings();
}
private void configureBindings() {
Command switchDropOff = commands.switchDropOff();
Command exchange = commands.exchange();
Command exchangeReturn = commands.exchangeReturn();
Command portal = commands.portal();
Command cancelAuto = Commands.runOnce(() -> {
switchDropOff.cancel();
exchange.cancel();
exchangeReturn.cancel();
portal.cancel();
});
// Primary Driver
drive.setDefaultCommand(
driveCommands.teleopCommand(
() -> -controlCurve(primaryController.getLeftY()),
() -> -controlCurve(primaryController.getLeftX()),
() -> -controlCurve(primaryController.getRightX())
)
);
primaryController.rightBumper().onTrue(cancelAuto);
primaryController.leftBumper().onTrue(cancelAuto);
primaryController.a().onTrue(commands.groundPickup());
primaryController.b().onTrue(switchDropOff);
primaryController.x().onTrue(portal);
primaryController.y().onTrue(exchange);
primaryController.leftStick().onTrue(commands.driving());
primaryController.rightStick().onTrue(commands.driving());
// Secondary Driver
secondaryController.button(6).onTrue(exchange);
secondaryController.button(7).onTrue(exchangeReturn);
secondaryController.button(8).onTrue(portal);
secondaryController.button(9).onTrue(switchDropOff);
secondaryController.button(10).onTrue(commands.groundPickup());
secondaryController.button(11).onTrue(commands.resting());
secondaryController.button(12).onTrue(commands.driving());
}
private double controlCurve(double input) {
// Multiplier based on trigger axis (whichever one is larger) then scaled to start at 0.35
return Utils.controlCurve(input, Joystick.EXPONENT, Joystick.DEADBAND) * (
Utils.controlCurve(
Math.max(primaryController.getLeftTriggerAxis(), primaryController.getRightTriggerAxis()), | Teleop.Speed.EXPONENT, | 3 | 2023-10-23 20:31:46+00:00 | 8k |
ChrisGenti/DiscordTickets | src/main/java/com/github/chrisgenti/discordtickets/listeners/modals/ModalListener.java | [
{
"identifier": "TicketManager",
"path": "src/main/java/com/github/chrisgenti/discordtickets/managers/TicketManager.java",
"snippet": "public class TicketManager {\n private int lastNumber;\n private final List<Ticket> ticketCache;\n\n public TicketManager(DiscordTickets discord) {\n thi... | import com.github.chrisgenti.discordtickets.managers.TicketManager;
import com.github.chrisgenti.discordtickets.objects.Ticket;
import com.github.chrisgenti.discordtickets.tools.enums.TicketType;
import com.github.chrisgenti.discordtickets.DiscordTickets;
import com.github.chrisgenti.discordtickets.managers.mongo.MongoManager;
import com.github.chrisgenti.discordtickets.tools.utils.messages.MessageUtil;
import org.javacord.api.entity.channel.ChannelCategory;
import org.javacord.api.entity.channel.TextChannel;
import org.javacord.api.entity.message.MessageBuilder;
import org.javacord.api.entity.message.MessageFlag;
import org.javacord.api.entity.message.embed.EmbedBuilder;
import org.javacord.api.entity.message.mention.AllowedMentionsBuilder;
import org.javacord.api.entity.permission.PermissionType;
import org.javacord.api.entity.permission.PermissionsBuilder;
import org.javacord.api.entity.permission.Role;
import org.javacord.api.entity.server.Server;
import org.javacord.api.entity.user.User;
import org.javacord.api.event.interaction.ModalSubmitEvent;
import org.javacord.api.listener.interaction.ModalSubmitListener;
import org.tinylog.Logger;
import java.awt.*;
import java.time.Instant;
import java.util.Date; | 4,723 | package com.github.chrisgenti.discordtickets.listeners.modals;
public class ModalListener implements ModalSubmitListener {
private final MongoManager mongoManager;
private final TicketManager ticketManager;
public ModalListener(DiscordTickets discord) {
this.mongoManager = discord.getMongoManager();
this.ticketManager = discord.getTicketManager();
}
@Override
public void onModalSubmit(ModalSubmitEvent event) {
User user = event.getModalInteraction().getUser(); String customID = event.getModalInteraction().getCustomId().replace("_modal", "");
TicketType ticketType = TicketType.getByCustomID(customID);
if (ticketType == null)
return;
if (event.getModalInteraction().getServer().isEmpty())
return;
Server server = event.getModalInteraction().getServer().get();
if (ticketManager.getTicketsByUser(user.getIdAsString()).size() == 2) {
event.getInteraction().createImmediateResponder()
.setFlags(MessageFlag.EPHEMERAL)
.addEmbed(
new EmbedBuilder()
.setAuthor("Discord Support Tickets", "", "https://i.imgur.com/s5k4che.png")
.setDescription("You have reached your ticket limit.")
.setColor(Color.RED)
).respond();
return;
}
if (server.getChannelCategoriesByName(ticketType.getCategory()).stream().findFirst().isEmpty())
return;
ChannelCategory category = server.getChannelCategoriesByName(ticketType.getCategory()).stream().findFirst().get();
Role role = null;
if (server.getRolesByName("SUPPORT").stream().findFirst().isPresent())
role = server.getRolesByName("SUPPORT").stream().findFirst().get();
String username = null;
if (event.getModalInteraction().getTextInputValueByCustomId("username").isPresent())
username = event.getModalInteraction().getTextInputValueByCustomId("username").get();
String description = null;
if (event.getModalInteraction().getTextInputValueByCustomId("description").isPresent())
description = event.getModalInteraction().getTextInputValueByCustomId("description").get();
String reportedUsername = null;
if ((ticketType == TicketType.PLAYER_REPORTS || ticketType == TicketType.STAFF_REPORTS) && event.getModalInteraction().getTextInputValueByCustomId("reported_username").isPresent())
reportedUsername = event.getModalInteraction().getTextInputValueByCustomId("reported_username").get();
int number = ticketManager.getLastNumber() + 1; MessageBuilder builder = reportedUsername == null ? this.createMessage(ticketType, role, username, description) : this.createMessage(ticketType, role, username, reportedUsername, description);
server.createTextChannelBuilder()
.setCategory(category)
.setName(
"ticket-{username}-{id}"
.replace("{username}", user.getName())
.replace("{id}", String.valueOf(number))
)
.addPermissionOverwrite(server.getEveryoneRole(), new PermissionsBuilder().setDenied(PermissionType.VIEW_CHANNEL).build())
.addPermissionOverwrite(event.getModalInteraction().getUser(), new PermissionsBuilder().setAllowed(PermissionType.VIEW_CHANNEL, PermissionType.SEND_MESSAGES).build())
.create().whenComplete((var, throwable) -> {
if (var.getCurrentCachedInstance().isEmpty())
return;
TextChannel channel = var.getCurrentCachedInstance().get();
builder.send(channel);
event.getInteraction().createImmediateResponder()
.setAllowedMentions(new AllowedMentionsBuilder().build())
.addEmbed(
new EmbedBuilder()
.setAuthor(ticketType.getLabel() + " Ticket", "", "https://i.imgur.com/s5k4che.png")
.setDescription("New ticket created: <#" + channel.getIdAsString() + ">")
.setColor(Color.GREEN)
).setFlags(MessageFlag.EPHEMERAL).respond();
Ticket ticket = new Ticket(number, ticketType, user.getIdAsString(), channel.getIdAsString(), Date.from(Instant.now()));
mongoManager.createTicket(ticket); ticketManager.getTicketCache().add(ticket); ticketManager.setLastNumber(number);
Logger.info( | package com.github.chrisgenti.discordtickets.listeners.modals;
public class ModalListener implements ModalSubmitListener {
private final MongoManager mongoManager;
private final TicketManager ticketManager;
public ModalListener(DiscordTickets discord) {
this.mongoManager = discord.getMongoManager();
this.ticketManager = discord.getTicketManager();
}
@Override
public void onModalSubmit(ModalSubmitEvent event) {
User user = event.getModalInteraction().getUser(); String customID = event.getModalInteraction().getCustomId().replace("_modal", "");
TicketType ticketType = TicketType.getByCustomID(customID);
if (ticketType == null)
return;
if (event.getModalInteraction().getServer().isEmpty())
return;
Server server = event.getModalInteraction().getServer().get();
if (ticketManager.getTicketsByUser(user.getIdAsString()).size() == 2) {
event.getInteraction().createImmediateResponder()
.setFlags(MessageFlag.EPHEMERAL)
.addEmbed(
new EmbedBuilder()
.setAuthor("Discord Support Tickets", "", "https://i.imgur.com/s5k4che.png")
.setDescription("You have reached your ticket limit.")
.setColor(Color.RED)
).respond();
return;
}
if (server.getChannelCategoriesByName(ticketType.getCategory()).stream().findFirst().isEmpty())
return;
ChannelCategory category = server.getChannelCategoriesByName(ticketType.getCategory()).stream().findFirst().get();
Role role = null;
if (server.getRolesByName("SUPPORT").stream().findFirst().isPresent())
role = server.getRolesByName("SUPPORT").stream().findFirst().get();
String username = null;
if (event.getModalInteraction().getTextInputValueByCustomId("username").isPresent())
username = event.getModalInteraction().getTextInputValueByCustomId("username").get();
String description = null;
if (event.getModalInteraction().getTextInputValueByCustomId("description").isPresent())
description = event.getModalInteraction().getTextInputValueByCustomId("description").get();
String reportedUsername = null;
if ((ticketType == TicketType.PLAYER_REPORTS || ticketType == TicketType.STAFF_REPORTS) && event.getModalInteraction().getTextInputValueByCustomId("reported_username").isPresent())
reportedUsername = event.getModalInteraction().getTextInputValueByCustomId("reported_username").get();
int number = ticketManager.getLastNumber() + 1; MessageBuilder builder = reportedUsername == null ? this.createMessage(ticketType, role, username, description) : this.createMessage(ticketType, role, username, reportedUsername, description);
server.createTextChannelBuilder()
.setCategory(category)
.setName(
"ticket-{username}-{id}"
.replace("{username}", user.getName())
.replace("{id}", String.valueOf(number))
)
.addPermissionOverwrite(server.getEveryoneRole(), new PermissionsBuilder().setDenied(PermissionType.VIEW_CHANNEL).build())
.addPermissionOverwrite(event.getModalInteraction().getUser(), new PermissionsBuilder().setAllowed(PermissionType.VIEW_CHANNEL, PermissionType.SEND_MESSAGES).build())
.create().whenComplete((var, throwable) -> {
if (var.getCurrentCachedInstance().isEmpty())
return;
TextChannel channel = var.getCurrentCachedInstance().get();
builder.send(channel);
event.getInteraction().createImmediateResponder()
.setAllowedMentions(new AllowedMentionsBuilder().build())
.addEmbed(
new EmbedBuilder()
.setAuthor(ticketType.getLabel() + " Ticket", "", "https://i.imgur.com/s5k4che.png")
.setDescription("New ticket created: <#" + channel.getIdAsString() + ">")
.setColor(Color.GREEN)
).setFlags(MessageFlag.EPHEMERAL).respond();
Ticket ticket = new Ticket(number, ticketType, user.getIdAsString(), channel.getIdAsString(), Date.from(Instant.now()));
mongoManager.createTicket(ticket); ticketManager.getTicketCache().add(ticket); ticketManager.setLastNumber(number);
Logger.info( | MessageUtil.TICKET_CREATE_MESSAGE | 5 | 2023-10-23 13:24:05+00:00 | 8k |
moonstoneid/aero-cast | apps/feed-aggregator/src/main/java/com/moonstoneid/aerocast/aggregator/eth/EthPublisherAdapter.java | [
{
"identifier": "BaseEthAdapter",
"path": "apps/feed-common/src/main/java/com/moonstoneid/aerocast/common/eth/BaseEthAdapter.java",
"snippet": "public abstract class BaseEthAdapter {\n\n private static final BigInteger GAS_LIMIT = BigInteger.valueOf(6721975L);\n private static final BigInteger GAS... | import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import com.moonstoneid.aerocast.common.eth.BaseEthAdapter;
import com.moonstoneid.aerocast.common.eth.EthUtil;
import com.moonstoneid.aerocast.common.eth.contracts.FeedPublisher;
import com.moonstoneid.aerocast.common.eth.contracts.FeedPublisher.NewPubItemEventResponse;
import com.moonstoneid.aerocast.common.eth.contracts.FeedPublisher.PubItem;
import io.reactivex.disposables.Disposable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.request.EthFilter; | 5,807 | package com.moonstoneid.aerocast.aggregator.eth;
@Component
@Slf4j | package com.moonstoneid.aerocast.aggregator.eth;
@Component
@Slf4j | public class EthPublisherAdapter extends BaseEthAdapter { | 0 | 2023-10-23 20:33:07+00:00 | 8k |
UnityFoundation-io/Libre311 | app/src/test/java/app/JurisdictionSupportRootControllerTest.java | [
{
"identifier": "ServiceDTO",
"path": "app/src/main/java/app/dto/service/ServiceDTO.java",
"snippet": "@Introspected\npublic class ServiceDTO {\n\n @JsonProperty(\"service_code\")\n private String serviceCode;\n\n @JsonProperty(\"jurisdiction_id\")\n private String jurisdictionId;\n\n @Js... | import app.dto.service.ServiceDTO;
import app.dto.servicerequest.PostRequestServiceRequestDTO;
import app.dto.servicerequest.PostResponseServiceRequestDTO;
import app.dto.servicerequest.ServiceRequestDTO;
import app.model.service.ServiceRepository;
import app.model.servicerequest.ServiceRequestRepository;
import app.util.DbCleanup;
import app.util.MockAuthenticationFetcher;
import app.util.MockReCaptchaService;
import app.util.MockSecurityService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvValidationException;
import io.micronaut.core.util.StringUtils;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.MediaType;
import io.micronaut.http.client.HttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.http.client.exceptions.HttpClientResponseException;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import static io.micronaut.http.HttpStatus.INTERNAL_SERVER_ERROR;
import static io.micronaut.http.HttpStatus.UNAUTHORIZED;
import static org.junit.jupiter.api.Assertions.*; | 6,715 | // Copyright 2023 Libre311 Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package app;
@MicronautTest(environments={"test-jurisdiction-support"})
public class JurisdictionSupportRootControllerTest {
@Inject
@Client("/api")
HttpClient client;
@Inject
MockReCaptchaService mockReCaptchaService;
@Inject | // Copyright 2023 Libre311 Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package app;
@MicronautTest(environments={"test-jurisdiction-support"})
public class JurisdictionSupportRootControllerTest {
@Inject
@Client("/api")
HttpClient client;
@Inject
MockReCaptchaService mockReCaptchaService;
@Inject | ServiceRepository serviceRepository; | 4 | 2023-10-18 15:37:36+00:00 | 8k |
JonnyOnlineYT/xenza | src/minecraft/com/mojang/authlib/yggdrasil/YggdrasilAuthenticationService.java | [
{
"identifier": "Agent",
"path": "src/minecraft/com/mojang/authlib/Agent.java",
"snippet": "public class Agent {\n public static final Agent MINECRAFT = new Agent(\"Minecraft\", 1);\n public static final Agent SCROLLS = new Agent(\"Scrolls\", 1);\n private final String name;\n private final int ... | import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.mojang.authlib.Agent;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.GameProfileRepository;
import com.mojang.authlib.HttpAuthenticationService;
import com.mojang.authlib.UserAuthentication;
import com.mojang.authlib.exceptions.AuthenticationException;
import com.mojang.authlib.exceptions.AuthenticationUnavailableException;
import com.mojang.authlib.exceptions.InvalidCredentialsException;
import com.mojang.authlib.exceptions.UserMigratedException;
import com.mojang.authlib.minecraft.MinecraftSessionService;
import com.mojang.authlib.properties.PropertyMap;
import com.mojang.authlib.yggdrasil.response.ProfileSearchResultsResponse;
import com.mojang.authlib.yggdrasil.response.Response;
import com.mojang.util.UUIDTypeAdapter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.net.Proxy;
import java.net.URL;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils; | 4,323 | package com.mojang.authlib.yggdrasil;
public class YggdrasilAuthenticationService extends HttpAuthenticationService {
private final String clientToken;
private final Gson gson;
public YggdrasilAuthenticationService(Proxy proxy, String clientToken) {
super(proxy);
this.clientToken = clientToken;
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(GameProfile.class, new YggdrasilAuthenticationService.GameProfileSerializer());
builder.registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer());
builder.registerTypeAdapter(UUID.class, new UUIDTypeAdapter());
builder.registerTypeAdapter(ProfileSearchResultsResponse.class, new ProfileSearchResultsResponse.Serializer());
this.gson = builder.create();
}
@Override
public UserAuthentication createUserAuthentication(Agent agent) {
return new YggdrasilUserAuthentication(this, agent);
}
@Override
public MinecraftSessionService createMinecraftSessionService() {
return new YggdrasilMinecraftSessionService(this);
}
@Override | package com.mojang.authlib.yggdrasil;
public class YggdrasilAuthenticationService extends HttpAuthenticationService {
private final String clientToken;
private final Gson gson;
public YggdrasilAuthenticationService(Proxy proxy, String clientToken) {
super(proxy);
this.clientToken = clientToken;
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(GameProfile.class, new YggdrasilAuthenticationService.GameProfileSerializer());
builder.registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer());
builder.registerTypeAdapter(UUID.class, new UUIDTypeAdapter());
builder.registerTypeAdapter(ProfileSearchResultsResponse.class, new ProfileSearchResultsResponse.Serializer());
this.gson = builder.create();
}
@Override
public UserAuthentication createUserAuthentication(Agent agent) {
return new YggdrasilUserAuthentication(this, agent);
}
@Override
public MinecraftSessionService createMinecraftSessionService() {
return new YggdrasilMinecraftSessionService(this);
}
@Override | public GameProfileRepository createProfileRepository() { | 2 | 2023-10-15 00:21:15+00:00 | 8k |
Radekyspec/TasksMaster | src/main/java/app/schedule/add_new_event/AddNewEventUseCaseFactory.java | [
{
"identifier": "ScheduleDataAccessInterface",
"path": "src/main/java/data_access/schedule/ScheduleDataAccessInterface.java",
"snippet": "public interface ScheduleDataAccessInterface {\n List<Event> getEvents(long projectId, long scheduleid);\n\n Event addEvents(long projectId, long scheduleId, St... | import data_access.schedule.ScheduleDataAccessInterface;
import interface_adapter.ViewManagerModel;
import interface_adapter.schedule.ScheduleViewModel;
import interface_adapter.schedule.event.AddEventController;
import interface_adapter.schedule.event.AddEventPresenter;
import interface_adapter.schedule.event.AddEventViewModel;
import use_case.schedule.add_new_event.AddNewEventInputBoundary;
import use_case.schedule.add_new_event.AddNewEventInteractor;
import use_case.schedule.add_new_event.AddNewEventOutputBoundary;
import view.schedule.AddNewEventView; | 4,024 | package app.schedule.add_new_event;
public class AddNewEventUseCaseFactory {
private AddNewEventUseCaseFactory() {
}
public static AddNewEventView create(ViewManagerModel viewManagerModel, AddEventViewModel addEventViewModel, ScheduleViewModel scheduleViewModel, ScheduleDataAccessInterface scheduleDataAccessInterface) {
return new AddNewEventView(viewManagerModel, addEventViewModel, scheduleViewModel, AddNewEventUseCaseFactory.createContorller(viewManagerModel, scheduleViewModel, scheduleDataAccessInterface));
}
| package app.schedule.add_new_event;
public class AddNewEventUseCaseFactory {
private AddNewEventUseCaseFactory() {
}
public static AddNewEventView create(ViewManagerModel viewManagerModel, AddEventViewModel addEventViewModel, ScheduleViewModel scheduleViewModel, ScheduleDataAccessInterface scheduleDataAccessInterface) {
return new AddNewEventView(viewManagerModel, addEventViewModel, scheduleViewModel, AddNewEventUseCaseFactory.createContorller(viewManagerModel, scheduleViewModel, scheduleDataAccessInterface));
}
| public static AddEventController createContorller(ViewManagerModel viewManagerModel, ScheduleViewModel scheduleViewModel, ScheduleDataAccessInterface scheduleDataAccessInterface) { | 3 | 2023-10-23 15:17:21+00:00 | 8k |
denis-vp/toy-language-interpreter | src/main/java/view/cli/CliInterpreter.java | [
{
"identifier": "Controller",
"path": "src/main/java/controller/Controller.java",
"snippet": "public class Controller {\n private final IRepository repository;\n private Boolean logOutput;\n private final ExecutorService executor = Executors.newFixedThreadPool(8);\n\n public Controller(IRepo... | import adt.*;
import controller.Controller;
import programgenerator.ProgramGenerator;
import model.ProgramState;
import model.statement.Statement;
import repository.IRepository;
import repository.Repository;
import view.cli.commands.ExitCommand;
import view.cli.commands.RunExampleCommand;
import java.util.List;
import java.util.Objects;
import java.util.Scanner; | 5,097 | package view.cli;
public class CliInterpreter {
public static void main(String[] args) {
TextMenu menu = new TextMenu();
CliInterpreter.addCommands(CliInterpreter.getLogFile(), menu);
menu.show();
}
private static String getLogFile() {
String logFilePath = "./logs/";
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter the log file name: ");
String input = scanner.nextLine();
if (Objects.equals(input, "")) {
logFilePath += "log.txt";
} else {
logFilePath += input;
}
return logFilePath;
}
private static void addCommands(String logFilePath, TextMenu menu) { | package view.cli;
public class CliInterpreter {
public static void main(String[] args) {
TextMenu menu = new TextMenu();
CliInterpreter.addCommands(CliInterpreter.getLogFile(), menu);
menu.show();
}
private static String getLogFile() {
String logFilePath = "./logs/";
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter the log file name: ");
String input = scanner.nextLine();
if (Objects.equals(input, "")) {
logFilePath += "log.txt";
} else {
logFilePath += input;
}
return logFilePath;
}
private static void addCommands(String logFilePath, TextMenu menu) { | List<Statement> programs = ProgramGenerator.getPrograms(); | 1 | 2023-10-21 18:08:59+00:00 | 8k |
NewStudyGround/NewStudyGround | server/src/main/java/com/codestates/server/domain/member/controller/MemberController.java | [
{
"identifier": "MemberPatchDto",
"path": "server/src/main/java/com/codestates/server/domain/member/dto/MemberPatchDto.java",
"snippet": "@Getter\n@Setter\n@AllArgsConstructor\npublic class MemberPatchDto {\n\n private Long memberId;\n\n private String name;\n\n @Pattern(regexp = \"^(?=.*[A-Za-... | import com.codestates.server.domain.member.dto.MemberPatchDto;
import com.codestates.server.domain.member.dto.MemberPostDto;
import com.codestates.server.domain.member.dto.MemberResponseDto;
import com.codestates.server.domain.member.entity.Member;
import com.codestates.server.domain.member.mapper.MemberMapper;
import com.codestates.server.global.dto.MultiResponseDto;
import com.codestates.server.domain.member.service.MemberService;
import com.codestates.server.global.uri.UriCreator;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.Valid;
import javax.validation.constraints.Positive;
import java.io.IOException;
import java.net.URI;
import java.util.List; | 3,685 | package com.codestates.server.domain.member.controller;
@AllArgsConstructor
@RestController
@RequestMapping("/members")
@Validated
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class MemberController {
private final MemberMapper mapper; | package com.codestates.server.domain.member.controller;
@AllArgsConstructor
@RestController
@RequestMapping("/members")
@Validated
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class MemberController {
private final MemberMapper mapper; | private final MemberService memberService; | 6 | 2023-10-23 09:41:00+00:00 | 8k |
LeGhast/Miniaturise | src/main/java/de/leghast/miniaturise/listener/PlayerInteractListener.java | [
{
"identifier": "Miniaturise",
"path": "src/main/java/de/leghast/miniaturise/Miniaturise.java",
"snippet": "public final class Miniaturise extends JavaPlugin {\n\n private MiniatureManager miniatureManager;\n private RegionManager regionManager;\n private SettingsManager settingsManager;\n\n ... | import de.leghast.miniaturise.Miniaturise;
import de.leghast.miniaturise.instance.miniature.PlacedMiniature;
import de.leghast.miniaturise.instance.region.SelectedLocations;
import de.leghast.miniaturise.instance.settings.AdjusterSettings;
import de.leghast.miniaturise.manager.ConfigManager;
import de.leghast.miniaturise.ui.UserInterface;
import de.leghast.miniaturise.util.Util;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.EquipmentSlot; | 4,133 | package de.leghast.miniaturise.listener;
/**
* This class listens for player interactions, that are relevant for the Miniaturise plugin
* @author GhastCraftHD
* */
public class PlayerInteractListener implements Listener {
private Miniaturise main;
public PlayerInteractListener(Miniaturise main){
this.main = main;
}
@EventHandler
public void onPlayerInteract(PlayerInteractEvent e){
Player player = e.getPlayer();
Material material = player.getInventory().getItemInMainHand().getType();
if(player.hasPermission("miniaturise.use")){
if(material == ConfigManager.getSelectorToolMaterial()){
e.setCancelled(true);
handleSelectorInteraction(player, e.getAction(), e.getClickedBlock(), e.getHand());
}else if(material == ConfigManager.getAdjusterToolMaterial()){
e.setCancelled(true);
if(main.getMiniatureManager().hasPlacedMiniature(player.getUniqueId())){
handleAdjusterInteraction(player, e.getAction(), e.getHand());
}else{ | package de.leghast.miniaturise.listener;
/**
* This class listens for player interactions, that are relevant for the Miniaturise plugin
* @author GhastCraftHD
* */
public class PlayerInteractListener implements Listener {
private Miniaturise main;
public PlayerInteractListener(Miniaturise main){
this.main = main;
}
@EventHandler
public void onPlayerInteract(PlayerInteractEvent e){
Player player = e.getPlayer();
Material material = player.getInventory().getItemInMainHand().getType();
if(player.hasPermission("miniaturise.use")){
if(material == ConfigManager.getSelectorToolMaterial()){
e.setCancelled(true);
handleSelectorInteraction(player, e.getAction(), e.getClickedBlock(), e.getHand());
}else if(material == ConfigManager.getAdjusterToolMaterial()){
e.setCancelled(true);
if(main.getMiniatureManager().hasPlacedMiniature(player.getUniqueId())){
handleAdjusterInteraction(player, e.getAction(), e.getHand());
}else{ | player.sendMessage(Util.PREFIX + "§cYou have not selected a placed miniature"); | 6 | 2023-10-15 09:08:33+00:00 | 8k |
zendo-games/zenlib | src/main/java/zendo/games/zenlib/screens/transitions/Transition.java | [
{
"identifier": "ZenConfig",
"path": "src/main/java/zendo/games/zenlib/ZenConfig.java",
"snippet": "public class ZenConfig {\n\n public final Window window;\n public final UI ui;\n\n public ZenConfig() {\n this(\"zenlib\", 1280, 720, null);\n }\n\n public ZenConfig(String title, in... | import aurelienribon.tweenengine.Timeline;
import aurelienribon.tweenengine.Tween;
import aurelienribon.tweenengine.primitives.MutableFloat;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.*;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.FrameBuffer;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.utils.Disposable;
import zendo.games.zenlib.ZenConfig;
import zendo.games.zenlib.ZenMain;
import zendo.games.zenlib.assets.ZenTransition;
import zendo.games.zenlib.screens.ZenScreen;
import zendo.games.zenlib.utils.Time; | 4,220 | package zendo.games.zenlib.screens.transitions;
public class Transition implements Disposable {
public static final float DEFAULT_SPEED = 0.66f;
public boolean active;
public MutableFloat percent;
public ShaderProgram shader;
public final Screens screens = new Screens();
public final FrameBuffers fbo = new FrameBuffers();
public final Textures tex = new Textures();
private final ZenConfig config;
public Transition(ZenConfig config) {
this.config = config;
this.active = false;
this.percent = new MutableFloat(0);
this.fbo.from = new FrameBuffer(Pixmap.Format.RGBA8888, config.window.width, config.window.height, false);
this.fbo.to = new FrameBuffer(Pixmap.Format.RGBA8888, config.window.width, config.window.height, false);
this.tex.from = this.fbo.from.getColorBufferTexture();
this.tex.to = this.fbo.to.getColorBufferTexture();
}
@Override
public void dispose() {
screens.dispose();
fbo.dispose();
// no need to dispose textures here,
// they are owned by the frame buffers
}
public void alwaysUpdate(float dt) {
screens.current.alwaysUpdate(dt);
if (screens.next != null) {
screens.next.alwaysUpdate(dt);
}
}
public void update(float dt) {
screens.current.update(dt);
if (screens.next != null) {
screens.next.update(dt);
}
}
public void render(SpriteBatch batch, OrthographicCamera windowCamera) {
screens.next.update(Time.delta);
screens.next.renderFrameBuffers(batch);
// draw the next screen to the 'to' buffer
fbo.to.begin();
{
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
screens.next.render(batch);
}
fbo.to.end();
// draw the current screen to the 'from' buffer
fbo.from.begin();
{
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
screens.current.render(batch);
}
fbo.from.end();
// draw the transition buffer to the screen
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.setShader(shader);
batch.setProjectionMatrix(windowCamera.combined);
batch.begin();
{
tex.from.bind(1);
shader.setUniformi("u_texture1", 1);
tex.to.bind(0);
shader.setUniformi("u_texture", 0);
shader.setUniformf("u_percent", percent.floatValue());
batch.setColor(Color.WHITE);
batch.draw(tex.to, 0, 0, config.window.width, config.window.height);
}
batch.end();
batch.setShader(null);
}
public void startTransition(final ZenScreen newScreen, ZenTransition type, float transitionSpeed) {
// current screen is active, so trigger transition to new screen
active = true;
percent.setValue(0);
shader = (type != null) ? type.shader : ZenTransition.random();
Timeline.createSequence()
.pushPause(.1f)
.push(Tween.call((i, baseTween) -> screens.next = newScreen))
.push(Tween.to(percent, 0, transitionSpeed).target(1))
.push(Tween.call((i, baseTween) -> {
screens.current = screens.next;
screens.next = null;
active = false;
})) | package zendo.games.zenlib.screens.transitions;
public class Transition implements Disposable {
public static final float DEFAULT_SPEED = 0.66f;
public boolean active;
public MutableFloat percent;
public ShaderProgram shader;
public final Screens screens = new Screens();
public final FrameBuffers fbo = new FrameBuffers();
public final Textures tex = new Textures();
private final ZenConfig config;
public Transition(ZenConfig config) {
this.config = config;
this.active = false;
this.percent = new MutableFloat(0);
this.fbo.from = new FrameBuffer(Pixmap.Format.RGBA8888, config.window.width, config.window.height, false);
this.fbo.to = new FrameBuffer(Pixmap.Format.RGBA8888, config.window.width, config.window.height, false);
this.tex.from = this.fbo.from.getColorBufferTexture();
this.tex.to = this.fbo.to.getColorBufferTexture();
}
@Override
public void dispose() {
screens.dispose();
fbo.dispose();
// no need to dispose textures here,
// they are owned by the frame buffers
}
public void alwaysUpdate(float dt) {
screens.current.alwaysUpdate(dt);
if (screens.next != null) {
screens.next.alwaysUpdate(dt);
}
}
public void update(float dt) {
screens.current.update(dt);
if (screens.next != null) {
screens.next.update(dt);
}
}
public void render(SpriteBatch batch, OrthographicCamera windowCamera) {
screens.next.update(Time.delta);
screens.next.renderFrameBuffers(batch);
// draw the next screen to the 'to' buffer
fbo.to.begin();
{
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
screens.next.render(batch);
}
fbo.to.end();
// draw the current screen to the 'from' buffer
fbo.from.begin();
{
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
screens.current.render(batch);
}
fbo.from.end();
// draw the transition buffer to the screen
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.setShader(shader);
batch.setProjectionMatrix(windowCamera.combined);
batch.begin();
{
tex.from.bind(1);
shader.setUniformi("u_texture1", 1);
tex.to.bind(0);
shader.setUniformi("u_texture", 0);
shader.setUniformf("u_percent", percent.floatValue());
batch.setColor(Color.WHITE);
batch.draw(tex.to, 0, 0, config.window.width, config.window.height);
}
batch.end();
batch.setShader(null);
}
public void startTransition(final ZenScreen newScreen, ZenTransition type, float transitionSpeed) {
// current screen is active, so trigger transition to new screen
active = true;
percent.setValue(0);
shader = (type != null) ? type.shader : ZenTransition.random();
Timeline.createSequence()
.pushPause(.1f)
.push(Tween.call((i, baseTween) -> screens.next = newScreen))
.push(Tween.to(percent, 0, transitionSpeed).target(1))
.push(Tween.call((i, baseTween) -> {
screens.current = screens.next;
screens.next = null;
active = false;
})) | .start(ZenMain.instance.tween); | 1 | 2023-10-21 19:36:50+00:00 | 8k |
tuna-pizza/GraphXings | src/GraphXings/Legacy/Game/Game.java | [
{
"identifier": "CrossingCalculator",
"path": "src/GraphXings/Algorithms/CrossingCalculator.java",
"snippet": "public class CrossingCalculator\r\n{\r\n /**\r\n * The graph g.\r\n */\r\n private Graph g;\r\n /**\r\n * The positions of the already placed vertices.\r\n */\r\n pr... | import GraphXings.Algorithms.CrossingCalculator;
import GraphXings.Game.GameMove;
import GraphXings.Game.GameState;
import GraphXings.Legacy.Algorithms.Player;
import GraphXings.Data.Graph;
import java.util.*; | 4,762 | package GraphXings.Legacy.Game;
/**
* A class for managing a game of GraphXings!
*/
public class Game
{
/**
* Decides whether or not data is copied before being passed on to players.
*/
public static boolean safeMode = true;
/**
* The width of the game board.
*/
private int width;
/**
* The height of the game board.
*/
private int height;
/**
* The graph to be drawn.
*/
private Graph g;
/**
* The first player.
*/
private Player player1;
/**
* The second player.
*/
private Player player2;
/**
* The time limit for players.
*/
private long timeLimit;
/**
* Instantiates a game of GraphXings.
* @param g The graph to be drawn.
* @param width The width of the game board.
* @param height The height of the game board.
* @param player1 The first player. Plays as the maximizer in round one.
* @param player2 The second player. Plays as the minimizer in round one.
*/
public Game(Graph g, int width, int height, Player player1, Player player2)
{
this.g = g;
this.width = width;
this.height = height;
this.player1 = player1;
this.player2 = player2;
this.timeLimit = Long.MAX_VALUE;
}
/**
* Instantiates a game of GraphXings.
* @param g The graph to be drawn.
* @param width The width of the game board.
* @param height The height of the game board.
* @param player1 The first player. Plays as the maximizer in round one.
* @param player2 The second player. Plays as the minimizer in round one.
* @param timeLimit The time limit for players.
*/
public Game(Graph g, int width, int height, Player player1, Player player2, long timeLimit)
{
this.g = g;
this.width = width;
this.height = height;
this.player1 = player1;
this.player2 = player2;
this.timeLimit = timeLimit;
}
/**
* Runs the full game of GraphXings.
* @return Provides a GameResult Object containing the game's results.
*/
public GameResult play()
{
Random r = new Random(System.nanoTime());
if (r.nextBoolean())
{
Player swap = player1;
player1 = player2;
player2 = swap;
}
try
{
player1.initializeNextRound(g.copy(),width,height, Player.Role.MAX);
player2.initializeNextRound(g.copy(),width,height, Player.Role.MIN);
int crossingsGame1 = playRound(player1, player2);
player1.initializeNextRound(g.copy(),width,height, Player.Role.MIN);
player2.initializeNextRound(g.copy(),width,height, Player.Role.MAX);
int crossingsGame2 = playRound(player2, player1);
return new GameResult(crossingsGame1,crossingsGame2,player1,player2,false,false,false,false);
}
catch (InvalidMoveException ex)
{
System.err.println(ex.getCheater().getName() + " cheated!");
if (ex.getCheater().equals(player1))
{
return new GameResult(0, 0, player1, player2,true,false,false,false);
}
else if (ex.getCheater().equals(player2))
{
return new GameResult(0,0,player1,player2,false,true,false,false);
}
else
{
return new GameResult(0,0,player1,player2,false,false,false,false);
}
}
catch (TimeOutException ex)
{
System.err.println(ex.getTimeOutPlayer().getName() + " ran out of time!");
if (ex.getTimeOutPlayer().equals(player1))
{
return new GameResult(0, 0, player1, player2,false,false,true,false);
}
else if (ex.getTimeOutPlayer().equals(player2))
{
return new GameResult(0,0,player1,player2,false,false,false,true);
}
else
{
return new GameResult(0,0,player1,player2,false,false,false,false);
}
}
}
/**
* Plays a single round of the game.
* @param maximizer The player with the goal to maximize the number of crossings.
* @param minimizer The player with the goal to minimize the number of crossings
* @return The number of crossings yielded in the final drawing.
* @throws InvalidMoveException An exception caused by cheating.
*/
private int playRound(Player maximizer, Player minimizer) throws InvalidMoveException, TimeOutException
{
int turn = 0; | package GraphXings.Legacy.Game;
/**
* A class for managing a game of GraphXings!
*/
public class Game
{
/**
* Decides whether or not data is copied before being passed on to players.
*/
public static boolean safeMode = true;
/**
* The width of the game board.
*/
private int width;
/**
* The height of the game board.
*/
private int height;
/**
* The graph to be drawn.
*/
private Graph g;
/**
* The first player.
*/
private Player player1;
/**
* The second player.
*/
private Player player2;
/**
* The time limit for players.
*/
private long timeLimit;
/**
* Instantiates a game of GraphXings.
* @param g The graph to be drawn.
* @param width The width of the game board.
* @param height The height of the game board.
* @param player1 The first player. Plays as the maximizer in round one.
* @param player2 The second player. Plays as the minimizer in round one.
*/
public Game(Graph g, int width, int height, Player player1, Player player2)
{
this.g = g;
this.width = width;
this.height = height;
this.player1 = player1;
this.player2 = player2;
this.timeLimit = Long.MAX_VALUE;
}
/**
* Instantiates a game of GraphXings.
* @param g The graph to be drawn.
* @param width The width of the game board.
* @param height The height of the game board.
* @param player1 The first player. Plays as the maximizer in round one.
* @param player2 The second player. Plays as the minimizer in round one.
* @param timeLimit The time limit for players.
*/
public Game(Graph g, int width, int height, Player player1, Player player2, long timeLimit)
{
this.g = g;
this.width = width;
this.height = height;
this.player1 = player1;
this.player2 = player2;
this.timeLimit = timeLimit;
}
/**
* Runs the full game of GraphXings.
* @return Provides a GameResult Object containing the game's results.
*/
public GameResult play()
{
Random r = new Random(System.nanoTime());
if (r.nextBoolean())
{
Player swap = player1;
player1 = player2;
player2 = swap;
}
try
{
player1.initializeNextRound(g.copy(),width,height, Player.Role.MAX);
player2.initializeNextRound(g.copy(),width,height, Player.Role.MIN);
int crossingsGame1 = playRound(player1, player2);
player1.initializeNextRound(g.copy(),width,height, Player.Role.MIN);
player2.initializeNextRound(g.copy(),width,height, Player.Role.MAX);
int crossingsGame2 = playRound(player2, player1);
return new GameResult(crossingsGame1,crossingsGame2,player1,player2,false,false,false,false);
}
catch (InvalidMoveException ex)
{
System.err.println(ex.getCheater().getName() + " cheated!");
if (ex.getCheater().equals(player1))
{
return new GameResult(0, 0, player1, player2,true,false,false,false);
}
else if (ex.getCheater().equals(player2))
{
return new GameResult(0,0,player1,player2,false,true,false,false);
}
else
{
return new GameResult(0,0,player1,player2,false,false,false,false);
}
}
catch (TimeOutException ex)
{
System.err.println(ex.getTimeOutPlayer().getName() + " ran out of time!");
if (ex.getTimeOutPlayer().equals(player1))
{
return new GameResult(0, 0, player1, player2,false,false,true,false);
}
else if (ex.getTimeOutPlayer().equals(player2))
{
return new GameResult(0,0,player1,player2,false,false,false,true);
}
else
{
return new GameResult(0,0,player1,player2,false,false,false,false);
}
}
}
/**
* Plays a single round of the game.
* @param maximizer The player with the goal to maximize the number of crossings.
* @param minimizer The player with the goal to minimize the number of crossings
* @return The number of crossings yielded in the final drawing.
* @throws InvalidMoveException An exception caused by cheating.
*/
private int playRound(Player maximizer, Player minimizer) throws InvalidMoveException, TimeOutException
{
int turn = 0; | GameState gs = new GameState(g,width,height); | 2 | 2023-10-18 12:11:38+00:00 | 8k |
mosaic-addons/traffic-state-estimation | src/main/java/com/dcaiti/mosaic/app/tse/FxdKernel.java | [
{
"identifier": "FxdRecord",
"path": "src/main/java/com/dcaiti/mosaic/app/fxd/data/FxdRecord.java",
"snippet": "public abstract class FxdRecord implements Serializable {\n\n /**\n * Time at record creation. [ns]\n */\n protected final long timeStamp;\n /**\n * Position at record cre... | import com.dcaiti.mosaic.app.fxd.data.FxdRecord;
import com.dcaiti.mosaic.app.fxd.data.FxdTraversal;
import com.dcaiti.mosaic.app.fxd.messages.FxdUpdateMessage;
import com.dcaiti.mosaic.app.tse.config.CFxdReceiverApp;
import com.dcaiti.mosaic.app.tse.events.ExpiredUnitRemovalEvent;
import com.dcaiti.mosaic.app.tse.processors.FxdProcessor;
import com.dcaiti.mosaic.app.tse.processors.MessageBasedProcessor;
import com.dcaiti.mosaic.app.tse.processors.TimeBasedProcessor;
import com.dcaiti.mosaic.app.tse.processors.TraversalBasedProcessor;
import org.eclipse.mosaic.fed.application.ambassador.simulation.communication.ReceivedV2xMessage;
import org.eclipse.mosaic.fed.application.ambassador.util.UnitLogger;
import org.eclipse.mosaic.lib.objects.v2x.MessageRouting;
import org.eclipse.mosaic.lib.objects.v2x.V2xMessage;
import org.eclipse.mosaic.lib.util.scheduling.Event;
import org.eclipse.mosaic.lib.util.scheduling.EventManager;
import org.eclipse.mosaic.lib.util.scheduling.EventProcessor;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.stream.Collectors;
import javax.annotation.Nullable; | 3,835 | /*
* Copyright (c) 2021 Fraunhofer FOKUS and others. All rights reserved.
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*
* Contact: mosaic@fokus.fraunhofer.de
*/
package com.dcaiti.mosaic.app.tse;
/**
* The {@link FxdKernel} and all its inheriting classes handle traversal recognition, event management, initializing and execution of
* the {@link FxdProcessor FxdProcessors}.
*
* @param <RecordT> Record type (extension of {@link FxdRecord}) containing all spatio-temporal information that units
* periodically transmit to the server
* @param <TraversalT> Traversal type (extension of {@link FxdTraversal}) containing the traversal of a single connection consisting of a
* list of {@link RecordT Records}.
* @param <UpdateT> Updated type (extension of {@link FxdUpdateMessage}) representing the actual messages send by units.
* The most generic implementation contains a collection of records sampled by a unit.
* @param <ConfigT> Type of the configuration (extension of {@link CFxdReceiverApp}) in its generic form this class contains
* configuration parameters for the expired unit removal and the configured {@link FxdProcessor FxdProcessors}.
*/
public abstract class FxdKernel<
RecordT extends FxdRecord, | /*
* Copyright (c) 2021 Fraunhofer FOKUS and others. All rights reserved.
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*
* Contact: mosaic@fokus.fraunhofer.de
*/
package com.dcaiti.mosaic.app.tse;
/**
* The {@link FxdKernel} and all its inheriting classes handle traversal recognition, event management, initializing and execution of
* the {@link FxdProcessor FxdProcessors}.
*
* @param <RecordT> Record type (extension of {@link FxdRecord}) containing all spatio-temporal information that units
* periodically transmit to the server
* @param <TraversalT> Traversal type (extension of {@link FxdTraversal}) containing the traversal of a single connection consisting of a
* list of {@link RecordT Records}.
* @param <UpdateT> Updated type (extension of {@link FxdUpdateMessage}) representing the actual messages send by units.
* The most generic implementation contains a collection of records sampled by a unit.
* @param <ConfigT> Type of the configuration (extension of {@link CFxdReceiverApp}) in its generic form this class contains
* configuration parameters for the expired unit removal and the configured {@link FxdProcessor FxdProcessors}.
*/
public abstract class FxdKernel<
RecordT extends FxdRecord, | TraversalT extends FxdTraversal<RecordT, TraversalT>, | 1 | 2023-10-23 16:39:40+00:00 | 8k |
Primogem-Craft-Development/Primogem-Craft-Fabric | src/main/java/com/primogemstudio/primogemcraft/blocks/PrimogemCraftBlocks.java | [
{
"identifier": "AgnidusAgateBlock",
"path": "src/main/java/com/primogemstudio/primogemcraft/blocks/instances/materials/agnidus/AgnidusAgateBlock.java",
"snippet": "public class AgnidusAgateBlock extends Block {\n public AgnidusAgateBlock() {\n super(BlockBehaviour.Properties.of().sound(SoundT... | import com.primogemstudio.primogemcraft.blocks.instances.*;
import com.primogemstudio.primogemcraft.blocks.instances.dendrocore.*;
import com.primogemstudio.primogemcraft.blocks.instances.materials.agnidus.AgnidusAgateBlock;
import com.primogemstudio.primogemcraft.blocks.instances.materials.agnidus.AgnidusAgateOreBlock;
import com.primogemstudio.primogemcraft.blocks.instances.materials.nagadus.NagadusEmeraldBlock;
import com.primogemstudio.primogemcraft.blocks.instances.materials.nagadus.NagadusEmeraldOreBlock;
import com.primogemstudio.primogemcraft.blocks.instances.materials.prithva.PrithvaTopazBlock;
import com.primogemstudio.primogemcraft.blocks.instances.materials.prithva.PrithvaTopazOreBlock;
import com.primogemstudio.primogemcraft.blocks.instances.materials.vajrada.VajradaAmethystBlock;
import com.primogemstudio.primogemcraft.blocks.instances.materials.vajrada.VajradaAmethystOre;
import com.primogemstudio.primogemcraft.blocks.instances.materials.vayuda.VayudaTurquoiseGemstoneBlock;
import com.primogemstudio.primogemcraft.blocks.instances.materials.vayuda.VayudaTurquoiseGemstoneOre;
import com.primogemstudio.primogemcraft.blocks.instances.mora.*;
import com.primogemstudio.primogemcraft.blocks.instances.planks.*;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.blockrenderlayer.v1.BlockRenderLayerMap;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.SoundType;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.state.properties.NoteBlockInstrument;
import static com.primogemstudio.primogemcraft.PrimogemCraftFabric.MOD_ID; | 4,517 | package com.primogemstudio.primogemcraft.blocks;
public class PrimogemCraftBlocks {
public static final DendroCoreBlock DENDRO_CORE_BLOCK = registerWithItem("dendro_core_block", new DendroCoreBlock());
public static final PrimogemBlock PRIMOGEM_BLOCK = registerWithItem("primogem_block", new PrimogemBlock());
public static final PrimogemOre PRIMOGEM_ORE = registerWithItem("primogem_ore", new PrimogemOre());
public static final Block DEEP_SLATE_PRIMOGEM_ORE = registerWithItem("deep_slate_primogem_ore", new Block(BlockBehaviour.Properties.of().instrument(NoteBlockInstrument.BASEDRUM).sound(SoundType.POLISHED_DEEPSLATE).strength(5f, 10f).lightLevel(s -> 1).requiresCorrectToolForDrops()));
public static final IntertwinedFateBlock INTERTWINED_FATE_BLOCK = registerWithItem("intertwined_fate_block", new IntertwinedFateBlock());
public static final MoraBunchBlock MORA_BUNCH_BLOCK = registerWithItem("mora_bunch_block", new MoraBunchBlock());
public static final MoraBlock MORA_BLOCK = registerWithItem("mora_block", new MoraBlock());
public static final ExquisiteMoraBlock EXQUISITE_MORA_BLOCK = registerWithItem("exquisite_mora_block", new ExquisiteMoraBlock());
public static final CheapMoraBlock CHEAP_MORA_BLOCK = registerWithItem("cheap_mora_block", new CheapMoraBlock());
public static final CheapMoraSlabBlock CHEAP_MORA_SLAB_BLOCK = registerWithItem("cheap_mora_slab", new CheapMoraSlabBlock());
public static final CheapMoraStairBlock CHEAP_MORA_STAIR_BLOCK = registerWithItem("cheap_mora_stair", new CheapMoraStairBlock());
public static final CheapMoraWallBlock CHEAP_MORA_WALL_BLOCK = registerWithItem("cheap_mora_wall", new CheapMoraWallBlock());
public static final TeyvatPlanksBlock TEYVAT_PLANKS_BLOCK = registerWithItem("teyvat_planks", new TeyvatPlanksBlock());
public static final TeyvatPlankSlabBlock TEYVAT_PLANK_SLAB_BLOCK = registerWithItem("teyvat_plank_slab", new TeyvatPlankSlabBlock());
public static final TeyvatPlankStairBlock TEYVAT_PLANK_STAIR_BLOCK = registerWithItem("teyvat_plank_stair", new TeyvatPlankStairBlock());
public static final TeyvatPlankFenceBlock TEYVAT_PLANK_FENCE_BLOCK = registerWithItem("teyvat_plank_fence", new TeyvatPlankFenceBlock());
public static final TeyvatPlankFenceGateBlock TEYVAT_PLANK_FENCE_GATE_BLOCK = registerWithItem("teyvat_plank_fence_gate", new TeyvatPlankFenceGateBlock());
public static final BlueTeyvatPlanksBlock BLUE_TEYVAT_PLANKS_BLOCK = registerWithItem("blue_teyvat_planks", new BlueTeyvatPlanksBlock());
public static final TeyvatPlankSlabBlock BLUE_TEYVAT_PLANK_SLAB_BLOCK = registerWithItem("blue_teyvat_plank_slab", new TeyvatPlankSlabBlock());
public static final TeyvatPlankStairBlock BLUE_TEYVAT_PLANK_STAIR_BLOCK = registerWithItem("blue_teyvat_plank_stair", new TeyvatPlankStairBlock());
public static final TeyvatPlankFenceBlock BLUE_TEYVAT_PLANK_FENCE_BLOCK = registerWithItem("blue_teyvat_plank_fence", new TeyvatPlankFenceBlock());
public static final TeyvatPlankFenceGateBlock BLUE_TEYVAT_PLANK_FENCE_GATE_BLOCK = registerWithItem("blue_teyvat_plank_fence_gate", new TeyvatPlankFenceGateBlock());
public static final PinkTeyvatPlanksBlock PINK_TEYVAT_PLANKS_BLOCK = registerWithItem("pink_teyvat_planks", new PinkTeyvatPlanksBlock());
public static final TeyvatPlankSlabBlock PINK_TEYVAT_PLANK_SLAB_BLOCK = registerWithItem("pink_teyvat_plank_slab", new TeyvatPlankSlabBlock());
public static final TeyvatPlankStairBlock PINK_TEYVAT_PLANK_STAIR_BLOCK = registerWithItem("pink_teyvat_plank_stair", new TeyvatPlankStairBlock());
public static final TeyvatPlankFenceBlock PINK_TEYVAT_PLANK_FENCE_BLOCK = registerWithItem("pink_teyvat_plank_fence", new TeyvatPlankFenceBlock());
public static final TeyvatPlankFenceGateBlock PINK_TEYVAT_PLANK_FENCE_GATE_BLOCK = registerWithItem("pink_teyvat_plank_fence_gate", new TeyvatPlankFenceGateBlock());
public static final CharCoalBlock CHAR_COAL_BLOCK = registerWithItem("charcoal_block", new CharCoalBlock());
public static final RustedPlankBlock RUSTED_PLANK_BLOCK = registerWithItem("rusted_plank", new RustedPlankBlock());
public static final RustedPlankStairsBlock RUSTED_PLANK_STAIR_BLOCK = registerWithItem("rusted_plank_stairs", new RustedPlankStairsBlock());
public static final RustIronBarBlock RUST_IRON_BAR_BLOCK = registerWithItem("rust_iron_bar", new RustIronBarBlock());
public static final DendroCorePlanksBlock DENDRO_CORE_PLANKS_BLOCK = registerWithItem("dendro_core_planks", new DendroCorePlanksBlock());
public static final DendroCorePlankSlabBlock DENDRO_CORE_PLANK_SLAB_BLOCK = registerWithItem("dendro_core_plank_slab", new DendroCorePlankSlabBlock());
public static final DendroCorePlankStairsBlock DENDRO_CORE_PLANK_STAIRS_BLOCK = registerWithItem("dendro_core_plank_stairs", new DendroCorePlankStairsBlock());
public static final DendroCorePlankPressurePlateBlock DENDRO_CORE_PLANK_PRESSURE_PLATE_BLOCK = registerWithItem("dendro_core_plank_pressure_plate", new DendroCorePlankPressurePlateBlock());
public static final DendroCodePlankButtonBlock DENDRO_CORE_PLANK_BUTTON_BLOCK = registerWithItem("dendro_core_plank_button", new DendroCodePlankButtonBlock());
public static final DendroCorePlanksFenceGateBlock DENDRO_CORE_PLANK_FENCE_GATE_BLOCK = registerWithItem("dendro_core_plank_fence_gate", new DendroCorePlanksFenceGateBlock());
public static final DendroCorePlankFenceBlock DENDRO_CORE_PLANK_FENCE_BLOCK = registerWithItem("dendro_core_plank_fence", new DendroCorePlankFenceBlock());
public static final VayudaTurquoiseGemstoneOre VAYUDA_TURQUOISE_GEMSTONE_ORE_BLOCK = registerWithItem("vayuda_turquoise_gemstone_ore", new VayudaTurquoiseGemstoneOre());
public static final VayudaTurquoiseGemstoneBlock VAYUDA_TURQUOISE_GEMSTONE_BLOCK = registerWithItem("vayuda_turquoise_gemstone_block", new VayudaTurquoiseGemstoneBlock());
public static final VajradaAmethystOre VAJRADA_AMETHYST_ORE_BLOCK = registerWithItem("vajrada_amethyst_ore", new VajradaAmethystOre());
public static final VajradaAmethystBlock VAJRADA_AMETHYST_BLOCK = registerWithItem("vajrada_amethyst_block", new VajradaAmethystBlock());
public static final March7thStatueBlock MARCH_7TH_STATUE_BLOCK = registerWithItem("march_7th_statue", new March7thStatueBlock());
public static final NagadusEmeraldOreBlock NAGADUS_EMERALD_ORE_BLOCK = registerWithItem("nagadus_emerald_ore", new NagadusEmeraldOreBlock()); | package com.primogemstudio.primogemcraft.blocks;
public class PrimogemCraftBlocks {
public static final DendroCoreBlock DENDRO_CORE_BLOCK = registerWithItem("dendro_core_block", new DendroCoreBlock());
public static final PrimogemBlock PRIMOGEM_BLOCK = registerWithItem("primogem_block", new PrimogemBlock());
public static final PrimogemOre PRIMOGEM_ORE = registerWithItem("primogem_ore", new PrimogemOre());
public static final Block DEEP_SLATE_PRIMOGEM_ORE = registerWithItem("deep_slate_primogem_ore", new Block(BlockBehaviour.Properties.of().instrument(NoteBlockInstrument.BASEDRUM).sound(SoundType.POLISHED_DEEPSLATE).strength(5f, 10f).lightLevel(s -> 1).requiresCorrectToolForDrops()));
public static final IntertwinedFateBlock INTERTWINED_FATE_BLOCK = registerWithItem("intertwined_fate_block", new IntertwinedFateBlock());
public static final MoraBunchBlock MORA_BUNCH_BLOCK = registerWithItem("mora_bunch_block", new MoraBunchBlock());
public static final MoraBlock MORA_BLOCK = registerWithItem("mora_block", new MoraBlock());
public static final ExquisiteMoraBlock EXQUISITE_MORA_BLOCK = registerWithItem("exquisite_mora_block", new ExquisiteMoraBlock());
public static final CheapMoraBlock CHEAP_MORA_BLOCK = registerWithItem("cheap_mora_block", new CheapMoraBlock());
public static final CheapMoraSlabBlock CHEAP_MORA_SLAB_BLOCK = registerWithItem("cheap_mora_slab", new CheapMoraSlabBlock());
public static final CheapMoraStairBlock CHEAP_MORA_STAIR_BLOCK = registerWithItem("cheap_mora_stair", new CheapMoraStairBlock());
public static final CheapMoraWallBlock CHEAP_MORA_WALL_BLOCK = registerWithItem("cheap_mora_wall", new CheapMoraWallBlock());
public static final TeyvatPlanksBlock TEYVAT_PLANKS_BLOCK = registerWithItem("teyvat_planks", new TeyvatPlanksBlock());
public static final TeyvatPlankSlabBlock TEYVAT_PLANK_SLAB_BLOCK = registerWithItem("teyvat_plank_slab", new TeyvatPlankSlabBlock());
public static final TeyvatPlankStairBlock TEYVAT_PLANK_STAIR_BLOCK = registerWithItem("teyvat_plank_stair", new TeyvatPlankStairBlock());
public static final TeyvatPlankFenceBlock TEYVAT_PLANK_FENCE_BLOCK = registerWithItem("teyvat_plank_fence", new TeyvatPlankFenceBlock());
public static final TeyvatPlankFenceGateBlock TEYVAT_PLANK_FENCE_GATE_BLOCK = registerWithItem("teyvat_plank_fence_gate", new TeyvatPlankFenceGateBlock());
public static final BlueTeyvatPlanksBlock BLUE_TEYVAT_PLANKS_BLOCK = registerWithItem("blue_teyvat_planks", new BlueTeyvatPlanksBlock());
public static final TeyvatPlankSlabBlock BLUE_TEYVAT_PLANK_SLAB_BLOCK = registerWithItem("blue_teyvat_plank_slab", new TeyvatPlankSlabBlock());
public static final TeyvatPlankStairBlock BLUE_TEYVAT_PLANK_STAIR_BLOCK = registerWithItem("blue_teyvat_plank_stair", new TeyvatPlankStairBlock());
public static final TeyvatPlankFenceBlock BLUE_TEYVAT_PLANK_FENCE_BLOCK = registerWithItem("blue_teyvat_plank_fence", new TeyvatPlankFenceBlock());
public static final TeyvatPlankFenceGateBlock BLUE_TEYVAT_PLANK_FENCE_GATE_BLOCK = registerWithItem("blue_teyvat_plank_fence_gate", new TeyvatPlankFenceGateBlock());
public static final PinkTeyvatPlanksBlock PINK_TEYVAT_PLANKS_BLOCK = registerWithItem("pink_teyvat_planks", new PinkTeyvatPlanksBlock());
public static final TeyvatPlankSlabBlock PINK_TEYVAT_PLANK_SLAB_BLOCK = registerWithItem("pink_teyvat_plank_slab", new TeyvatPlankSlabBlock());
public static final TeyvatPlankStairBlock PINK_TEYVAT_PLANK_STAIR_BLOCK = registerWithItem("pink_teyvat_plank_stair", new TeyvatPlankStairBlock());
public static final TeyvatPlankFenceBlock PINK_TEYVAT_PLANK_FENCE_BLOCK = registerWithItem("pink_teyvat_plank_fence", new TeyvatPlankFenceBlock());
public static final TeyvatPlankFenceGateBlock PINK_TEYVAT_PLANK_FENCE_GATE_BLOCK = registerWithItem("pink_teyvat_plank_fence_gate", new TeyvatPlankFenceGateBlock());
public static final CharCoalBlock CHAR_COAL_BLOCK = registerWithItem("charcoal_block", new CharCoalBlock());
public static final RustedPlankBlock RUSTED_PLANK_BLOCK = registerWithItem("rusted_plank", new RustedPlankBlock());
public static final RustedPlankStairsBlock RUSTED_PLANK_STAIR_BLOCK = registerWithItem("rusted_plank_stairs", new RustedPlankStairsBlock());
public static final RustIronBarBlock RUST_IRON_BAR_BLOCK = registerWithItem("rust_iron_bar", new RustIronBarBlock());
public static final DendroCorePlanksBlock DENDRO_CORE_PLANKS_BLOCK = registerWithItem("dendro_core_planks", new DendroCorePlanksBlock());
public static final DendroCorePlankSlabBlock DENDRO_CORE_PLANK_SLAB_BLOCK = registerWithItem("dendro_core_plank_slab", new DendroCorePlankSlabBlock());
public static final DendroCorePlankStairsBlock DENDRO_CORE_PLANK_STAIRS_BLOCK = registerWithItem("dendro_core_plank_stairs", new DendroCorePlankStairsBlock());
public static final DendroCorePlankPressurePlateBlock DENDRO_CORE_PLANK_PRESSURE_PLATE_BLOCK = registerWithItem("dendro_core_plank_pressure_plate", new DendroCorePlankPressurePlateBlock());
public static final DendroCodePlankButtonBlock DENDRO_CORE_PLANK_BUTTON_BLOCK = registerWithItem("dendro_core_plank_button", new DendroCodePlankButtonBlock());
public static final DendroCorePlanksFenceGateBlock DENDRO_CORE_PLANK_FENCE_GATE_BLOCK = registerWithItem("dendro_core_plank_fence_gate", new DendroCorePlanksFenceGateBlock());
public static final DendroCorePlankFenceBlock DENDRO_CORE_PLANK_FENCE_BLOCK = registerWithItem("dendro_core_plank_fence", new DendroCorePlankFenceBlock());
public static final VayudaTurquoiseGemstoneOre VAYUDA_TURQUOISE_GEMSTONE_ORE_BLOCK = registerWithItem("vayuda_turquoise_gemstone_ore", new VayudaTurquoiseGemstoneOre());
public static final VayudaTurquoiseGemstoneBlock VAYUDA_TURQUOISE_GEMSTONE_BLOCK = registerWithItem("vayuda_turquoise_gemstone_block", new VayudaTurquoiseGemstoneBlock());
public static final VajradaAmethystOre VAJRADA_AMETHYST_ORE_BLOCK = registerWithItem("vajrada_amethyst_ore", new VajradaAmethystOre());
public static final VajradaAmethystBlock VAJRADA_AMETHYST_BLOCK = registerWithItem("vajrada_amethyst_block", new VajradaAmethystBlock());
public static final March7thStatueBlock MARCH_7TH_STATUE_BLOCK = registerWithItem("march_7th_statue", new March7thStatueBlock());
public static final NagadusEmeraldOreBlock NAGADUS_EMERALD_ORE_BLOCK = registerWithItem("nagadus_emerald_ore", new NagadusEmeraldOreBlock()); | public static final NagadusEmeraldBlock NAGADUS_EMERALD_BLOCK = registerWithItem("nagadus_emerald_block", new NagadusEmeraldBlock()); | 2 | 2023-10-15 08:07:06+00:00 | 8k |
turtleisaac/PokEditor | src/main/java/io/github/turtleisaac/pokeditor/gui/editors/data/DefaultDataEditorPanel.java | [
{
"identifier": "ComboBoxItem",
"path": "src/main/java/io/github/turtleisaac/pokeditor/gui/EditorComboBox.java",
"snippet": "public static class ComboBoxItem\n{\n private String str;\n\n public ComboBoxItem(String str)\n {\n this.str= str;\n }\n\n public ComboBoxItem(int num)\n ... | import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import io.github.turtleisaac.nds4j.ui.ThemeUtils;
import io.github.turtleisaac.pokeditor.formats.GenericFileData;
import io.github.turtleisaac.pokeditor.gui.EditorComboBox.ComboBoxItem;
import io.github.turtleisaac.pokeditor.gui.EditorComboBox;
import io.github.turtleisaac.pokeditor.gui.PokeditorManager;
import net.miginfocom.swing.*; | 4,182 | /*
* Created by JFormDesigner
*/
package io.github.turtleisaac.pokeditor.gui.editors.data;
/**
* @author turtleisaac
*/
public class DefaultDataEditorPanel<G extends GenericFileData, E extends Enum<E>> extends JPanel {
private final DefaultDataEditor<G, E> editor; | /*
* Created by JFormDesigner
*/
package io.github.turtleisaac.pokeditor.gui.editors.data;
/**
* @author turtleisaac
*/
public class DefaultDataEditorPanel<G extends GenericFileData, E extends Enum<E>> extends JPanel {
private final DefaultDataEditor<G, E> editor; | private final PokeditorManager manager; | 2 | 2023-10-15 05:00:57+00:00 | 8k |
xiezhihui98/GAT1400 | src/main/java/com/cz/viid/kafka/listener/AbstractMessageListener.java | [
{
"identifier": "WebSocketEndpoint",
"path": "src/main/java/com/cz/viid/be/socket/WebSocketEndpoint.java",
"snippet": "@ServerEndpoint(\"/VIID/Subscribe/WebSocket\")\n@Component\npublic class WebSocketEndpoint {\n private static final Logger log = LoggerFactory.getLogger(WebSocketEndpoint.class);\n\n... | import com.alibaba.fastjson.JSONObject;
import com.cz.viid.be.socket.WebSocketEndpoint;
import com.cz.viid.be.task.action.KeepaliveAction;
import com.cz.viid.framework.config.Constants;
import com.cz.viid.framework.context.AppContextHolder;
import com.cz.viid.framework.domain.entity.VIIDPublish;
import com.cz.viid.framework.domain.entity.VIIDServer;
import com.cz.viid.framework.domain.vo.SubscribeNotificationRequest;
import com.cz.viid.kafka.KafkaStartupService;
import com.cz.viid.rpc.VIIDServerClient;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.support.Acknowledgment;
import java.net.URI;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors; | 6,013 | package com.cz.viid.kafka.listener;
public abstract class AbstractMessageListener<T> implements CustomMessageListener {
private final Logger log = LoggerFactory.getLogger(getClass()); | package com.cz.viid.kafka.listener;
public abstract class AbstractMessageListener<T> implements CustomMessageListener {
private final Logger log = LoggerFactory.getLogger(getClass()); | protected VIIDPublish publish; | 4 | 2023-10-23 11:25:43+00:00 | 8k |
eclipse-egit/egit | org.eclipse.egit.core/src/org/eclipse/egit/core/synchronize/GitRemoteResourceVariantTree.java | [
{
"identifier": "GitSynchronizeData",
"path": "org.eclipse.egit.core/src/org/eclipse/egit/core/synchronize/dto/GitSynchronizeData.java",
"snippet": "public class GitSynchronizeData {\n\n\tprivate static final IWorkspaceRoot ROOT = ResourcesPlugin.getWorkspace()\n\t\t\t\t\t.getRoot();\n\n\t/**\n\t * Matc... | import org.eclipse.egit.core.synchronize.dto.GitSynchronizeData;
import org.eclipse.egit.core.synchronize.dto.GitSynchronizeDataSet;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.team.core.variants.SessionResourceVariantByteStore; | 3,863 | /*******************************************************************************
* Copyright (c) 2010, 2013 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* IBM Corporation - initial API and implementation
* Dariusz Luksza <dariusz@luksza.org>
* Laurent Goubet <laurent.goubet@obeo.fr> - 393294
*******************************************************************************/
package org.eclipse.egit.core.synchronize;
class GitRemoteResourceVariantTree extends GitResourceVariantTree {
GitRemoteResourceVariantTree(GitSyncCache cache, GitSynchronizeDataSet data) {
super(new SessionResourceVariantByteStore(), cache, data);
}
@Override
protected ObjectId getObjectId(ThreeWayDiffEntry diffEntry) {
return diffEntry.getRemoteId().toObjectId();
}
@Override | /*******************************************************************************
* Copyright (c) 2010, 2013 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* IBM Corporation - initial API and implementation
* Dariusz Luksza <dariusz@luksza.org>
* Laurent Goubet <laurent.goubet@obeo.fr> - 393294
*******************************************************************************/
package org.eclipse.egit.core.synchronize;
class GitRemoteResourceVariantTree extends GitResourceVariantTree {
GitRemoteResourceVariantTree(GitSyncCache cache, GitSynchronizeDataSet data) {
super(new SessionResourceVariantByteStore(), cache, data);
}
@Override
protected ObjectId getObjectId(ThreeWayDiffEntry diffEntry) {
return diffEntry.getRemoteId().toObjectId();
}
@Override | protected RevCommit getCommitId(GitSynchronizeData gsd) { | 0 | 2023-10-20 15:17:51+00:00 | 8k |
leforero4-ui/unico_proyecto_con_todos_los_patrones_de_diseno_en_java | src/main/application/driver/adapter/usecase/Game.java | [
{
"identifier": "BigBoard",
"path": "src/main/application/driver/adapter/usecase/board/BigBoard.java",
"snippet": "public class BigBoard implements BoardCollection<Enemy> {\n private final Enemy[][] squares;\n private final PatternsIterator<Enemy> iterator;\n private static final int ROWS = 8;\... | import java.util.ArrayList;
import java.util.List;
import main.application.driver.adapter.usecase.board.BigBoard;
import main.application.driver.adapter.usecase.expression.ConjunctionExpression;
import main.application.driver.adapter.usecase.expression.Context;
import main.application.driver.adapter.usecase.expression.AlternativeExpression;
import main.application.driver.adapter.usecase.expression.EnemyExpression;
import main.application.driver.adapter.usecase.factory_enemies.EnemyBasicMethod;
import main.application.driver.adapter.usecase.factory_enemies.EnemyHighMethod;
import main.application.driver.adapter.usecase.factory_enemies.EnemyMiddleMethod;
import main.application.driver.adapter.usecase.mission.BasicMission;
import main.application.driver.adapter.usecase.mission.HighMission;
import main.application.driver.adapter.usecase.mission.MiddleMission;
import main.application.driver.port.usecase.EnemyMethod;
import main.application.driver.port.usecase.Expression;
import main.application.driver.port.usecase.GameableUseCase;
import main.application.driver.port.usecase.iterator.BoardCollection;
import main.application.driver.port.usecase.iterator.PatternsIterator;
import main.domain.model.ArmyFactory;
import main.domain.model.CaretakerPlayer;
import main.domain.model.Command;
import main.domain.model.Enemy;
import main.domain.model.FavorableEnvironment;
import main.domain.model.Healable;
import main.domain.model.Mission;
import main.domain.model.Player;
import main.domain.model.Player.MementoPlayer;
import main.domain.model.command.Attack;
import main.domain.model.command.HealingPlayer;
import main.domain.model.Visitor; | 7,197 | package main.application.driver.adapter.usecase;
public class Game implements GameableUseCase {
private final ArmyFactory armyFactory;
private EnemyMethod enemyMethod;
private final Player player;
private BoardCollection<Enemy> board;
private PatternsIterator<Enemy> enemyIterator;
private FavorableEnvironment favorableEnvironments;
private final Frostbite frostbite; | package main.application.driver.adapter.usecase;
public class Game implements GameableUseCase {
private final ArmyFactory armyFactory;
private EnemyMethod enemyMethod;
private final Player player;
private BoardCollection<Enemy> board;
private PatternsIterator<Enemy> enemyIterator;
private FavorableEnvironment favorableEnvironments;
private final Frostbite frostbite; | private final CaretakerPlayer caretakerPlayer; | 17 | 2023-10-20 18:36:47+00:00 | 8k |
greatwqs/finance-manager | src/main/java/com/github/greatwqs/app/controller/UserController.java | [
{
"identifier": "AppConstants",
"path": "src/main/java/com/github/greatwqs/app/common/AppConstants.java",
"snippet": "public class AppConstants {\n\n // default locale\n public static final Locale LOCALE = new Locale(\"zh\", \"CN\");\n\n /**\n * ErrorCode i18n properties prefix key.\n *... | import com.github.greatwqs.app.common.AppConstants;
import com.github.greatwqs.app.common.exception.AppException;
import com.github.greatwqs.app.common.exception.ErrorCode;
import com.github.greatwqs.app.component.RequestComponent;
import com.github.greatwqs.app.domain.po.UserPo;
import com.github.greatwqs.app.domain.vo.UserVo;
import com.github.greatwqs.app.interceptor.annotation.LoginRequired;
import com.github.greatwqs.app.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static com.github.greatwqs.app.common.AppConstants.*; | 3,794 | package com.github.greatwqs.app.controller;
/**
* 用户业务模块
*
* @author greatwqs
* Create on 2020/6/25
*/
@Slf4j
@RestController
@RequestMapping("user")
public class UserController {
@Autowired
private ModelMapper modelMapper;
@Autowired
private UserService userService;
@Autowired
private RequestComponent requestComponent;
/**
* 用户详情
*/
@LoginRequired
@RequestMapping(value = "info", method = RequestMethod.GET)
public UserVo getUserInfo() {
UserPo userPo = requestComponent.getLoginUser();
return modelMapper.map(userPo, UserVo.class);
}
/**
* 用户登录
*/
@RequestMapping(value = "login", method = RequestMethod.POST)
public void login(Model mode,
@RequestParam(value = "username") String username,
@RequestParam(value = "password") String password,
HttpServletResponse response) throws IOException {
final String loginIp = requestComponent.getClientIp();
final String loginToken = userService.login(username, password, loginIp);
if (StringUtils.isEmpty(loginToken)) {
log.warn("user login failed! username: " + username); | package com.github.greatwqs.app.controller;
/**
* 用户业务模块
*
* @author greatwqs
* Create on 2020/6/25
*/
@Slf4j
@RestController
@RequestMapping("user")
public class UserController {
@Autowired
private ModelMapper modelMapper;
@Autowired
private UserService userService;
@Autowired
private RequestComponent requestComponent;
/**
* 用户详情
*/
@LoginRequired
@RequestMapping(value = "info", method = RequestMethod.GET)
public UserVo getUserInfo() {
UserPo userPo = requestComponent.getLoginUser();
return modelMapper.map(userPo, UserVo.class);
}
/**
* 用户登录
*/
@RequestMapping(value = "login", method = RequestMethod.POST)
public void login(Model mode,
@RequestParam(value = "username") String username,
@RequestParam(value = "password") String password,
HttpServletResponse response) throws IOException {
final String loginIp = requestComponent.getClientIp();
final String loginToken = userService.login(username, password, loginIp);
if (StringUtils.isEmpty(loginToken)) {
log.warn("user login failed! username: " + username); | throw new AppException(ErrorCode.USER_LOGIN_ERROR); | 1 | 2023-10-16 12:45:57+00:00 | 8k |
Wind-Gone/Vodka | code/src/main/java/utils/load/LoadDataWorker.java | [
{
"identifier": "NationData",
"path": "code/src/main/java/benchmark/olap/data/NationData.java",
"snippet": "public class NationData {\n public static Integer[] nationKey = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24};\n public static String[] nationNam... | import benchmark.olap.data.NationData;
import benchmark.olap.data.RegionData;
import utils.math.random.BasicRandom;
import org.apache.log4j.Logger;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.*;
import java.util.Date; | 5,209 | package utils.load;/*
* LoadDataWorker - Class to utils.load one Warehouse (or in a special case
* the ITEM table).
*
*
*
*/
public class LoadDataWorker implements Runnable {
private static Logger log = Logger.getLogger(LoadDataWorker.class);
private int worker;
private Connection dbConn; | package utils.load;/*
* LoadDataWorker - Class to utils.load one Warehouse (or in a special case
* the ITEM table).
*
*
*
*/
public class LoadDataWorker implements Runnable {
private static Logger log = Logger.getLogger(LoadDataWorker.class);
private int worker;
private Connection dbConn; | private BasicRandom rnd; | 2 | 2023-10-22 11:22:32+00:00 | 8k |
Onuraktasj/stock-tracking-system | src/main/java/com/onuraktas/stocktrackingsystem/impl/ProductServiceImpl.java | [
{
"identifier": "ProductProducer",
"path": "src/main/java/com/onuraktas/stocktrackingsystem/amqp/producer/ProductProducer.java",
"snippet": "@Component\npublic class ProductProducer {\n\n private final RabbitTemplate rabbitTemplate;\n\n public ProductProducer(RabbitTemplate rabbitTemplate) {\n ... | import com.onuraktas.stocktrackingsystem.amqp.producer.ProductProducer;
import com.onuraktas.stocktrackingsystem.constant.QueueName;
import com.onuraktas.stocktrackingsystem.dto.amqp.DeletedProductMessage;
import com.onuraktas.stocktrackingsystem.dto.entity.ProductDto;
import com.onuraktas.stocktrackingsystem.dto.general.SimpleCategory;
import com.onuraktas.stocktrackingsystem.dto.request.CreateProductRequest;
import com.onuraktas.stocktrackingsystem.dto.request.UpdateProductAmountRequest;
import com.onuraktas.stocktrackingsystem.dto.response.CreateProductResponse;
import com.onuraktas.stocktrackingsystem.dto.response.DeleteProductByIdResponse;
import com.onuraktas.stocktrackingsystem.entity.Category;
import com.onuraktas.stocktrackingsystem.entity.CategoryProductRel;
import com.onuraktas.stocktrackingsystem.entity.Product;
import com.onuraktas.stocktrackingsystem.entity.enums.Status;
import com.onuraktas.stocktrackingsystem.exception.ProductBadRequestException;
import com.onuraktas.stocktrackingsystem.exception.ProductNotFoundException;
import com.onuraktas.stocktrackingsystem.helper.GeneralValues;
import com.onuraktas.stocktrackingsystem.mapper.ProductMapper;
import com.onuraktas.stocktrackingsystem.message.ExceptionMessages;
import com.onuraktas.stocktrackingsystem.message.ProductMessages;
import com.onuraktas.stocktrackingsystem.repository.CategoryProductRelRepository;
import com.onuraktas.stocktrackingsystem.repository.CategoryRepository;
import com.onuraktas.stocktrackingsystem.repository.ProductRepository;
import com.onuraktas.stocktrackingsystem.service.ProductService;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.*; | 3,824 | package com.onuraktas.stocktrackingsystem.impl;
@Service
public class ProductServiceImpl implements ProductService {
private final ProductRepository productRepository;
private final CategoryProductRelRepository categoryProductRelRepository;
private final CategoryRepository categoryRepository;
private final ProductProducer productProducer;
public ProductServiceImpl (ProductRepository productRepository, CategoryProductRelRepository categoryProductRelRepository, CategoryRepository categoryRepository, ProductProducer productProducer){
this.productRepository = productRepository;
this.categoryProductRelRepository = categoryProductRelRepository;
this.categoryRepository = categoryRepository;
this.productProducer = productProducer;
}
@Override
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public CreateProductResponse createProduct(CreateProductRequest createProductRequest) {
this.validateCreateProductRequest(createProductRequest);
List<Category> categoryList = this.categoryRepository.findAllByCategoryIdInAndIsActive(createProductRequest.getCategoryList().stream().map(SimpleCategory::getCategoryId).toList(), Boolean.TRUE);
if (categoryList.isEmpty())
throw new ProductBadRequestException(ProductMessages.CATEGORY_NOT_FOUND);
List<UUID> categoryIdList = categoryList.stream().map(Category::getCategoryId).toList();
Product product = this.productRepository.save(ProductMapper.toEntity(createProductRequest));
CreateProductResponse createProductResponse = ProductMapper.toCreateProductResponse(product);
createProductResponse.setStatus(Status.OK.getStatus());
List<CategoryProductRel> categoryProductRelList = new ArrayList<>();
for (UUID categoryId : categoryIdList) {
categoryProductRelList.add(CategoryProductRel.builder().categoryId(categoryId).productId(product.getProductId()).build());
}
this.categoryProductRelRepository.saveAll(categoryProductRelList);
return createProductResponse;
}
@Override
public List<ProductDto> getAllProduct() {
return ProductMapper.toDtoList(productRepository.findAll());
}
@Override
public ProductDto getProduct(UUID productId) {
return ProductMapper.toDto(productRepository.findById(productId).orElseThrow(()-> new NoSuchElementException(ProductMessages.PRODUCT_NOT_FOUND)));
}
@Override
public ResponseEntity<ProductDto> updateProduct(UUID productId, ProductDto productDto) {
if (Objects.isNull(productId) || Objects.isNull(productDto.getProductId()) || !Objects.equals(productId,productDto.getProductId()))
return ResponseEntity.badRequest().build();
Optional<Product> existProduct = productRepository.findById(productId);
if (existProduct.isEmpty())
return ResponseEntity.notFound().build();
final ProductDto updateProduct = this.save(productDto);
if (Objects.nonNull(updateProduct))
return ResponseEntity.ok(updateProduct);
return ResponseEntity.internalServerError().build();
}
@Override
public ProductDto updateProductAmount(UUID productId, UpdateProductAmountRequest request) {
Product product = productRepository.findById(productId).orElseThrow(()-> new NoSuchElementException(ProductMessages.PRODUCT_NOT_FOUND));
product.setAmount(request.getAmount());
productRepository.save(product);
return ProductMapper.toDto(productRepository.save(product));
}
@Override
public DeleteProductByIdResponse deleteProductById(UUID productId) {
Product deletedProduct = this.productRepository.findByProductIdAndIsActive(productId, Boolean.TRUE).orElseThrow(()-> new ProductNotFoundException(ProductMessages.PRODUCT_NOT_FOUND));
deletedProduct.setIsActive(Boolean.FALSE);
this.productRepository.save(deletedProduct);
List<CategoryProductRel> categoryProductRelList = this.categoryProductRelRepository.findAllByProductIdAndIsActive(productId, Boolean.TRUE);
categoryProductRelList.forEach(categoryProductRel -> {
categoryProductRel.setIsActive(Boolean.FALSE);
});
this.categoryProductRelRepository.saveAll(categoryProductRelList);
return DeleteProductByIdResponse.builder().productId(productId).isActive(Boolean.FALSE).build();
}
@Override
public List<ProductDto> getProductListByCategory(UUID categoryId) {
List<UUID> productIdList = this.categoryProductRelRepository.findAllByCategoryIdAndIsActive(categoryId, Boolean.TRUE).stream().map(CategoryProductRel::getProductId).toList();
if (productIdList.isEmpty())
throw new ProductNotFoundException(ProductMessages.PRODUCT_NOT_FOUND);
List<ProductDto> productDtoList = ProductMapper.toDtoList(this.productRepository.findAllByProductIdInAndIsActive(productIdList, Boolean.TRUE));
if (productDtoList.isEmpty())
throw new ProductNotFoundException(ProductMessages.PRODUCT_NOT_FOUND);
return productDtoList;
}
@Override
public void deleteProductListByProductListIdList(List<UUID> productIdList) {
List<Product> productList = this.productRepository.findAllByProductIdInAndIsActive(productIdList, Boolean.TRUE);
productList.forEach(product -> product.setIsActive(Boolean.FALSE));
this.productRepository.saveAll(productList);
List<DeletedProductMessage> deletedProductMessageList = new ArrayList<>();
productList.stream().map(Product::getProductId).forEach(productId -> deletedProductMessageList.add(DeletedProductMessage.builder().productId(productId).build()));
this.productProducer.sendToQueue(QueueName.DELETED_PRODUCT_QUEUE, deletedProductMessageList);
}
private ProductDto save (ProductDto productDto){
Product product = ProductMapper.toEntity(productDto);
product = productRepository.save(product);
return ProductMapper.toDto(product);
}
private void validateCreateProductRequest(CreateProductRequest createProductRequest) {
if (Objects.isNull(createProductRequest)) | package com.onuraktas.stocktrackingsystem.impl;
@Service
public class ProductServiceImpl implements ProductService {
private final ProductRepository productRepository;
private final CategoryProductRelRepository categoryProductRelRepository;
private final CategoryRepository categoryRepository;
private final ProductProducer productProducer;
public ProductServiceImpl (ProductRepository productRepository, CategoryProductRelRepository categoryProductRelRepository, CategoryRepository categoryRepository, ProductProducer productProducer){
this.productRepository = productRepository;
this.categoryProductRelRepository = categoryProductRelRepository;
this.categoryRepository = categoryRepository;
this.productProducer = productProducer;
}
@Override
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public CreateProductResponse createProduct(CreateProductRequest createProductRequest) {
this.validateCreateProductRequest(createProductRequest);
List<Category> categoryList = this.categoryRepository.findAllByCategoryIdInAndIsActive(createProductRequest.getCategoryList().stream().map(SimpleCategory::getCategoryId).toList(), Boolean.TRUE);
if (categoryList.isEmpty())
throw new ProductBadRequestException(ProductMessages.CATEGORY_NOT_FOUND);
List<UUID> categoryIdList = categoryList.stream().map(Category::getCategoryId).toList();
Product product = this.productRepository.save(ProductMapper.toEntity(createProductRequest));
CreateProductResponse createProductResponse = ProductMapper.toCreateProductResponse(product);
createProductResponse.setStatus(Status.OK.getStatus());
List<CategoryProductRel> categoryProductRelList = new ArrayList<>();
for (UUID categoryId : categoryIdList) {
categoryProductRelList.add(CategoryProductRel.builder().categoryId(categoryId).productId(product.getProductId()).build());
}
this.categoryProductRelRepository.saveAll(categoryProductRelList);
return createProductResponse;
}
@Override
public List<ProductDto> getAllProduct() {
return ProductMapper.toDtoList(productRepository.findAll());
}
@Override
public ProductDto getProduct(UUID productId) {
return ProductMapper.toDto(productRepository.findById(productId).orElseThrow(()-> new NoSuchElementException(ProductMessages.PRODUCT_NOT_FOUND)));
}
@Override
public ResponseEntity<ProductDto> updateProduct(UUID productId, ProductDto productDto) {
if (Objects.isNull(productId) || Objects.isNull(productDto.getProductId()) || !Objects.equals(productId,productDto.getProductId()))
return ResponseEntity.badRequest().build();
Optional<Product> existProduct = productRepository.findById(productId);
if (existProduct.isEmpty())
return ResponseEntity.notFound().build();
final ProductDto updateProduct = this.save(productDto);
if (Objects.nonNull(updateProduct))
return ResponseEntity.ok(updateProduct);
return ResponseEntity.internalServerError().build();
}
@Override
public ProductDto updateProductAmount(UUID productId, UpdateProductAmountRequest request) {
Product product = productRepository.findById(productId).orElseThrow(()-> new NoSuchElementException(ProductMessages.PRODUCT_NOT_FOUND));
product.setAmount(request.getAmount());
productRepository.save(product);
return ProductMapper.toDto(productRepository.save(product));
}
@Override
public DeleteProductByIdResponse deleteProductById(UUID productId) {
Product deletedProduct = this.productRepository.findByProductIdAndIsActive(productId, Boolean.TRUE).orElseThrow(()-> new ProductNotFoundException(ProductMessages.PRODUCT_NOT_FOUND));
deletedProduct.setIsActive(Boolean.FALSE);
this.productRepository.save(deletedProduct);
List<CategoryProductRel> categoryProductRelList = this.categoryProductRelRepository.findAllByProductIdAndIsActive(productId, Boolean.TRUE);
categoryProductRelList.forEach(categoryProductRel -> {
categoryProductRel.setIsActive(Boolean.FALSE);
});
this.categoryProductRelRepository.saveAll(categoryProductRelList);
return DeleteProductByIdResponse.builder().productId(productId).isActive(Boolean.FALSE).build();
}
@Override
public List<ProductDto> getProductListByCategory(UUID categoryId) {
List<UUID> productIdList = this.categoryProductRelRepository.findAllByCategoryIdAndIsActive(categoryId, Boolean.TRUE).stream().map(CategoryProductRel::getProductId).toList();
if (productIdList.isEmpty())
throw new ProductNotFoundException(ProductMessages.PRODUCT_NOT_FOUND);
List<ProductDto> productDtoList = ProductMapper.toDtoList(this.productRepository.findAllByProductIdInAndIsActive(productIdList, Boolean.TRUE));
if (productDtoList.isEmpty())
throw new ProductNotFoundException(ProductMessages.PRODUCT_NOT_FOUND);
return productDtoList;
}
@Override
public void deleteProductListByProductListIdList(List<UUID> productIdList) {
List<Product> productList = this.productRepository.findAllByProductIdInAndIsActive(productIdList, Boolean.TRUE);
productList.forEach(product -> product.setIsActive(Boolean.FALSE));
this.productRepository.saveAll(productList);
List<DeletedProductMessage> deletedProductMessageList = new ArrayList<>();
productList.stream().map(Product::getProductId).forEach(productId -> deletedProductMessageList.add(DeletedProductMessage.builder().productId(productId).build()));
this.productProducer.sendToQueue(QueueName.DELETED_PRODUCT_QUEUE, deletedProductMessageList);
}
private ProductDto save (ProductDto productDto){
Product product = ProductMapper.toEntity(productDto);
product = productRepository.save(product);
return ProductMapper.toDto(product);
}
private void validateCreateProductRequest(CreateProductRequest createProductRequest) {
if (Objects.isNull(createProductRequest)) | throw new ProductBadRequestException(ExceptionMessages.BAD_REQUEST); | 17 | 2023-10-23 19:00:09+00:00 | 8k |
ushh789/FinancialCalculator | src/main/java/com/netrunners/financialcalculator/MenuControllers/ResultTableController.java | [
{
"identifier": "Converter",
"path": "src/main/java/com/netrunners/financialcalculator/LogicalInstrumnts/CurrencyConverter/Converter.java",
"snippet": "public class Converter {\n public static JsonArray getRates() throws IOException {\n URL url = new URL(\"https://bank.gov.ua/NBUStatService/v1... | import com.netrunners.financialcalculator.LogicalInstrumnts.CurrencyConverter.Converter;
import com.netrunners.financialcalculator.LogicalInstrumnts.FileInstruments.LogHelper;
import com.netrunners.financialcalculator.LogicalInstrumnts.TimeFunctions.DateTimeFunctions;
import com.netrunners.financialcalculator.LogicalInstrumnts.TypesOfFinancialOpearation.Deposit.*;
import com.netrunners.financialcalculator.LogicalInstrumnts.TypesOfFinancialOpearation.Credit.*;
import com.netrunners.financialcalculator.VisualInstruments.MenuActions.*;
import com.netrunners.financialcalculator.VisualInstruments.WindowsOpener;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.logging.Level; | 5,450 | }
tempDate = tempDate.plusDays(daysToNextPeriod);
numbersColumnFlag++;
}
return data;
}
private List<Object[]> countCreditWithHolidaysData(CreditWithHolidays credit) {
DaystoNextPeriod.add(0);
DaystoNextPeriodWithHolidays.add(0);
LocalDate tempDate = credit.getStartDate();
List<Object[]> data = new ArrayList<>();
int numbersColumnFlag = 0;
float dailyBodyPart = credit.countCreditBodyPerDay();
dailyPart = credit.countCreditBodyPerDay();
float tempLoan;
loan = credit.getLoan();
while (!tempDate.equals(credit.getEndDate())) {
tempLoan = credit.getLoan();
float totalLoan = tempLoan;
float creditBody = 0;
float periodPercents = 0;
int daysToNextPeriod = DateTimeFunctions.countDaysToNextPeriod(credit, tempDate);
if (numbersColumnFlag == 0) {
periodColumn.textProperty().bind(languageManager.getStringBinding(credit.getNameOfPaymentType()));
investmentloanColumn.textProperty().bind(languageManager.getStringBinding("LoanInput"));
periodProfitLoanColumn.textProperty().bind(languageManager.getStringBinding("PaymentLoan"));
} else {
DaystoNextPeriod.add(daysToNextPeriod);
DaystoNextPeriodWithHolidays.add(daysToNextPeriod);
for (int i = 0; i < daysToNextPeriod; i++) {
if (!DateTimeFunctions.isDateBetweenDates(tempDate, credit.getHolidaysStart(), credit.getHolidaysEnd())) {
creditBody += dailyBodyPart;
} else {
DaystoNextPeriod.set(numbersColumnFlag, DaystoNextPeriod.get(numbersColumnFlag) - 1);
}
periodPercents += credit.countLoan();
tempDate = tempDate.plusDays(1);
}
if (tempDate.equals(credit.getEndDate())) {
creditBody = tempLoan;
}
totalLoan -= creditBody;
credit.setLoan(totalLoan);
}
data.add(new Object[]{numbersColumnFlag,
String.format("%.2f", tempLoan) + credit.getCurrency(),
String.format("%.2f", creditBody) + credit.getCurrency(),
String.format("%.2f", totalLoan) + credit.getCurrency(),
String.format("%.2f", periodPercents) + credit.getCurrency()
});
numbersColumnFlag++;
}
return data;
}
private List<Object[]> countCreditWithoutHolidaysData(Credit credit) {
DaystoNextPeriod.add(0);
DaystoNextPeriodWithHolidays.add(0);
LocalDate tempDate = credit.getStartDate();
List<Object[]> data = new ArrayList<>();
int numbersColumnFlag = 0;
float dailyBodyPart = credit.countCreditBodyPerDay();
dailyPart = credit.countCreditBodyPerDay();
loan = credit.getLoan();
float tempLoan;
while (tempDate.isBefore(credit.getEndDate())) {
tempLoan = credit.getLoan();
float totalLoan = tempLoan;
float creditBody = 0;
float periodPercents = 0;
int daysToNextPeriod = DateTimeFunctions.countDaysToNextPeriod(credit, tempDate);
if (numbersColumnFlag == 0) {
periodColumn.textProperty().bind(languageManager.getStringBinding(credit.getNameOfPaymentType()));
investmentloanColumn.textProperty().bind(languageManager.getStringBinding("LoanInput"));
periodProfitLoanColumn.textProperty().bind(languageManager.getStringBinding("PaymentLoan"));
} else {
DaystoNextPeriod.add(daysToNextPeriod);
DaystoNextPeriodWithHolidays.add(daysToNextPeriod);
for (int i = 0; i < daysToNextPeriod; i++) {
periodPercents += credit.countLoan();
creditBody += dailyBodyPart;
tempDate = tempDate.plusDays(1);
}
if (tempDate.equals(credit.getEndDate())) {
creditBody = tempLoan;
}
totalLoan -= creditBody;
credit.setLoan(totalLoan);
}
data.add(new Object[]{numbersColumnFlag,
String.format("%.2f", tempLoan) + credit.getCurrency(),
String.format("%.2f", creditBody) + credit.getCurrency(),
String.format("%.2f", totalLoan) + credit.getCurrency(),
String.format("%.2f", periodPercents) + credit.getCurrency()
});
numbersColumnFlag++;
}
return data;
}
private void writeDataToCSV(List<Object[]> data, Deposit deposit, File file) {
if(file!=null){
try (PrintWriter writer = new PrintWriter(new FileWriter(file))) {
writer.println(deposit.getNameOfWithdrawalType() + ";" + investmentloanColumn.getText() + ";" + periodProfitLoanColumn.getText() + ";" + totalColumn.getText());
for (Object[] row : data) {
writer.println(row[0] + ";" + row[1] + ";" + row[2] + ";" + row[3]);
writer.flush();
}
writer.println("Annual percent of deposit: " + deposit.getAnnualPercent());
writer.println("Currency: " + deposit.getCurrency());
writer.println("Start date: " + deposit.getStartDate());
writer.println("End date: " + deposit.getEndDate());
if (deposit.isEarlyWithdrawal()) {
writer.println("Early withdrawal date: " + deposit.getEarlyWithdrawalDate());
}
} catch (IOException e) { | package com.netrunners.financialcalculator.MenuControllers;
public class ResultTableController {
@FXML
private MenuItem aboutUs;
@FXML
private MenuItem creditButtonMenu;
@FXML
private MenuItem currency;
@FXML
private MenuItem darkTheme;
@FXML
private Menu fileButton;
@FXML
private Menu aboutButton;
@FXML
private MenuItem depositButtonMenu;
@FXML
private MenuItem exitApp;
@FXML
private TableColumn<Object[], Integer> periodColumn;
@FXML
private MenuItem languageButton;
@FXML
private MenuItem lightTheme;
@FXML
private TableColumn<Object[], String> investmentloanColumn;
@FXML
private MenuItem openFileButton;
@FXML
private TableColumn<Object[], String> periodProfitLoanColumn;
@FXML
private TableView<Object[]> resultTable;
@FXML
private MenuItem saveAsButton;
@FXML
private MenuItem saveButton;
@FXML
private Menu viewButton;
@FXML
private Menu settingsButton;
@FXML
private Menu themeButton;
@FXML
private TableColumn<Object[], String> totalColumn;
@FXML
private TableColumn<Object[], String> periodPercentsColumn;
@FXML
private Button exportButton;
@FXML
private Menu newButton;
@FXML
private Label financialCalculatorLabel;
@FXML
private Button convertButton;
float loan;
float dailyPart;
private LanguageManager languageManager = LanguageManager.getInstance();
List<Integer> DaystoNextPeriodWithHolidays = new ArrayList<>();
List<Integer> DaystoNextPeriod = new ArrayList<>();
private String userSelectedCurrency;
float tempinvest;
@FXML
void initialize() {
openFileButton.setDisable(true);
currency.setDisable(true);
darkTheme.setOnAction(event -> ThemeSelector.setDarkTheme());
lightTheme.setOnAction(event -> ThemeSelector.setLightTheme());
aboutUs.setOnAction(event -> AboutUsAlert.showAboutUs());
exitApp.setOnAction(event -> ExitApp.exitApp());
depositButtonMenu.setOnAction(event -> WindowsOpener.depositOpener());
creditButtonMenu.setOnAction(event -> WindowsOpener.creditOpener());
exportButton.setOnAction(event -> {
});
convertButton.setOnAction(event -> {
List<String> choices = new ArrayList<>();
choices.add("₴");
choices.add("$");
choices.add("£");
choices.add("€");
ChoiceDialog<String> dialog = new ChoiceDialog<>("-", choices);
dialog.setTitle(LanguageManager.getInstance().getStringBinding("ConvertTitle").get());
Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("file:src/main/resources/com/netrunners/financialcalculator/assets/Logo.png"));
dialog.setHeaderText(null);
dialog.setContentText(LanguageManager.getInstance().getStringBinding("ConvertTo").get());
Optional<String> result = dialog.showAndWait();
if (result.isPresent()) {
String selectedConvertCurrency = result.get();
float rate = Converter.getRateByCC(Converter.getCC(userSelectedCurrency)) / Converter.getRateByCC(Converter.getCC(selectedConvertCurrency));
ObservableList<Object[]> investmentLoanColumnItems = investmentloanColumn.getTableView().getItems();
ObservableList<Object[]> periodProfitLoanColumnItems = periodProfitLoanColumn.getTableView().getItems();
ObservableList<Object[]> totalColumnItems = totalColumn.getTableView().getItems();
for (Object[] item : investmentLoanColumnItems) {
item[1] = extractFloatValue((String) item[1]) * rate;
String newValue = String.format("%.2f", item[1]) + selectedConvertCurrency;
item[1] = newValue;
if(!investmentLoanColumnItems.isEmpty()) {
if(loan==0){tempinvest = extractFloatValue((String) investmentLoanColumnItems.get(0)[1]);}
else{ loan = extractFloatValue((String) investmentLoanColumnItems.get(0)[1]);}
}
}
for (Object[] item : periodProfitLoanColumnItems) {
item[2] = extractFloatValue((String) item[2]) * rate;
String newValue = String.format("%.2f", item[2]) + selectedConvertCurrency;
item[2] = newValue;
}
for (Object[] item : totalColumnItems) {
item[3] = extractFloatValue((String) item[3]) * rate;
String newValue = String.format("%.2f", item[3]) + selectedConvertCurrency;
item[3] = newValue;
}
if (periodPercentsColumn.isVisible()) {
ObservableList<Object[]> periodPercentsColumnItems = periodPercentsColumn.getTableView().getItems();
for (Object[] item : periodPercentsColumnItems) {
item[4] = extractFloatValue((String) item[4]) * rate;
String newValue = String.format("%.2f", item[4]) + selectedConvertCurrency;
item[4] = newValue;
}
}
userSelectedCurrency = selectedConvertCurrency;
resultTable.refresh();
}
});
languageButton.setOnAction(event -> {
List<String> choices = new ArrayList<>();
choices.add("English");
choices.add("Українська");
choices.add("Español");
choices.add("Français");
choices.add("Deutsch");
choices.add("Czech");
choices.add("Polski");
choices.add("Nederlands");
choices.add("日本語");
choices.add("中国人");
ChoiceDialog<String> dialog = new ChoiceDialog<>("English", choices);
dialog.setTitle(LanguageManager.getInstance().getStringBinding("LanguageTitle").get());
Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("file:src/main/resources/com/netrunners/financialcalculator/assets/Logo.png"));
dialog.setHeaderText(null);
dialog.setContentText(LanguageManager.getInstance().getStringBinding("ChooseLanguage").get());
Optional<String> result = dialog.showAndWait();
if (result.isPresent()) {
String chosenLanguage = result.get();
Locale locale = switch (chosenLanguage) {
case "Українська" -> new Locale("uk");
case "Español" -> new Locale("es");
case "Français" -> new Locale("fr");
case "Deutsch" -> new Locale("de");
case "Czech" -> new Locale("cs");
case "Polski" -> new Locale("pl");
case "Nederlands" -> new Locale("nl");
case "日本語" -> new Locale("ja");
case "中国人" -> new Locale("zh");
default -> new Locale("en");
};
languageManager.changeLanguage(locale);
}
});
financialCalculatorLabel.textProperty().bind(languageManager.getStringBinding("ResultTableLabel"));
depositButtonMenu.textProperty().bind(languageManager.getStringBinding("DepositButton"));
creditButtonMenu.textProperty().bind(languageManager.getStringBinding("CreditButton"));
languageButton.textProperty().bind(languageManager.getStringBinding("languageButton"));
darkTheme.textProperty().bind(languageManager.getStringBinding("darkTheme"));
lightTheme.textProperty().bind(languageManager.getStringBinding("lightTheme"));
aboutUs.textProperty().bind(languageManager.getStringBinding("aboutUs"));
exitApp.textProperty().bind(languageManager.getStringBinding("exitApp"));
currency.textProperty().bind(languageManager.getStringBinding("currency"));
openFileButton.textProperty().bind(languageManager.getStringBinding("openFileButton"));
saveAsButton.textProperty().bind(languageManager.getStringBinding("saveAsButton"));
saveButton.textProperty().bind(languageManager.getStringBinding("saveButton"));
totalColumn.textProperty().bind(languageManager.getStringBinding("totalColumn"));
periodPercentsColumn.textProperty().bind(languageManager.getStringBinding("PeriodPercents"));
exportButton.textProperty().bind(languageManager.getStringBinding("Export"));
viewButton.textProperty().bind(languageManager.getStringBinding("viewButton"));
settingsButton.textProperty().bind(languageManager.getStringBinding("settingsButton"));
themeButton.textProperty().bind(languageManager.getStringBinding("themeButton"));
fileButton.textProperty().bind(languageManager.getStringBinding("fileButton"));
aboutButton.textProperty().bind(languageManager.getStringBinding("aboutButton"));
newButton.textProperty().bind(languageManager.getStringBinding("newButton"));
convertButton.textProperty().bind(languageManager.getStringBinding("ConvertTitle"));
}
public void updateTable(Deposit deposit) {
fillColumns(deposit);
}
public void updateTable(Credit credit) {
fillColumns(credit);
}
private void fillColumns(Credit credit) {
userSelectedCurrency = credit.getCurrency();
resultTable.getColumns().clear();
periodPercentsColumn.setVisible(true);
periodColumn.setCellValueFactory(cellData -> cellData.getValue()[0] == null ? null : new SimpleObjectProperty<>((Integer) cellData.getValue()[0]));
investmentloanColumn.setCellValueFactory(cellData -> cellData.getValue()[1] == null ? null : new SimpleObjectProperty<>((String) cellData.getValue()[1]));
periodProfitLoanColumn.setCellValueFactory(cellData -> cellData.getValue()[2] == null ? null : new SimpleObjectProperty<>((String) cellData.getValue()[2]));
totalColumn.setCellValueFactory(cellData -> cellData.getValue()[3] == null ? null : new SimpleObjectProperty<>((String) cellData.getValue()[3]));
periodPercentsColumn.setCellValueFactory(cellData -> cellData.getValue()[4] == null ? null : new SimpleObjectProperty<>((String) cellData.getValue()[4]));
List<Object[]> data = new ArrayList<>();
resultTable.getColumns().addAll(periodColumn, investmentloanColumn, periodProfitLoanColumn, totalColumn, periodPercentsColumn);
if (credit instanceof CreditWithoutHolidays) {
data = countCreditWithoutHolidaysData(credit);
} else if (credit instanceof CreditWithHolidays) {
data = countCreditWithHolidaysData((CreditWithHolidays) credit);
}
ObservableList<Object[]> observableData = FXCollections.observableArrayList(data);
resultTable.setItems(observableData);
List<Object[]> finalData = data;
exportButton.setOnAction(event -> {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle(LanguageManager.getInstance().getStringBinding("Export").get());
File initialDirectory = new File("saves/");
fileChooser.setInitialDirectory(initialDirectory);
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("CSV Files", "*.csv"));
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Excel Files", "*.xlsx"));
File file = fileChooser.showSaveDialog(null);
if (file != null && file.getName().endsWith(".xlsx")) {
writeDataToExcel(finalData, credit, file);
} else {
writeDataToCSV(finalData, credit, file);
}
});
saveButton.setOnAction(event -> {
System.out.println(loan);
System.out.println(tempinvest);
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss");
String formattedNow = now.format(formatter);
File file = new File("saves/Credit_result_" + formattedNow + ".csv");
writeDataToCSV(finalData, credit, file);
SavingAlert.showSavingAlert();
});
saveAsButton.setOnAction(event -> {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle(LanguageManager.getInstance().getStringBinding("saveAsButton").get());
File initialDirectory = new File("saves/");
fileChooser.setInitialDirectory(initialDirectory);
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("CSV Files", "*.csv"));
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Excel Files", "*.xlsx"));
File file = fileChooser.showSaveDialog(null);
if (file != null && file.getName().endsWith(".xlsx")) {
writeDataToExcel(finalData, credit, file);
} else {
writeDataToCSV(finalData, credit, file);
}
});
}
private void fillColumns(Deposit deposit) {
userSelectedCurrency = deposit.getCurrency();
resultTable.getColumns().clear();
periodPercentsColumn.setVisible(false);
periodColumn.setCellValueFactory(cellData -> cellData.getValue()[0] == null ? null : new SimpleObjectProperty<>((Integer) cellData.getValue()[0]));
investmentloanColumn.setCellValueFactory(cellData -> cellData.getValue()[1] == null ? null : new SimpleObjectProperty<>((String) cellData.getValue()[1]));
periodProfitLoanColumn.setCellValueFactory(cellData -> cellData.getValue()[2] == null ? null : new SimpleObjectProperty<>((String) cellData.getValue()[2]));
totalColumn.setCellValueFactory(cellData -> cellData.getValue()[3] == null ? null : new SimpleObjectProperty<>((String) cellData.getValue()[3]));
List<Object[]> data = countDepositData(deposit);
resultTable.getColumns().addAll(periodColumn, investmentloanColumn, periodProfitLoanColumn, totalColumn);
ObservableList<Object[]> observableData = FXCollections.observableArrayList(data);
resultTable.setItems(observableData);
exportButton.setOnAction(event -> {
FileChooser fileChooser = new FileChooser();
File initialDirectory = new File("saves/");
fileChooser.setInitialDirectory(initialDirectory);
fileChooser.setTitle(LanguageManager.getInstance().getStringBinding("Export").get());
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("CSV Files", "*.csv"));
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Excel Files", "*.xlsx"));
File file = fileChooser.showSaveDialog(null);
if (file != null && file.getName().endsWith(".xlsx")) {
writeDataToExcel(data, deposit, file);
} else {
writeDataToCSV(data, deposit, file);
}
});
saveButton.setOnAction(event -> {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss");
String formattedNow = now.format(formatter);
File file = new File("saves/Deposit_result_" + formattedNow + ".csv");
writeDataToCSV(data, deposit, file);
SavingAlert.showSavingAlert();
});
saveAsButton.setOnAction(event -> {
FileChooser fileChooser = new FileChooser();
File initialDirectory = new File("saves/");
fileChooser.setInitialDirectory(initialDirectory);
fileChooser.setTitle(LanguageManager.getInstance().getStringBinding("saveAsButton").get());
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("CSV Files", "*.csv"));
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Excel Files", "*.xlsx"));
File file = fileChooser.showSaveDialog(null);
if (file != null && file.getName().endsWith(".xlsx")) {
writeDataToExcel(data, deposit, file);
} else {
writeDataToCSV(data, deposit, file);
}
});
}
private List<Object[]> countDepositData(Deposit deposit) {
DaystoNextPeriod.add(0);
List<Object[]> data = new ArrayList<>();
LocalDate tempDate = deposit.getStartDate();
float tempInvestment = deposit.getInvestment();
tempinvest = tempInvestment;
float totalInvestment = tempInvestment;
int numbersColumnFlag = 0;
LocalDate endOfContract;
if (deposit.isEarlyWithdrawal()) {
endOfContract = deposit.getEarlyWithdrawalDate();
} else {
endOfContract = deposit.getEndDate();
}
boolean capitalize = deposit instanceof CapitalisedDeposit;
while (!tempDate.equals(endOfContract)) {
float periodProfit = 0;
int daysToNextPeriod = DateTimeFunctions.countDaysToNextPeriod(deposit, tempDate, endOfContract);
if (numbersColumnFlag == 0) {
periodColumn.textProperty().bind(languageManager.getStringBinding(deposit.getNameOfWithdrawalType()));
investmentloanColumn.textProperty().bind(languageManager.getStringBinding("InvestInput"));
periodProfitLoanColumn.textProperty().bind(languageManager.getStringBinding("ProfitColumn"));
daysToNextPeriod = 0;
} else {
DaystoNextPeriod.add(daysToNextPeriod);
if (capitalize) {
for (int i = 0; i < daysToNextPeriod; i++) {
periodProfit += deposit.countProfit();
}
} else {
for (int i = 0; i < daysToNextPeriod; i++) {
periodProfit += deposit.countProfit();
}
}
}
totalInvestment += periodProfit;
data.add(new Object[]{numbersColumnFlag,
String.format("%.2f", tempInvestment) + deposit.getCurrency(),
String.format("%.2f", periodProfit) + deposit.getCurrency(),
String.format("%.2f", totalInvestment) + deposit.getCurrency()
});
if (capitalize) {
tempInvestment = totalInvestment;
deposit.setInvestment(tempInvestment);
}
tempDate = tempDate.plusDays(daysToNextPeriod);
numbersColumnFlag++;
}
return data;
}
private List<Object[]> countCreditWithHolidaysData(CreditWithHolidays credit) {
DaystoNextPeriod.add(0);
DaystoNextPeriodWithHolidays.add(0);
LocalDate tempDate = credit.getStartDate();
List<Object[]> data = new ArrayList<>();
int numbersColumnFlag = 0;
float dailyBodyPart = credit.countCreditBodyPerDay();
dailyPart = credit.countCreditBodyPerDay();
float tempLoan;
loan = credit.getLoan();
while (!tempDate.equals(credit.getEndDate())) {
tempLoan = credit.getLoan();
float totalLoan = tempLoan;
float creditBody = 0;
float periodPercents = 0;
int daysToNextPeriod = DateTimeFunctions.countDaysToNextPeriod(credit, tempDate);
if (numbersColumnFlag == 0) {
periodColumn.textProperty().bind(languageManager.getStringBinding(credit.getNameOfPaymentType()));
investmentloanColumn.textProperty().bind(languageManager.getStringBinding("LoanInput"));
periodProfitLoanColumn.textProperty().bind(languageManager.getStringBinding("PaymentLoan"));
} else {
DaystoNextPeriod.add(daysToNextPeriod);
DaystoNextPeriodWithHolidays.add(daysToNextPeriod);
for (int i = 0; i < daysToNextPeriod; i++) {
if (!DateTimeFunctions.isDateBetweenDates(tempDate, credit.getHolidaysStart(), credit.getHolidaysEnd())) {
creditBody += dailyBodyPart;
} else {
DaystoNextPeriod.set(numbersColumnFlag, DaystoNextPeriod.get(numbersColumnFlag) - 1);
}
periodPercents += credit.countLoan();
tempDate = tempDate.plusDays(1);
}
if (tempDate.equals(credit.getEndDate())) {
creditBody = tempLoan;
}
totalLoan -= creditBody;
credit.setLoan(totalLoan);
}
data.add(new Object[]{numbersColumnFlag,
String.format("%.2f", tempLoan) + credit.getCurrency(),
String.format("%.2f", creditBody) + credit.getCurrency(),
String.format("%.2f", totalLoan) + credit.getCurrency(),
String.format("%.2f", periodPercents) + credit.getCurrency()
});
numbersColumnFlag++;
}
return data;
}
private List<Object[]> countCreditWithoutHolidaysData(Credit credit) {
DaystoNextPeriod.add(0);
DaystoNextPeriodWithHolidays.add(0);
LocalDate tempDate = credit.getStartDate();
List<Object[]> data = new ArrayList<>();
int numbersColumnFlag = 0;
float dailyBodyPart = credit.countCreditBodyPerDay();
dailyPart = credit.countCreditBodyPerDay();
loan = credit.getLoan();
float tempLoan;
while (tempDate.isBefore(credit.getEndDate())) {
tempLoan = credit.getLoan();
float totalLoan = tempLoan;
float creditBody = 0;
float periodPercents = 0;
int daysToNextPeriod = DateTimeFunctions.countDaysToNextPeriod(credit, tempDate);
if (numbersColumnFlag == 0) {
periodColumn.textProperty().bind(languageManager.getStringBinding(credit.getNameOfPaymentType()));
investmentloanColumn.textProperty().bind(languageManager.getStringBinding("LoanInput"));
periodProfitLoanColumn.textProperty().bind(languageManager.getStringBinding("PaymentLoan"));
} else {
DaystoNextPeriod.add(daysToNextPeriod);
DaystoNextPeriodWithHolidays.add(daysToNextPeriod);
for (int i = 0; i < daysToNextPeriod; i++) {
periodPercents += credit.countLoan();
creditBody += dailyBodyPart;
tempDate = tempDate.plusDays(1);
}
if (tempDate.equals(credit.getEndDate())) {
creditBody = tempLoan;
}
totalLoan -= creditBody;
credit.setLoan(totalLoan);
}
data.add(new Object[]{numbersColumnFlag,
String.format("%.2f", tempLoan) + credit.getCurrency(),
String.format("%.2f", creditBody) + credit.getCurrency(),
String.format("%.2f", totalLoan) + credit.getCurrency(),
String.format("%.2f", periodPercents) + credit.getCurrency()
});
numbersColumnFlag++;
}
return data;
}
private void writeDataToCSV(List<Object[]> data, Deposit deposit, File file) {
if(file!=null){
try (PrintWriter writer = new PrintWriter(new FileWriter(file))) {
writer.println(deposit.getNameOfWithdrawalType() + ";" + investmentloanColumn.getText() + ";" + periodProfitLoanColumn.getText() + ";" + totalColumn.getText());
for (Object[] row : data) {
writer.println(row[0] + ";" + row[1] + ";" + row[2] + ";" + row[3]);
writer.flush();
}
writer.println("Annual percent of deposit: " + deposit.getAnnualPercent());
writer.println("Currency: " + deposit.getCurrency());
writer.println("Start date: " + deposit.getStartDate());
writer.println("End date: " + deposit.getEndDate());
if (deposit.isEarlyWithdrawal()) {
writer.println("Early withdrawal date: " + deposit.getEarlyWithdrawalDate());
}
} catch (IOException e) { | LogHelper.log(Level.SEVERE, "Error while writing Deposit to CSV", e); | 1 | 2023-10-18 16:03:09+00:00 | 8k |
bowbahdoe/java-audio-stack | tritonus-share/src/main/java/dev/mccue/tritonus/share/sampled/convert/TAsynchronousFilteredAudioInputStream.java | [
{
"identifier": "TCircularBuffer",
"path": "tritonus-share/src/main/java/dev/mccue/tritonus/share/TCircularBuffer.java",
"snippet": "public class TCircularBuffer\r\n{\r\n\tprivate boolean\t\tm_bBlockingRead;\r\n\tprivate boolean\t\tm_bBlockingWrite;\r\n\tprivate byte[]\t\tm_abData;\r\n\tprivate int\t\t\... | import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import dev.mccue.tritonus.share.TCircularBuffer;
import dev.mccue.tritonus.share.TDebug;
| 4,158 | /*
* TAsynchronousFilteredAudioInputStream.java
*
* This file is part of Tritonus: http://www.tritonus.org/
*/
/*
* Copyright (c) 1999, 2000 by Matthias Pfisterer
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
/*
|<--- this code is formatted to fit into 80 columns --->|
*/
package dev.mccue.tritonus.share.sampled.convert;
/** Base class for asynchronus converters.
This class serves as base class for
converters that do not have a fixed
ratio between the size of a block of input
data and the size of a block of output data.
These types of converters therefore need an
internal buffer, which is realized in this
class.
@author Matthias Pfisterer
*/
public abstract class TAsynchronousFilteredAudioInputStream
extends TAudioInputStream
implements TCircularBuffer.Trigger
{
private static final int DEFAULT_BUFFER_SIZE = 327670;
private static final int DEFAULT_MIN_AVAILABLE = 4096;
private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
// must be protected because it's accessed by the native CDDA lib
protected TCircularBuffer m_circularBuffer;
private int m_nMinAvailable;
private byte[] m_abSingleByte;
/** Constructor.
This constructor uses the default buffer size and the default
min available amount.
@param lLength length of this stream in frames. May be
AudioSystem.NOT_SPECIFIED.
*/
public TAsynchronousFilteredAudioInputStream(AudioFormat outputFormat, long lLength)
{
this(outputFormat, lLength,
DEFAULT_BUFFER_SIZE,
DEFAULT_MIN_AVAILABLE);
}
/** Constructor.
With this constructor, the buffer size and the minimum
available amount can be specified as parameters.
@param lLength length of this stream in frames. May be
AudioSystem.NOT_SPECIFIED.
@param nBufferSize size of the circular buffer in bytes.
*/
public TAsynchronousFilteredAudioInputStream(
AudioFormat outputFormat, long lLength,
int nBufferSize,
int nMinAvailable)
{
/* The usage of a ByteArrayInputStream is a hack.
* (the infamous "JavaOne hack", because I did it on June
* 6th 2000 in San Francisco, only hours before a
* JavaOne session where I wanted to show mp3 playback
* with Java Sound.) It is necessary because in the FCS
* version of the Sun jdk1.3, the constructor of
* AudioInputStream throws an exception if its first
* argument is null. So we have to pass a dummy non-null
* value.
*/
super(new ByteArrayInputStream(EMPTY_BYTE_ARRAY),
outputFormat,
lLength);
| /*
* TAsynchronousFilteredAudioInputStream.java
*
* This file is part of Tritonus: http://www.tritonus.org/
*/
/*
* Copyright (c) 1999, 2000 by Matthias Pfisterer
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
/*
|<--- this code is formatted to fit into 80 columns --->|
*/
package dev.mccue.tritonus.share.sampled.convert;
/** Base class for asynchronus converters.
This class serves as base class for
converters that do not have a fixed
ratio between the size of a block of input
data and the size of a block of output data.
These types of converters therefore need an
internal buffer, which is realized in this
class.
@author Matthias Pfisterer
*/
public abstract class TAsynchronousFilteredAudioInputStream
extends TAudioInputStream
implements TCircularBuffer.Trigger
{
private static final int DEFAULT_BUFFER_SIZE = 327670;
private static final int DEFAULT_MIN_AVAILABLE = 4096;
private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
// must be protected because it's accessed by the native CDDA lib
protected TCircularBuffer m_circularBuffer;
private int m_nMinAvailable;
private byte[] m_abSingleByte;
/** Constructor.
This constructor uses the default buffer size and the default
min available amount.
@param lLength length of this stream in frames. May be
AudioSystem.NOT_SPECIFIED.
*/
public TAsynchronousFilteredAudioInputStream(AudioFormat outputFormat, long lLength)
{
this(outputFormat, lLength,
DEFAULT_BUFFER_SIZE,
DEFAULT_MIN_AVAILABLE);
}
/** Constructor.
With this constructor, the buffer size and the minimum
available amount can be specified as parameters.
@param lLength length of this stream in frames. May be
AudioSystem.NOT_SPECIFIED.
@param nBufferSize size of the circular buffer in bytes.
*/
public TAsynchronousFilteredAudioInputStream(
AudioFormat outputFormat, long lLength,
int nBufferSize,
int nMinAvailable)
{
/* The usage of a ByteArrayInputStream is a hack.
* (the infamous "JavaOne hack", because I did it on June
* 6th 2000 in San Francisco, only hours before a
* JavaOne session where I wanted to show mp3 playback
* with Java Sound.) It is necessary because in the FCS
* version of the Sun jdk1.3, the constructor of
* AudioInputStream throws an exception if its first
* argument is null. So we have to pass a dummy non-null
* value.
*/
super(new ByteArrayInputStream(EMPTY_BYTE_ARRAY),
outputFormat,
lLength);
| if (TDebug.TraceAudioConverter) { TDebug.out("TAsynchronousFilteredAudioInputStream.<init>(): begin"); }
| 1 | 2023-10-19 14:09:37+00:00 | 8k |
dvillavicencio/Riven-of-a-Thousand-Servers | src/test/java/com/danielvm/destiny2bot/integration/InteractionControllerTest.java | [
{
"identifier": "BungieConfiguration",
"path": "src/main/java/com/danielvm/destiny2bot/config/BungieConfiguration.java",
"snippet": "@Data\n@Configuration\n@ConfigurationProperties(prefix = \"bungie.api\")\npublic class BungieConfiguration implements OAuth2Configuration {\n\n /**\n * The name of the ... | import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching;
import static org.assertj.core.api.Assertions.assertThat;
import com.danielvm.destiny2bot.config.BungieConfiguration;
import com.danielvm.destiny2bot.config.DiscordConfiguration;
import com.danielvm.destiny2bot.dao.UserDetailsReactiveDao;
import com.danielvm.destiny2bot.dto.destiny.GenericResponse;
import com.danielvm.destiny2bot.dto.destiny.milestone.MilestoneEntry;
import com.danielvm.destiny2bot.dto.discord.DiscordUser;
import com.danielvm.destiny2bot.dto.discord.Interaction;
import com.danielvm.destiny2bot.dto.discord.InteractionData;
import com.danielvm.destiny2bot.dto.discord.Member;
import com.danielvm.destiny2bot.entity.UserDetails;
import com.danielvm.destiny2bot.enums.InteractionType;
import com.danielvm.destiny2bot.enums.ManifestEntity;
import com.danielvm.destiny2bot.util.MessageUtil;
import com.danielvm.destiny2bot.util.OAuth2Util;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.PublicKey;
import java.time.Instant;
import java.util.Map;
import java.util.Objects;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec;
import org.springframework.web.reactive.function.BodyInserters;
import software.pando.crypto.nacl.Crypto; | 7,052 | stubFor(get(urlPathEqualTo("/bungie/Destiny2/Milestones/"))
.withHeader("x-api-key", equalTo(bungieConfiguration.getKey()))
.willReturn(aResponse()
.withStatus(400)
.withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.withBodyFile("bungie/missing-api-key.json")));
// when: the request is sent
var response = webTestClient.post()
.uri("/interactions")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.header("X-Signature-Ed25519", signature)
.header("X-Signature-Timestamp", timestamp)
.body(BodyInserters.fromValue(body))
.exchange();
// then: the response JSON is correct
String errorJson;
try {
errorJson = objectMapper.writeValueAsString(
objectMapper.readValue(
new ClassPathResource("__files/bungie/missing-api-key.json").getInputStream(),
Object.class));
} catch (IOException e) {
throw new RuntimeException(e);
}
response.expectStatus()
.isBadRequest()
.expectBody()
.jsonPath("$.detail").value(json -> assertJsonLenient(errorJson, json))
.jsonPath("$.status").isEqualTo(HttpStatus.BAD_REQUEST.value());
}
@Test
@DisplayName("Interactions fail if the signature is invalid")
public void getWeeklyRaidInvalidSignature() throws JsonProcessingException, DecoderException {
// given: an interaction with an invalid signature
InteractionData data = new InteractionData(2, "weekly_raid", 1);
Interaction body = new Interaction(1, "theApplicationId", 2, data, null);
String timestamp = String.valueOf(Instant.now().getEpochSecond());
String signature = createInvalidSignature(body, timestamp);
// when: the request is sent
var response = webTestClient.post()
.uri("/interactions")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.header("X-Signature-Ed25519", signature)
.header("X-Signature-Timestamp", timestamp)
.body(BodyInserters.fromValue(body))
.exchange();
// then: the response JSON has the correct error message
response.expectStatus()
.isBadRequest()
.expectBody()
.jsonPath("$.status").isEqualTo(HttpStatus.BAD_REQUEST.value())
.jsonPath("$.detail").isEqualTo("interactions.request: Signature is invalid");
}
@Test
@DisplayName("PING interactions with valid signatures are ack'd correctly")
public void pingRequestsAreAckdCorrectly() throws JsonProcessingException, DecoderException {
// given: an interaction with an invalid signature
Interaction body = new Interaction(1, "theApplicationId", 1, null, null);
String timestamp = String.valueOf(Instant.now().getEpochSecond());
String signature = createValidSignature(body, timestamp);
// when: the request is sent
var response = webTestClient.post()
.uri("/interactions")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.header("X-Signature-Ed25519", signature)
.header("X-Signature-Timestamp", timestamp)
.body(BodyInserters.fromValue(body))
.exchange();
// then: the response JSON has the correct error message
response.expectStatus()
.isOk()
.expectBody()
.jsonPath("$.type").isEqualTo(InteractionType.PING.getType());
}
@Test
@DisplayName("PING interactions with invalid signatures are not ack'd")
public void invalidPingRequestsAreNotAckd() throws JsonProcessingException, DecoderException {
// given: an interaction with an invalid signature
Interaction body = new Interaction(1, "theApplicationId", 1, null, null);
String timestamp = String.valueOf(Instant.now().getEpochSecond());
String signature = createInvalidSignature(body, timestamp);
// when: the request is sent
var response = webTestClient.post()
.uri("/interactions")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.header("X-Signature-Ed25519", signature)
.header("X-Signature-Timestamp", timestamp)
.body(BodyInserters.fromValue(body))
.exchange();
// then: the response JSON has the correct error message
response.expectStatus()
.isBadRequest()
.expectBody()
.jsonPath("$.status").isEqualTo(HttpStatus.BAD_REQUEST.value())
.jsonPath("$.detail").isEqualTo("interactions.request: Signature is invalid");
}
@Test
@DisplayName("Autocomplete requests for raid stats returns the user's characters successfully")
public void autocompleteRequestsForRaidStats() throws DecoderException, JsonProcessingException {
// given: a valid autocomplete request
String username = "deahtstroke";
String discordId = "123456";
| package com.danielvm.destiny2bot.integration;
public class InteractionControllerTest extends BaseIntegrationTest {
private static final String VALID_PRIVATE_KEY = "F0EA3A0516695324C03ED552CD5A08A58CA1248172E8816C3BF235E52E75A7BF";
private static final String MALICIOUS_PRIVATE_KEY = "CE4517095255B0C92D586AF9EEC27B998D68775363F9FE74341483FB3A657CEC";
// Static mapper to be used on the @BeforeAll static method
private static final ObjectMapper OBJECT_MAPPER = new JsonMapper.Builder(new JsonMapper())
.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.build()
.registerModule(new JavaTimeModule());
@Autowired
BungieConfiguration bungieConfiguration;
@Autowired
DiscordConfiguration discordConfiguration;
@Autowired
UserDetailsReactiveDao userDetailsReactiveDao;
/**
* This method replaces all the placeholder values in the milestones-response.json file The reason
* for this is that the /weekly_raid and /weekly_dungeon responses will be weird if the dates are
* not dynamic, therefore this method
*
* @throws IOException in case we are not able to write back to the file (in-place)
*/
@BeforeAll
public static void before() throws IOException {
File milestoneFile = new File("src/test/resources/__files/bungie/milestone-response.json");
TypeReference<GenericResponse<Map<String, MilestoneEntry>>> typeReference = new TypeReference<>() {
};
var milestoneResponse = OBJECT_MAPPER.readValue(milestoneFile, typeReference);
replaceDates(milestoneResponse, "526718853");
replaceDates(milestoneResponse, "2712317338");
OBJECT_MAPPER.writeValue(milestoneFile, milestoneResponse);
}
private static void replaceDates(GenericResponse<Map<String, MilestoneEntry>> response,
String hash) {
response.getResponse().entrySet().stream()
.filter(entry -> Objects.equals(entry.getKey(), hash))
.forEach(entry -> {
var startDate = entry.getValue().getStartDate();
var endDate = entry.getValue().getEndDate();
if (Objects.nonNull(startDate)) {
entry.getValue().setStartDate(MessageUtil.PREVIOUS_TUESDAY);
}
if (Objects.nonNull(endDate)) {
entry.getValue().setEndDate(MessageUtil.NEXT_TUESDAY);
}
});
}
private String createValidSignature(Interaction body, String timestamp)
throws JsonProcessingException, DecoderException {
KeyPair signingKeys = Crypto.seedSigningKeyPair(Hex.decodeHex(VALID_PRIVATE_KEY.toCharArray()));
discordConfiguration.setBotPublicKey(
Hex.encodeHexString(
signingKeys.getPublic().getEncoded())); // change the public key in the config class
var signatureBytes = Crypto.sign(signingKeys.getPrivate(),
(timestamp + objectMapper.writeValueAsString(body)).getBytes(StandardCharsets.UTF_8));
return Hex.encodeHexString(signatureBytes);
}
private String createInvalidSignature(Interaction body, String timestamp)
throws JsonProcessingException, DecoderException {
KeyPair invalidSigningKeyPair = Crypto.seedSigningKeyPair(
Hex.decodeHex(MALICIOUS_PRIVATE_KEY.toCharArray()));
PublicKey validPublicKey = Crypto.seedSigningKeyPair(
Hex.decodeHex(VALID_PRIVATE_KEY.toCharArray())).getPublic();
discordConfiguration.setBotPublicKey(
Hex.encodeHexString(validPublicKey.getEncoded()));
var signatureBytes = Crypto.sign(invalidSigningKeyPair.getPrivate(),
(timestamp + objectMapper.writeValueAsString(body)).getBytes(StandardCharsets.UTF_8));
return Hex.encodeHexString(signatureBytes);
}
@Test
@DisplayName("get weekly dungeon works successfully")
public void getWeeklyDungeonWorksSuccessfully() throws JsonProcessingException, DecoderException {
// given: a weekly_dungeon interaction with a valid signature
InteractionData weeklyDungeonData = new InteractionData(2, "weekly_dungeon", 1);
Interaction body = new Interaction(1, "theApplicationId", 2, weeklyDungeonData, null);
String timestamp = String.valueOf(Instant.now().getEpochSecond());
String signature = createValidSignature(body, timestamp);
stubFor(get(urlPathEqualTo("/bungie/Destiny2/Milestones/"))
.withHeader("x-api-key", equalTo(bungieConfiguration.getKey()))
.willReturn(aResponse()
.withStatus(200)
.withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.withBodyFile("bungie/milestone-response.json")));
var activityDefinition = ManifestEntity.ACTIVITY_DEFINITION.getId();
var activityHash = "1262462921";
stubFor(get(urlPathEqualTo(
"/bungie/Destiny2/Manifest/%s/%s/".formatted(activityDefinition, activityHash)))
.withHeader("x-api-key", equalTo(bungieConfiguration.getKey()))
.willReturn(aResponse()
.withStatus(200)
.withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.withBodyFile("bungie/dungeon-activity-response.json")));
var masterDungeonHash = "2296818662";
stubFor(get(urlPathEqualTo(
"/bungie/Destiny2/Manifest/%s/%s/".formatted(activityDefinition, masterDungeonHash)))
.withHeader("x-api-key", equalTo(bungieConfiguration.getKey()))
.willReturn(aResponse()
.withStatus(200)
.withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.withBodyFile("bungie/master-dungeon-activity-response.json")));
var activityTypeDefinition = ManifestEntity.ACTIVITY_TYPE_DEFINITION.getId();
var activityTypeHash = "608898761";
stubFor(get(urlPathEqualTo(
"/bungie/Destiny2/Manifest/%s/%s/".formatted(activityTypeDefinition, activityTypeHash)))
.withHeader("x-api-key", equalTo(bungieConfiguration.getKey()))
.willReturn(aResponse()
.withStatus(200)
.withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.withBodyFile("bungie/dungeon-activity-type-response.json")));
var milestoneDefinition = ManifestEntity.MILESTONE_DEFINITION.getId();
var milestoneHash = "526718853";
stubFor(get(urlPathEqualTo(
"/bungie/Destiny2/Manifest/%s/%s/".formatted(milestoneDefinition, milestoneHash)))
.withHeader("x-api-key", equalTo(bungieConfiguration.getKey()))
.willReturn(aResponse()
.withStatus(200)
.withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.withBodyFile("bungie/dungeon-milestone-response.json")));
// when: the request is sent
var response = webTestClient.post()
.uri("/interactions")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.header("X-Signature-Ed25519", signature)
.header("X-Signature-Timestamp", timestamp)
.body(BodyInserters.fromValue(body))
.exchange();
// then: the response JSON is correct
response.expectStatus()
.isOk()
.expectBody()
.jsonPath("$.type").isEqualTo(4)
.jsonPath("$.data.content").isEqualTo(
"""
This week's dungeon is: Spire of the Watcher.
You have until %s to complete it before the next dungeon in the rotation.
""".formatted(MessageUtil.formatDate(MessageUtil.NEXT_TUESDAY.toLocalDate())));
}
@Test
@DisplayName("get weekly raid works successfully")
public void getWeeklyRaidWorksSuccessfully() throws JsonProcessingException, DecoderException {
// given: a weekly_raid interaction with a valid signature
InteractionData weeklyRaidData = new InteractionData(2, "weekly_raid", 1);
Interaction body = new Interaction(1, "theApplicationId", 2, weeklyRaidData, null);
String timestamp = String.valueOf(Instant.now().getEpochSecond());
String signature = createValidSignature(body, timestamp);
stubFor(get(urlPathEqualTo("/bungie/Destiny2/Milestones/"))
.withHeader("x-api-key", equalTo(bungieConfiguration.getKey()))
.willReturn(aResponse()
.withStatus(200)
.withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.withBodyFile("bungie/milestone-response.json")));
var activityDefinition = ManifestEntity.ACTIVITY_DEFINITION.getId();
var activityHash = "1042180643";
stubFor(get(urlPathEqualTo(
"/bungie/Destiny2/Manifest/%s/%s/".formatted(activityDefinition, activityHash)))
.withHeader("x-api-key", equalTo(bungieConfiguration.getKey()))
.willReturn(aResponse()
.withStatus(200)
.withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.withBodyFile("bungie/raid-activity-response.json")));
var activityTypeDefinition = ManifestEntity.ACTIVITY_TYPE_DEFINITION.getId();
var activityTypeHash = "2043403989";
stubFor(get(urlPathEqualTo(
"/bungie/Destiny2/Manifest/%s/%s/".formatted(activityTypeDefinition, activityTypeHash)))
.withHeader("x-api-key", equalTo(bungieConfiguration.getKey()))
.willReturn(aResponse()
.withStatus(200)
.withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.withBodyFile("bungie/raid-activity-type-response.json")));
var milestoneDefinition = ManifestEntity.MILESTONE_DEFINITION.getId();
var milestoneHash = "2712317338";
stubFor(get(urlPathEqualTo(
"/bungie/Destiny2/Manifest/%s/%s/".formatted(milestoneDefinition, milestoneHash)))
.withHeader("x-api-key", equalTo(bungieConfiguration.getKey()))
.willReturn(aResponse()
.withStatus(200)
.withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.withBodyFile("bungie/raid-milestone-response.json")));
// when: the request is sent
var response = webTestClient.post()
.uri("/interactions")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.header("X-Signature-Ed25519", signature)
.header("X-Signature-Timestamp", timestamp)
.body(BodyInserters.fromValue(body))
.exchange();
// then: the response JSON is correct
response.expectStatus()
.isOk()
.expectBody()
.jsonPath("$.type").isEqualTo(4)
.jsonPath("$.data.content").isEqualTo(
"""
This week's raid is: Garden of Salvation.
You have until %s to complete it before the next raid comes along.
""".formatted(MessageUtil.formatDate(MessageUtil.NEXT_TUESDAY.toLocalDate())));
}
@Test
@DisplayName("get weekly raid fails if no milestones are found")
public void getWeeklyRaidsShouldThrowErrors() throws JsonProcessingException, DecoderException {
// given: a weekly_raid interaction with a valid signature
InteractionData weeklyRaidData = new InteractionData(2, "weekly_raid", 1);
Interaction body = new Interaction(1, "theApplicationId", 2, weeklyRaidData, null);
String timestamp = String.valueOf(Instant.now().getEpochSecond());
String signature = createValidSignature(body, timestamp);
stubFor(get(urlPathEqualTo("/bungie/Destiny2/Milestones/"))
.withHeader("x-api-key", equalTo(bungieConfiguration.getKey()))
.willReturn(aResponse()
.withStatus(400)
.withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.withBodyFile("bungie/missing-api-key.json")));
// when: the request is sent
var response = webTestClient.post()
.uri("/interactions")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.header("X-Signature-Ed25519", signature)
.header("X-Signature-Timestamp", timestamp)
.body(BodyInserters.fromValue(body))
.exchange();
// then: the response JSON is correct
String errorJson;
try {
errorJson = objectMapper.writeValueAsString(
objectMapper.readValue(
new ClassPathResource("__files/bungie/missing-api-key.json").getInputStream(),
Object.class));
} catch (IOException e) {
throw new RuntimeException(e);
}
response.expectStatus()
.isBadRequest()
.expectBody()
.jsonPath("$.detail").value(json -> assertJsonLenient(errorJson, json))
.jsonPath("$.status").isEqualTo(HttpStatus.BAD_REQUEST.value());
}
@Test
@DisplayName("Interactions fail if the signature is invalid")
public void getWeeklyRaidInvalidSignature() throws JsonProcessingException, DecoderException {
// given: an interaction with an invalid signature
InteractionData data = new InteractionData(2, "weekly_raid", 1);
Interaction body = new Interaction(1, "theApplicationId", 2, data, null);
String timestamp = String.valueOf(Instant.now().getEpochSecond());
String signature = createInvalidSignature(body, timestamp);
// when: the request is sent
var response = webTestClient.post()
.uri("/interactions")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.header("X-Signature-Ed25519", signature)
.header("X-Signature-Timestamp", timestamp)
.body(BodyInserters.fromValue(body))
.exchange();
// then: the response JSON has the correct error message
response.expectStatus()
.isBadRequest()
.expectBody()
.jsonPath("$.status").isEqualTo(HttpStatus.BAD_REQUEST.value())
.jsonPath("$.detail").isEqualTo("interactions.request: Signature is invalid");
}
@Test
@DisplayName("PING interactions with valid signatures are ack'd correctly")
public void pingRequestsAreAckdCorrectly() throws JsonProcessingException, DecoderException {
// given: an interaction with an invalid signature
Interaction body = new Interaction(1, "theApplicationId", 1, null, null);
String timestamp = String.valueOf(Instant.now().getEpochSecond());
String signature = createValidSignature(body, timestamp);
// when: the request is sent
var response = webTestClient.post()
.uri("/interactions")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.header("X-Signature-Ed25519", signature)
.header("X-Signature-Timestamp", timestamp)
.body(BodyInserters.fromValue(body))
.exchange();
// then: the response JSON has the correct error message
response.expectStatus()
.isOk()
.expectBody()
.jsonPath("$.type").isEqualTo(InteractionType.PING.getType());
}
@Test
@DisplayName("PING interactions with invalid signatures are not ack'd")
public void invalidPingRequestsAreNotAckd() throws JsonProcessingException, DecoderException {
// given: an interaction with an invalid signature
Interaction body = new Interaction(1, "theApplicationId", 1, null, null);
String timestamp = String.valueOf(Instant.now().getEpochSecond());
String signature = createInvalidSignature(body, timestamp);
// when: the request is sent
var response = webTestClient.post()
.uri("/interactions")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.header("X-Signature-Ed25519", signature)
.header("X-Signature-Timestamp", timestamp)
.body(BodyInserters.fromValue(body))
.exchange();
// then: the response JSON has the correct error message
response.expectStatus()
.isBadRequest()
.expectBody()
.jsonPath("$.status").isEqualTo(HttpStatus.BAD_REQUEST.value())
.jsonPath("$.detail").isEqualTo("interactions.request: Signature is invalid");
}
@Test
@DisplayName("Autocomplete requests for raid stats returns the user's characters successfully")
public void autocompleteRequestsForRaidStats() throws DecoderException, JsonProcessingException {
// given: a valid autocomplete request
String username = "deahtstroke";
String discordId = "123456";
| DiscordUser user = new DiscordUser(discordId, username); | 5 | 2023-10-20 05:53:03+00:00 | 8k |
MinecraftForge/ModLauncher | ml-test/src/test/java/net/minecraftforge/modlauncher/test/ClassTransformerTests.java | [
{
"identifier": "ITransformationService",
"path": "src/main/java/cpw/mods/modlauncher/api/ITransformationService.java",
"snippet": "public interface ITransformationService {\n /**\n * The name of this mod service. It will be used throughout the system. It should be lower case,\n * the first c... | import cpw.mods.modlauncher.*;
import cpw.mods.modlauncher.api.ITransformationService;
import cpw.mods.modlauncher.api.ITransformer;
import cpw.mods.modlauncher.api.ITransformerVotingContext;
import cpw.mods.modlauncher.api.TransformerVoteResult;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.MarkerManager;
import org.apache.logging.log4j.core.config.Configurator;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.powermock.reflect.Whitebox;
import java.util.Collections;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*; | 4,234 | /*
* Copyright (c) Forge Development LLC
* SPDX-License-Identifier: LGPL-3.0-only
*/
package net.minecraftforge.modlauncher.test;
/**
* Test core transformer functionality
*/
class ClassTransformerTests {
@Test
void testClassTransformer() throws Exception {
MarkerManager.getMarker("CLASSDUMP");
Configurator.setLevel(ClassTransformer.class.getName(), Level.TRACE);
UnsafeHacksUtil.hackPowermock();
final TransformStore transformStore = new TransformStore();
final ModuleLayerHandler layerHandler = Whitebox.invokeConstructor(ModuleLayerHandler.class);
final LaunchPluginHandler lph = new LaunchPluginHandler(layerHandler);
final ClassTransformer classTransformer = Whitebox.invokeConstructor(ClassTransformer.class, new Class[] { transformStore.getClass(), lph.getClass(), TransformingClassLoader.class }, new Object[] { transformStore, lph, null});
final ITransformationService dummyService = new MockTransformerService();
Whitebox.invokeMethod(transformStore, "addTransformer", new TransformTargetLabel("test.MyClass", TransformTargetLabel.LabelType.CLASS), classTransformer(), dummyService);
byte[] result = Whitebox.invokeMethod(classTransformer, "transform", new Class[]{byte[].class, String.class,String.class}, new byte[0], "test.MyClass","testing");
assertAll("Class loads and is valid",
() -> assertNotNull(result),
// () -> assertNotNull(new TransformingClassLoader(transformStore, lph, FileSystems.getDefault().getPath(".")).getClass("test.MyClass", result)),
() ->
{
ClassReader cr = new ClassReader(result);
ClassNode cn = new ClassNode();
cr.accept(cn, 0);
assertTrue(cn.fields.stream().anyMatch(f -> f.name.equals("testfield")));
}
);
ClassNode dummyClass = new ClassNode();
dummyClass.superName = "java/lang/Object";
dummyClass.version = 52;
dummyClass.name = "test/DummyClass";
dummyClass.fields.add(new FieldNode(Opcodes.ACC_PUBLIC, "dummyfield", "Ljava/lang/String;", null, null));
ClassWriter cw = new ClassWriter(Opcodes.ASM5);
dummyClass.accept(cw);
Whitebox.invokeMethod(transformStore, "addTransformer", new TransformTargetLabel("test.DummyClass", "dummyfield"), fieldNodeTransformer1(), dummyService);
byte[] result1 = Whitebox.invokeMethod(classTransformer, "transform", new Class[]{byte[].class, String.class, String.class}, cw.toByteArray(), "test.DummyClass", "testing");
assertAll("Class loads and is valid",
() -> assertNotNull(result1),
// () -> assertNotNull(new TransformingClassLoader(transformStore, lph, FileSystems.getDefault().getPath(".")).getClass("test.DummyClass", result1)),
() ->
{
ClassReader cr = new ClassReader(result1);
ClassNode cn = new ClassNode();
cr.accept(cn, 0);
assertEquals("CHEESE", cn.fields.get(0).value);
}
);
}
private ITransformer<FieldNode> fieldNodeTransformer1() {
return new ITransformer<>() {
@NotNull
@Override
public FieldNode transform(FieldNode input, ITransformerVotingContext context) {
input.value = "CHEESE";
return input;
}
@NotNull
@Override | /*
* Copyright (c) Forge Development LLC
* SPDX-License-Identifier: LGPL-3.0-only
*/
package net.minecraftforge.modlauncher.test;
/**
* Test core transformer functionality
*/
class ClassTransformerTests {
@Test
void testClassTransformer() throws Exception {
MarkerManager.getMarker("CLASSDUMP");
Configurator.setLevel(ClassTransformer.class.getName(), Level.TRACE);
UnsafeHacksUtil.hackPowermock();
final TransformStore transformStore = new TransformStore();
final ModuleLayerHandler layerHandler = Whitebox.invokeConstructor(ModuleLayerHandler.class);
final LaunchPluginHandler lph = new LaunchPluginHandler(layerHandler);
final ClassTransformer classTransformer = Whitebox.invokeConstructor(ClassTransformer.class, new Class[] { transformStore.getClass(), lph.getClass(), TransformingClassLoader.class }, new Object[] { transformStore, lph, null});
final ITransformationService dummyService = new MockTransformerService();
Whitebox.invokeMethod(transformStore, "addTransformer", new TransformTargetLabel("test.MyClass", TransformTargetLabel.LabelType.CLASS), classTransformer(), dummyService);
byte[] result = Whitebox.invokeMethod(classTransformer, "transform", new Class[]{byte[].class, String.class,String.class}, new byte[0], "test.MyClass","testing");
assertAll("Class loads and is valid",
() -> assertNotNull(result),
// () -> assertNotNull(new TransformingClassLoader(transformStore, lph, FileSystems.getDefault().getPath(".")).getClass("test.MyClass", result)),
() ->
{
ClassReader cr = new ClassReader(result);
ClassNode cn = new ClassNode();
cr.accept(cn, 0);
assertTrue(cn.fields.stream().anyMatch(f -> f.name.equals("testfield")));
}
);
ClassNode dummyClass = new ClassNode();
dummyClass.superName = "java/lang/Object";
dummyClass.version = 52;
dummyClass.name = "test/DummyClass";
dummyClass.fields.add(new FieldNode(Opcodes.ACC_PUBLIC, "dummyfield", "Ljava/lang/String;", null, null));
ClassWriter cw = new ClassWriter(Opcodes.ASM5);
dummyClass.accept(cw);
Whitebox.invokeMethod(transformStore, "addTransformer", new TransformTargetLabel("test.DummyClass", "dummyfield"), fieldNodeTransformer1(), dummyService);
byte[] result1 = Whitebox.invokeMethod(classTransformer, "transform", new Class[]{byte[].class, String.class, String.class}, cw.toByteArray(), "test.DummyClass", "testing");
assertAll("Class loads and is valid",
() -> assertNotNull(result1),
// () -> assertNotNull(new TransformingClassLoader(transformStore, lph, FileSystems.getDefault().getPath(".")).getClass("test.DummyClass", result1)),
() ->
{
ClassReader cr = new ClassReader(result1);
ClassNode cn = new ClassNode();
cr.accept(cn, 0);
assertEquals("CHEESE", cn.fields.get(0).value);
}
);
}
private ITransformer<FieldNode> fieldNodeTransformer1() {
return new ITransformer<>() {
@NotNull
@Override
public FieldNode transform(FieldNode input, ITransformerVotingContext context) {
input.value = "CHEESE";
return input;
}
@NotNull
@Override | public TransformerVoteResult castVote(ITransformerVotingContext context) { | 3 | 2023-10-18 17:56:01+00:00 | 8k |
Kyrotechnic/KyroClient | Client/src/main/java/me/kyroclient/managers/WindowManager.java | [
{
"identifier": "Module",
"path": "Client/src/main/java/me/kyroclient/modules/Module.java",
"snippet": "public class Module {\n @Expose\n @SerializedName(\"name\")\n public String name;\n @Expose\n @SerializedName(\"toggled\")\n private boolean toggled;\n @Expose\n @SerializedNam... | import java.util.ArrayList;
import java.util.List;
import me.kyroclient.modules.Module;
import me.kyroclient.ui.modern.windows.Window;
import me.kyroclient.ui.modern.windows.impl.HomeWindow;
import me.kyroclient.ui.modern.windows.impl.ModuleWindow;
import me.kyroclient.ui.modern.windows.impl.ThemeWindow; | 4,719 | package me.kyroclient.managers;
public class WindowManager {
public List<Window> windows = new ArrayList<Window>();
public WindowManager() { | package me.kyroclient.managers;
public class WindowManager {
public List<Window> windows = new ArrayList<Window>();
public WindowManager() { | this.windows.add(new HomeWindow()); | 2 | 2023-10-15 16:24:51+00:00 | 8k |
AstroDev2023/2023-studio-1-but-better | source/core/src/test/com/csse3200/game/missions/quests/AutoQuestTest.java | [
{
"identifier": "MissionManager",
"path": "source/core/src/main/com/csse3200/game/missions/MissionManager.java",
"snippet": "public class MissionManager implements Json.Serializable {\n\n\t/**\n\t * An enum storing all possible events that the {@link MissionManager}'s {@link EventHandler} should listen ... | import com.badlogic.gdx.utils.JsonValue;
import com.csse3200.game.missions.MissionManager;
import com.csse3200.game.missions.rewards.Reward;
import com.csse3200.game.services.GameTime;
import com.csse3200.game.services.ServiceLocator;
import com.csse3200.game.services.TimeService;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*; | 7,110 | package com.csse3200.game.missions.quests;
class AutoQuestTest {
private AutoQuest autoQuest1, autoQuest2, autoQuest3;
private Reward r1, r2, r3;
private boolean areQuestsRegistered = false;
@BeforeEach
public void init() {
ServiceLocator.registerTimeSource(new GameTime()); | package com.csse3200.game.missions.quests;
class AutoQuestTest {
private AutoQuest autoQuest1, autoQuest2, autoQuest3;
private Reward r1, r2, r3;
private boolean areQuestsRegistered = false;
@BeforeEach
public void init() {
ServiceLocator.registerTimeSource(new GameTime()); | ServiceLocator.registerTimeService(new TimeService()); | 4 | 2023-10-17 22:34:04+00:00 | 8k |
moeinfatehi/PassiveDigger | src/PassiveDigger/Passive_Headers.java | [
{
"identifier": "BurpExtender",
"path": "src/burp/BurpExtender.java",
"snippet": "public class BurpExtender extends JPanel implements IBurpExtender\r\n{\r\n \r\n public static IBurpExtenderCallbacks callbacks;\r\n static JScrollPane frame;\r\n public static PrintWriter output;\r\n public ... | import burp.BurpExtender;
import burp.IHttpRequestResponse;
import burp.IRequestInfo;
import burp.IResponseInfo;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter; | 4,751 | }
});
jScrollPane6.setViewportView(securityHeadersTable);
if (securityHeadersTable.getColumnModel().getColumnCount() > 0) {
securityHeadersTable.getColumnModel().getColumn(0).setPreferredWidth(150);
securityHeadersTable.getColumnModel().getColumn(0).setMaxWidth(180);
securityHeadersTable.getColumnModel().getColumn(1).setPreferredWidth(60);
securityHeadersTable.getColumnModel().getColumn(1).setMaxWidth(80);
securityHeadersTable.getColumnModel().getColumn(2).setPreferredWidth(200);
}
javax.swing.GroupLayout SecurityHeadersPanelLayout = new javax.swing.GroupLayout(SecurityHeadersPanel);
SecurityHeadersPanel.setLayout(SecurityHeadersPanelLayout);
SecurityHeadersPanelLayout.setHorizontalGroup(
SecurityHeadersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(SecurityHeadersPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(SecurityHeadersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(SecurityHeadersPanelLayout.createSequentialGroup()
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 265, Short.MAX_VALUE)
.addComponent(updateSecurityHeadersButton))
.addComponent(jScrollPane4)
.addGroup(SecurityHeadersPanelLayout.createSequentialGroup()
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jScrollPane6))
.addContainerGap())
);
SecurityHeadersPanelLayout.setVerticalGroup(
SecurityHeadersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(SecurityHeadersPanelLayout.createSequentialGroup()
.addGroup(SecurityHeadersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(updateSecurityHeadersButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(10, 10, 10)
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 179, Short.MAX_VALUE))
);
HeadersTabs.addTab("Security Headers", SecurityHeadersPanel);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(HeadersTabs)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(HeadersTabs)
);
}// </editor-fold>//GEN-END:initComponents
private void securityHeadersTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_securityHeadersTableMouseClicked
if(evt.getClickCount()==2){
int index=securityHeadersTable.getSelectedRow();
if(securityHeaderReqRespList[index]!=null){
reqRespForm.setReqResp(securityHeaderReqRespList[index]);
reqRespForm jf=new reqRespForm();
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
jf.tabs.setSelectedIndex(1);
jf.setVisible(true);
}
}
else{
setDescription(getDescription((String) securityHeadersTable.getValueAt(securityHeadersTable.getSelectedRow(), 0)));
}
}//GEN-LAST:event_securityHeadersTableMouseClicked
private void updateSecurityHeadersButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateSecurityHeadersButtonActionPerformed
for (int i = 0; i < securityHeadersTable.getRowCount(); i++) {
if(!(boolean)securityHeadersTable.getValueAt(i, 1)){
for (int j = 0; j < HeadersTable.getRowCount(); j++) {
if(HeadersTable.getValueAt(j, 1).equals(securityHeadersTable.getValueAt(i, 0))){
DefaultTableModel model=(DefaultTableModel)securityHeadersTable.getModel();
model.setValueAt(true, i, 1);
model.setValueAt(HeadersTable.getValueAt(j, 2), i, 2);
securityHeaderReqRespList[i]=headersReqRespList.get(j);
break;
}
}
}
}
}//GEN-LAST:event_updateSecurityHeadersButtonActionPerformed
private void tableExceptionButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tableExceptionButtonActionPerformed
int[]rows=HeadersTable.getSelectedRows();
for(int i=rows.length-1;i>=0;i--){
String parameter=HeadersTable.getValueAt(rows[i], 3).toString();
addToExceptions(parameter);
}
removeExceptions();
}//GEN-LAST:event_tableExceptionButtonActionPerformed
private void removeRowButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeRowButtonActionPerformed
int[]rows=HeadersTable.getSelectedRows();
for(int i=rows.length-1;i>=0;i--){
int thisInd=HeadersTable.convertRowIndexToModel(rows[i]); //to delete correctly in a sorted table
removeHeadersTableRow(thisInd);
}
}//GEN-LAST:event_removeRowButtonActionPerformed
private void exceptionRemoveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exceptionRemoveButtonActionPerformed
removeExceptions();
}//GEN-LAST:event_exceptionRemoveButtonActionPerformed
private void exceptionFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exceptionFieldActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_exceptionFieldActionPerformed
private void HeadersTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_HeadersTableMouseClicked
if(evt.getClickCount()==2){
int ind=HeadersTable.getSelectedRow();
int index=(int)HeadersTable.getValueAt(ind, 0)-1; | package PassiveDigger;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author "Moein Fatehi moein.fatehi@gmail.com"
*/
public class Passive_Headers extends javax.swing.JPanel {
private static Scanner sc;
private static List<IHttpRequestResponse> headersReqRespList=new ArrayList<>();
private static IHttpRequestResponse [] securityHeaderReqRespList= new IHttpRequestResponse [6];
/**
* Creates new form HeadersPanel
*/
public Passive_Headers() {
initComponents();
initialize();
}
public static List<IHttpRequestResponse> getHeadersReqRespList(){
return headersReqRespList;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
HeadersTabs = new javax.swing.JTabbedPane();
HeadersPanel = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
HeadersTable = new javax.swing.JTable();
jLabel3 = new javax.swing.JLabel();
exceptionField = new javax.swing.JTextField();
exceptionRemoveButton = new javax.swing.JButton();
removeRowButton = new javax.swing.JButton();
tableExceptionButton = new javax.swing.JButton();
SecurityHeadersPanel = new javax.swing.JPanel();
jLabel6 = new javax.swing.JLabel();
updateSecurityHeadersButton = new javax.swing.JButton();
jScrollPane4 = new javax.swing.JScrollPane();
DescriptionField = new javax.swing.JTextArea();
jLabel7 = new javax.swing.JLabel();
jScrollPane6 = new javax.swing.JScrollPane();
securityHeadersTable = new javax.swing.JTable();
HeadersTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"#", "Host", "Port", "Header", "Value"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, true, false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
HeadersTable.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
HeadersTableMouseClicked(evt);
}
});
jScrollPane1.setViewportView(HeadersTable);
if (HeadersTable.getColumnModel().getColumnCount() > 0) {
HeadersTable.getColumnModel().getColumn(0).setPreferredWidth(45);
HeadersTable.getColumnModel().getColumn(0).setMaxWidth(100);
HeadersTable.getColumnModel().getColumn(1).setPreferredWidth(120);
HeadersTable.getColumnModel().getColumn(1).setMaxWidth(200);
HeadersTable.getColumnModel().getColumn(2).setPreferredWidth(60);
HeadersTable.getColumnModel().getColumn(2).setMaxWidth(85);
HeadersTable.getColumnModel().getColumn(3).setPreferredWidth(200);
HeadersTable.getColumnModel().getColumn(3).setMaxWidth(300);
}
jLabel3.setText("Exceptions");
exceptionField.setText("Date,Content-Length,Set-Cookie,Content-Type,Connection,Last-Modified,CF-RAY,Expires,ETag,Location,Vary");
exceptionField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exceptionFieldActionPerformed(evt);
}
});
exceptionRemoveButton.setText("Remove");
exceptionRemoveButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exceptionRemoveButtonActionPerformed(evt);
}
});
removeRowButton.setText("Remove");
removeRowButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeRowButtonActionPerformed(evt);
}
});
tableExceptionButton.setText("Exception");
tableExceptionButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tableExceptionButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout HeadersPanelLayout = new javax.swing.GroupLayout(HeadersPanel);
HeadersPanel.setLayout(HeadersPanelLayout);
HeadersPanelLayout.setHorizontalGroup(
HeadersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(HeadersPanelLayout.createSequentialGroup()
.addGroup(HeadersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(HeadersPanelLayout.createSequentialGroup()
.addGroup(HeadersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(tableExceptionButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(removeRowButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
.addGroup(HeadersPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel3)
.addGap(1, 1, 1)
.addComponent(exceptionField, javax.swing.GroupLayout.DEFAULT_SIZE, 379, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(exceptionRemoveButton)))
.addContainerGap())
);
HeadersPanelLayout.setVerticalGroup(
HeadersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, HeadersPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(HeadersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(exceptionField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(exceptionRemoveButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(HeadersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(HeadersPanelLayout.createSequentialGroup()
.addComponent(removeRowButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tableExceptionButton)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 392, Short.MAX_VALUE))
.addContainerGap())
);
HeadersTabs.addTab("Headers", HeadersPanel);
jLabel6.setFont(new java.awt.Font("Ubuntu", 1, 12)); // NOI18N
jLabel6.setForeground(new java.awt.Color(255, 150, 0));
jLabel6.setText("Security Headers");
updateSecurityHeadersButton.setText("Update From History");
updateSecurityHeadersButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
updateSecurityHeadersButtonActionPerformed(evt);
}
});
DescriptionField.setColumns(20);
DescriptionField.setRows(5);
jScrollPane4.setViewportView(DescriptionField);
jLabel7.setFont(new java.awt.Font("Ubuntu", 1, 12)); // NOI18N
jLabel7.setForeground(new java.awt.Color(255, 150, 0));
jLabel7.setText("Description");
securityHeadersTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{"X-XSS-Protection", null, null},
{"X-Frame-Options", null, null},
{"Content-Security-Policy", null, null},
{"X-Content-Type-Options", null, null},
{"Referrer-Policy", null, null},
{"Strict-Transport-Security", null, null}
},
new String [] {
"Header", "Status", "Value"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.Boolean.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
securityHeadersTable.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
securityHeadersTableMouseClicked(evt);
}
});
securityHeadersTable.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
securityHeadersTableKeyPressed(evt);
}
public void keyReleased(java.awt.event.KeyEvent evt) {
securityHeadersTableKeyReleased(evt);
}
});
jScrollPane6.setViewportView(securityHeadersTable);
if (securityHeadersTable.getColumnModel().getColumnCount() > 0) {
securityHeadersTable.getColumnModel().getColumn(0).setPreferredWidth(150);
securityHeadersTable.getColumnModel().getColumn(0).setMaxWidth(180);
securityHeadersTable.getColumnModel().getColumn(1).setPreferredWidth(60);
securityHeadersTable.getColumnModel().getColumn(1).setMaxWidth(80);
securityHeadersTable.getColumnModel().getColumn(2).setPreferredWidth(200);
}
javax.swing.GroupLayout SecurityHeadersPanelLayout = new javax.swing.GroupLayout(SecurityHeadersPanel);
SecurityHeadersPanel.setLayout(SecurityHeadersPanelLayout);
SecurityHeadersPanelLayout.setHorizontalGroup(
SecurityHeadersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(SecurityHeadersPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(SecurityHeadersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(SecurityHeadersPanelLayout.createSequentialGroup()
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 265, Short.MAX_VALUE)
.addComponent(updateSecurityHeadersButton))
.addComponent(jScrollPane4)
.addGroup(SecurityHeadersPanelLayout.createSequentialGroup()
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jScrollPane6))
.addContainerGap())
);
SecurityHeadersPanelLayout.setVerticalGroup(
SecurityHeadersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(SecurityHeadersPanelLayout.createSequentialGroup()
.addGroup(SecurityHeadersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(updateSecurityHeadersButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(10, 10, 10)
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 179, Short.MAX_VALUE))
);
HeadersTabs.addTab("Security Headers", SecurityHeadersPanel);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(HeadersTabs)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(HeadersTabs)
);
}// </editor-fold>//GEN-END:initComponents
private void securityHeadersTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_securityHeadersTableMouseClicked
if(evt.getClickCount()==2){
int index=securityHeadersTable.getSelectedRow();
if(securityHeaderReqRespList[index]!=null){
reqRespForm.setReqResp(securityHeaderReqRespList[index]);
reqRespForm jf=new reqRespForm();
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
jf.tabs.setSelectedIndex(1);
jf.setVisible(true);
}
}
else{
setDescription(getDescription((String) securityHeadersTable.getValueAt(securityHeadersTable.getSelectedRow(), 0)));
}
}//GEN-LAST:event_securityHeadersTableMouseClicked
private void updateSecurityHeadersButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateSecurityHeadersButtonActionPerformed
for (int i = 0; i < securityHeadersTable.getRowCount(); i++) {
if(!(boolean)securityHeadersTable.getValueAt(i, 1)){
for (int j = 0; j < HeadersTable.getRowCount(); j++) {
if(HeadersTable.getValueAt(j, 1).equals(securityHeadersTable.getValueAt(i, 0))){
DefaultTableModel model=(DefaultTableModel)securityHeadersTable.getModel();
model.setValueAt(true, i, 1);
model.setValueAt(HeadersTable.getValueAt(j, 2), i, 2);
securityHeaderReqRespList[i]=headersReqRespList.get(j);
break;
}
}
}
}
}//GEN-LAST:event_updateSecurityHeadersButtonActionPerformed
private void tableExceptionButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tableExceptionButtonActionPerformed
int[]rows=HeadersTable.getSelectedRows();
for(int i=rows.length-1;i>=0;i--){
String parameter=HeadersTable.getValueAt(rows[i], 3).toString();
addToExceptions(parameter);
}
removeExceptions();
}//GEN-LAST:event_tableExceptionButtonActionPerformed
private void removeRowButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeRowButtonActionPerformed
int[]rows=HeadersTable.getSelectedRows();
for(int i=rows.length-1;i>=0;i--){
int thisInd=HeadersTable.convertRowIndexToModel(rows[i]); //to delete correctly in a sorted table
removeHeadersTableRow(thisInd);
}
}//GEN-LAST:event_removeRowButtonActionPerformed
private void exceptionRemoveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exceptionRemoveButtonActionPerformed
removeExceptions();
}//GEN-LAST:event_exceptionRemoveButtonActionPerformed
private void exceptionFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exceptionFieldActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_exceptionFieldActionPerformed
private void HeadersTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_HeadersTableMouseClicked
if(evt.getClickCount()==2){
int ind=HeadersTable.getSelectedRow();
int index=(int)HeadersTable.getValueAt(ind, 0)-1; | BurpExtender.output.println("table size: "+HeadersTable.getRowCount()); | 0 | 2023-10-23 12:13:00+00:00 | 8k |
LuckPerms/rest-api-java-client | src/main/java/net/luckperms/rest/service/UserService.java | [
{
"identifier": "CreateUserRequest",
"path": "src/main/java/net/luckperms/rest/model/CreateUserRequest.java",
"snippet": "public class CreateUserRequest extends AbstractModel {\n private final UUID uniqueId;\n private final String username;\n\n public CreateUserRequest(UUID uniqueId, String use... | import net.luckperms.rest.model.CreateUserRequest;
import net.luckperms.rest.model.DemotionResult;
import net.luckperms.rest.model.Metadata;
import net.luckperms.rest.model.Node;
import net.luckperms.rest.model.NodeType;
import net.luckperms.rest.model.PermissionCheckRequest;
import net.luckperms.rest.model.PermissionCheckResult;
import net.luckperms.rest.model.PlayerSaveResult;
import net.luckperms.rest.model.PromotionResult;
import net.luckperms.rest.model.TemporaryNodeMergeStrategy;
import net.luckperms.rest.model.TrackRequest;
import net.luckperms.rest.model.UpdateUserRequest;
import net.luckperms.rest.model.User;
import net.luckperms.rest.model.UserLookupResult;
import net.luckperms.rest.model.UserSearchResult;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.HTTP;
import retrofit2.http.PATCH;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import retrofit2.http.Query;
import java.util.List;
import java.util.Set;
import java.util.UUID; | 3,845 | /*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.luckperms.rest.service;
public interface UserService {
@GET("/user")
Call<Set<UUID>> list();
@POST("/user")
Call<PlayerSaveResult> create(@Body CreateUserRequest req);
@GET("/user/lookup")
Call<UserLookupResult> lookup(@Query("username") String username);
@GET("/user/lookup")
Call<UserLookupResult> lookup(@Query("uniqueId") UUID uniqueId);
@GET("/user/search")
Call<List<UserSearchResult>> searchNodesByKey(@Query("key") String key);
@GET("/user/search")
Call<List<UserSearchResult>> searchNodesByKeyStartsWith(@Query("keyStartsWith") String keyStartsWith);
@GET("/user/search")
Call<List<UserSearchResult>> searchNodesByMetaKey(@Query("metaKey") String metaKey);
@GET("/user/search")
Call<List<UserSearchResult>> searchNodesByType(@Query("type") NodeType type);
@GET("/user/{uniqueId}")
Call<User> get(@Path("uniqueId") UUID uniqueId);
@PATCH("/user/{uniqueId}")
Call<Void> update(@Path("uniqueId") UUID uniqueId, @Body UpdateUserRequest req);
@DELETE("/user/{uniqueId}")
Call<Void> delete(@Path("uniqueId") UUID uniqueId);
@GET("/user/{uniqueId}/nodes")
Call<List<Node>> nodes(@Path("uniqueId") UUID uniqueId);
@POST("/user/{uniqueId}/nodes")
Call<List<Node>> nodesAdd(@Path("uniqueId") UUID uniqueId, @Body Node node);
@POST("/user/{uniqueId}/nodes")
Call<List<Node>> nodesAdd(@Path("uniqueId") UUID uniqueId, @Body Node node, @Query("temporaryNodeMergeStrategy") TemporaryNodeMergeStrategy temporaryNodeMergeStrategy);
@PATCH("/user/{uniqueId}/nodes")
Call<List<Node>> nodesAdd(@Path("uniqueId") UUID uniqueId, @Body List<Node> nodes);
@PATCH("/user/{uniqueId}/nodes")
Call<List<Node>> nodesAdd(@Path("uniqueId") UUID uniqueId, @Body List<Node> nodes, @Query("temporaryNodeMergeStrategy") TemporaryNodeMergeStrategy temporaryNodeMergeStrategy);
@PUT("/user/{uniqueId}/nodes")
Call<Void> nodesSet(@Path("uniqueId") UUID uniqueId, @Body List<Node> nodes);
@DELETE("/user/{uniqueId}/nodes")
Call<Void> nodesDelete(@Path("uniqueId") UUID uniqueId);
@HTTP(method = "DELETE", path = "/user/{uniqueId}/nodes", hasBody = true)
Call<Void> nodesDelete(@Path("uniqueId") UUID uniqueId, @Body List<Node> nodes);
@GET("/user/{uniqueId}/meta")
Call<Metadata> metadata(@Path("uniqueId") UUID uniqueId);
@GET("/user/{uniqueId}/permissionCheck")
Call<PermissionCheckResult> permissionCheck(@Path("uniqueId") UUID uniqueId, @Query("permission") String permission);
@POST("/user/{uniqueId}/permissionCheck")
Call<PermissionCheckResult> permissionCheck(@Path("uniqueId") UUID uniqueId, @Body PermissionCheckRequest req);
@POST("/user/{uniqueId}/promote") | /*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.luckperms.rest.service;
public interface UserService {
@GET("/user")
Call<Set<UUID>> list();
@POST("/user")
Call<PlayerSaveResult> create(@Body CreateUserRequest req);
@GET("/user/lookup")
Call<UserLookupResult> lookup(@Query("username") String username);
@GET("/user/lookup")
Call<UserLookupResult> lookup(@Query("uniqueId") UUID uniqueId);
@GET("/user/search")
Call<List<UserSearchResult>> searchNodesByKey(@Query("key") String key);
@GET("/user/search")
Call<List<UserSearchResult>> searchNodesByKeyStartsWith(@Query("keyStartsWith") String keyStartsWith);
@GET("/user/search")
Call<List<UserSearchResult>> searchNodesByMetaKey(@Query("metaKey") String metaKey);
@GET("/user/search")
Call<List<UserSearchResult>> searchNodesByType(@Query("type") NodeType type);
@GET("/user/{uniqueId}")
Call<User> get(@Path("uniqueId") UUID uniqueId);
@PATCH("/user/{uniqueId}")
Call<Void> update(@Path("uniqueId") UUID uniqueId, @Body UpdateUserRequest req);
@DELETE("/user/{uniqueId}")
Call<Void> delete(@Path("uniqueId") UUID uniqueId);
@GET("/user/{uniqueId}/nodes")
Call<List<Node>> nodes(@Path("uniqueId") UUID uniqueId);
@POST("/user/{uniqueId}/nodes")
Call<List<Node>> nodesAdd(@Path("uniqueId") UUID uniqueId, @Body Node node);
@POST("/user/{uniqueId}/nodes")
Call<List<Node>> nodesAdd(@Path("uniqueId") UUID uniqueId, @Body Node node, @Query("temporaryNodeMergeStrategy") TemporaryNodeMergeStrategy temporaryNodeMergeStrategy);
@PATCH("/user/{uniqueId}/nodes")
Call<List<Node>> nodesAdd(@Path("uniqueId") UUID uniqueId, @Body List<Node> nodes);
@PATCH("/user/{uniqueId}/nodes")
Call<List<Node>> nodesAdd(@Path("uniqueId") UUID uniqueId, @Body List<Node> nodes, @Query("temporaryNodeMergeStrategy") TemporaryNodeMergeStrategy temporaryNodeMergeStrategy);
@PUT("/user/{uniqueId}/nodes")
Call<Void> nodesSet(@Path("uniqueId") UUID uniqueId, @Body List<Node> nodes);
@DELETE("/user/{uniqueId}/nodes")
Call<Void> nodesDelete(@Path("uniqueId") UUID uniqueId);
@HTTP(method = "DELETE", path = "/user/{uniqueId}/nodes", hasBody = true)
Call<Void> nodesDelete(@Path("uniqueId") UUID uniqueId, @Body List<Node> nodes);
@GET("/user/{uniqueId}/meta")
Call<Metadata> metadata(@Path("uniqueId") UUID uniqueId);
@GET("/user/{uniqueId}/permissionCheck")
Call<PermissionCheckResult> permissionCheck(@Path("uniqueId") UUID uniqueId, @Query("permission") String permission);
@POST("/user/{uniqueId}/permissionCheck")
Call<PermissionCheckResult> permissionCheck(@Path("uniqueId") UUID uniqueId, @Body PermissionCheckRequest req);
@POST("/user/{uniqueId}/promote") | Call<PromotionResult> promote(@Path("uniqueId") UUID uniqueId, @Body TrackRequest req); | 8 | 2023-10-22 16:07:30+00:00 | 8k |
EvanAatrox/hubbo | hubbo-config/src/main/java/cn/hubbo/configuration/security/SpringSecurityConfig.java | [
{
"identifier": "JWTProperties",
"path": "hubbo-common/src/main/java/cn/hubbo/common/domain/to/properties/JWTProperties.java",
"snippet": "@Component\n@ConfigurationProperties(prefix = \"token\")\n@Data\npublic class JWTProperties {\n\n\n Map<String, Object> header = new HashMap<>();\n\n\n /* 类型 *... | import cn.hubbo.common.domain.to.properties.JWTProperties;
import cn.hubbo.security.filter.AccessDecisionManagerImpl;
import cn.hubbo.security.filter.CustomFilterInvocationSecurityMetadataSource;
import cn.hubbo.security.filter.DynamicFilter;
import cn.hubbo.security.filter.FormAndJsonLoginFilter;
import cn.hubbo.security.filter.JwtTokenFilter;
import cn.hubbo.security.handler.AccessDeniedHandlerImpl;
import cn.hubbo.security.handler.AuthenticationEntryPointImpl;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.filter.OncePerRequestFilter;
import java.util.List; | 4,705 | package cn.hubbo.configuration.security;
/**
* @author 张晓华
* @version V1.0
* @Package cn.hubbo.configuration.security
* @date 2023/10/20 23:51
* @Copyright © 2023-2025 版权所有,未经授权均为剽窃,作者保留一切权利
*/
@Configuration
@AllArgsConstructor
public class SpringSecurityConfig {
private UserDetailsService userDetailsService;
private AuthenticationConfiguration authenticationConfiguration;
private RedisTemplate<String, Object> redisTemplate;
private JWTProperties jwtProperties;
/**
* @return 密码加密工具
*/
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
/**
* @return 用户信息校验的工具
*/
@Bean
public AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(userDetailsService);
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
return daoAuthenticationProvider;
}
@Bean
public AuthenticationManager authenticationManager() throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
List<String> ignorePathPatterns = List.of("/test/**", "/user/login");
httpSecurity.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.NEVER))
.passwordManagement(AbstractHttpConfigurer::disable)
.anonymous(AbstractHttpConfigurer::disable)
.rememberMe(AbstractHttpConfigurer::disable)
.headers(AbstractHttpConfigurer::disable)
.authenticationManager(authenticationManager())
.httpBasic(Customizer.withDefaults())
.authorizeHttpRequests(authorization -> authorization.requestMatchers(ignorePathPatterns.toArray(new String[]{}))
.permitAll()
.anyRequest()
.authenticated())
.authenticationProvider(authenticationProvider())
.exceptionHandling(web -> web
.accessDeniedHandler(accessDeniedHandler())
.authenticationEntryPoint(authenticationEntryPoint()))
//.addFilterBefore(dynamicFilter(), FilterSecurityInterceptor.class)
.addFilterBefore(oncePerRequestFilter(), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(loginFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class);
return httpSecurity.build();
}
/**
* @return 放行的资源
*/
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
List<String> ignorePathPatterns = List.of("/test/**", "/user/login");
return web -> web.ignoring().requestMatchers(ignorePathPatterns.toArray(new String[]{}));
}
@Bean
public FormAndJsonLoginFilter loginFilter(AuthenticationManager authenticationManager) {
FormAndJsonLoginFilter loginFilter = new FormAndJsonLoginFilter(authenticationManager, redisTemplate, jwtProperties);
loginFilter.setPostOnly(true);
loginFilter.setFilterProcessesUrl("/user/login");
loginFilter.setAuthenticationManager(authenticationManager);
loginFilter.setAllowSessionCreation(false);
return loginFilter;
}
@Bean
public AccessDeniedHandler accessDeniedHandler() { | package cn.hubbo.configuration.security;
/**
* @author 张晓华
* @version V1.0
* @Package cn.hubbo.configuration.security
* @date 2023/10/20 23:51
* @Copyright © 2023-2025 版权所有,未经授权均为剽窃,作者保留一切权利
*/
@Configuration
@AllArgsConstructor
public class SpringSecurityConfig {
private UserDetailsService userDetailsService;
private AuthenticationConfiguration authenticationConfiguration;
private RedisTemplate<String, Object> redisTemplate;
private JWTProperties jwtProperties;
/**
* @return 密码加密工具
*/
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
/**
* @return 用户信息校验的工具
*/
@Bean
public AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(userDetailsService);
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
return daoAuthenticationProvider;
}
@Bean
public AuthenticationManager authenticationManager() throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
List<String> ignorePathPatterns = List.of("/test/**", "/user/login");
httpSecurity.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.NEVER))
.passwordManagement(AbstractHttpConfigurer::disable)
.anonymous(AbstractHttpConfigurer::disable)
.rememberMe(AbstractHttpConfigurer::disable)
.headers(AbstractHttpConfigurer::disable)
.authenticationManager(authenticationManager())
.httpBasic(Customizer.withDefaults())
.authorizeHttpRequests(authorization -> authorization.requestMatchers(ignorePathPatterns.toArray(new String[]{}))
.permitAll()
.anyRequest()
.authenticated())
.authenticationProvider(authenticationProvider())
.exceptionHandling(web -> web
.accessDeniedHandler(accessDeniedHandler())
.authenticationEntryPoint(authenticationEntryPoint()))
//.addFilterBefore(dynamicFilter(), FilterSecurityInterceptor.class)
.addFilterBefore(oncePerRequestFilter(), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(loginFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class);
return httpSecurity.build();
}
/**
* @return 放行的资源
*/
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
List<String> ignorePathPatterns = List.of("/test/**", "/user/login");
return web -> web.ignoring().requestMatchers(ignorePathPatterns.toArray(new String[]{}));
}
@Bean
public FormAndJsonLoginFilter loginFilter(AuthenticationManager authenticationManager) {
FormAndJsonLoginFilter loginFilter = new FormAndJsonLoginFilter(authenticationManager, redisTemplate, jwtProperties);
loginFilter.setPostOnly(true);
loginFilter.setFilterProcessesUrl("/user/login");
loginFilter.setAuthenticationManager(authenticationManager);
loginFilter.setAllowSessionCreation(false);
return loginFilter;
}
@Bean
public AccessDeniedHandler accessDeniedHandler() { | return new AccessDeniedHandlerImpl(); | 6 | 2023-10-18 09:38:29+00:00 | 8k |
RoessinghResearch/senseeact | SenSeeActService/src/main/java/nl/rrd/senseeact/service/controller/AccessController.java | [
{
"identifier": "ProjectDataModule",
"path": "SenSeeActClient/src/main/java/nl/rrd/senseeact/client/model/ProjectDataModule.java",
"snippet": "@JsonIgnoreProperties(ignoreUnknown=true)\npublic class ProjectDataModule extends JsonObject {\n\tprivate String name;\n\tprivate List<String> tables = new Array... | import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import nl.rrd.senseeact.client.model.ProjectDataModule;
import nl.rrd.senseeact.client.model.ProjectUserAccessRule;
import nl.rrd.senseeact.service.QueryRunner;
import nl.rrd.senseeact.service.exception.HttpException;
import nl.rrd.senseeact.service.model.PermissionRecord;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map; | 5,569 | package nl.rrd.senseeact.service.controller;
@RestController
@RequestMapping("/v{version}/access")
public class AccessController {
private static final Object WRITE_LOCK = new Object();
private AccessControllerExecution exec = new AccessControllerExecution();
@RequestMapping(value="/project/{project}/modules",
method=RequestMethod.GET)
public List<ProjectDataModule> getModuleList(
HttpServletRequest request,
HttpServletResponse response,
@PathVariable("version")
@Parameter(hidden = true)
String versionName,
@PathVariable("project")
String project) throws HttpException, Exception {
return QueryRunner.runProjectQuery(
(version, authDb, projectDb, user, srvProject) ->
exec.getModuleList(project),
versionName, project, request, response);
}
@RequestMapping(value="/project/{project}/grantee/list",
method=RequestMethod.GET) | package nl.rrd.senseeact.service.controller;
@RestController
@RequestMapping("/v{version}/access")
public class AccessController {
private static final Object WRITE_LOCK = new Object();
private AccessControllerExecution exec = new AccessControllerExecution();
@RequestMapping(value="/project/{project}/modules",
method=RequestMethod.GET)
public List<ProjectDataModule> getModuleList(
HttpServletRequest request,
HttpServletResponse response,
@PathVariable("version")
@Parameter(hidden = true)
String versionName,
@PathVariable("project")
String project) throws HttpException, Exception {
return QueryRunner.runProjectQuery(
(version, authDb, projectDb, user, srvProject) ->
exec.getModuleList(project),
versionName, project, request, response);
}
@RequestMapping(value="/project/{project}/grantee/list",
method=RequestMethod.GET) | public List<ProjectUserAccessRule> getGranteeList( | 1 | 2023-10-24 09:36:50+00:00 | 8k |
Spectrum3847/SpectrumTraining | src/main/java/frc/robot/auton/Auton.java | [
{
"identifier": "Robot",
"path": "src/main/java/frc/robot/Robot.java",
"snippet": "public class Robot extends LoggedRobot {\n public static RobotConfig config;\n public static RobotTelemetry telemetry;\n\n /** Create a single static instance of all of your subsystems */\n public static Train... | import com.pathplanner.lib.auto.AutoBuilder;
import com.pathplanner.lib.auto.NamedCommands;
import com.pathplanner.lib.commands.PathPlannerAuto;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj2.command.Command;
import edu.wpi.first.wpilibj2.command.PrintCommand;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import frc.robot.Robot;
import frc.robot.RobotTelemetry;
import frc.robot.auton.commands.AutoBalance;
import frc.robot.auton.config.AutonConfig;
import frc.robot.swerve.commands.ApplyChassisSpeeds; | 4,776 | package frc.robot.auton;
public class Auton extends SubsystemBase {
public static final SendableChooser<Command> autonChooser = new SendableChooser<>();
private static boolean autoMessagePrinted = true;
private static double autonStart = 0;
// A chooser for autonomous commands
public static void setupSelectors() {
autonChooser.setDefaultOption("Clean Side 3", new PathPlannerAuto("Clean Side 3"));
// autonChooser.addOption("Clean3", AutoPaths.CleanSide());
}
// Setup the named commands
public static void setupNamedCommands() {
// Register Named Commands
NamedCommands.registerCommand("autoBalance", new AutoBalance());
}
// Subsystem Documentation:
// https://docs.wpilib.org/en/stable/docs/software/commandbased/subsystems.html
public Auton() {
configureAutoBuilder(); // configures the auto builder
setupNamedCommands(); // registers named commands
setupSelectors(); // runs the command to start the chooser for auto on shuffleboard
RobotTelemetry.print("Auton Subsystem Initialized: ");
}
// Configures the auto builder to use to run autons
public static void configureAutoBuilder() {
// Configure the AutoBuilder last
AutoBuilder.configureHolonomic(
Robot.swerve::getPose, // Robot pose supplier
Robot.swerve
::resetPose, // Method to reset odometry (will be called if your auto has a
// starting pose)
Robot.swerve
::getRobotRelativeSpeeds, // ChassisSpeeds supplier. MUST BE ROBOT RELATIVE | package frc.robot.auton;
public class Auton extends SubsystemBase {
public static final SendableChooser<Command> autonChooser = new SendableChooser<>();
private static boolean autoMessagePrinted = true;
private static double autonStart = 0;
// A chooser for autonomous commands
public static void setupSelectors() {
autonChooser.setDefaultOption("Clean Side 3", new PathPlannerAuto("Clean Side 3"));
// autonChooser.addOption("Clean3", AutoPaths.CleanSide());
}
// Setup the named commands
public static void setupNamedCommands() {
// Register Named Commands
NamedCommands.registerCommand("autoBalance", new AutoBalance());
}
// Subsystem Documentation:
// https://docs.wpilib.org/en/stable/docs/software/commandbased/subsystems.html
public Auton() {
configureAutoBuilder(); // configures the auto builder
setupNamedCommands(); // registers named commands
setupSelectors(); // runs the command to start the chooser for auto on shuffleboard
RobotTelemetry.print("Auton Subsystem Initialized: ");
}
// Configures the auto builder to use to run autons
public static void configureAutoBuilder() {
// Configure the AutoBuilder last
AutoBuilder.configureHolonomic(
Robot.swerve::getPose, // Robot pose supplier
Robot.swerve
::resetPose, // Method to reset odometry (will be called if your auto has a
// starting pose)
Robot.swerve
::getRobotRelativeSpeeds, // ChassisSpeeds supplier. MUST BE ROBOT RELATIVE | ApplyChassisSpeeds.robotRelativeOutput( | 4 | 2023-10-23 17:01:53+00:00 | 8k |
imart302/DulceNectar-BE | src/main/java/com/dulcenectar/java/services/OrderServiceImpl.java | [
{
"identifier": "CreateOrderRequestDto",
"path": "src/main/java/com/dulcenectar/java/dtos/order/CreateOrderRequestDto.java",
"snippet": "public class CreateOrderRequestDto implements RequestDto<Order> {\n\t\n\n\tpublic static class OrderItem {\n\t\tprivate Integer productId;\n\t\tprivate Integer quantit... | import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import com.dulcenectar.java.dtos.order.CreateOrderRequestDto;
import com.dulcenectar.java.dtos.order.GetOrderResponseDto;
import com.dulcenectar.java.exceptions.OrderNotFoundException;
import com.dulcenectar.java.models.Order;
import com.dulcenectar.java.models.OrderProducts;
import com.dulcenectar.java.models.Product;
import com.dulcenectar.java.repositories.OrderProductsRepository;
import com.dulcenectar.java.repositories.OrderRepository;
import com.dulcenectar.java.security.UserDetailsImpl;
import com.dulcenectar.java.services.interfaces.OrderService; | 4,640 | package com.dulcenectar.java.services;
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
private OrderRepository orderRepository;
private final OrderProductsRepository orderProductsRepository;
public OrderServiceImpl(OrderRepository orderRepository, OrderProductsRepository orderProductsRepository) {
super();
this.orderRepository = orderRepository;
this.orderProductsRepository = orderProductsRepository;
}
public Integer createNewOrder(CreateOrderRequestDto order) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UserDetailsImpl user = (UserDetailsImpl)authentication.getPrincipal();
List<CreateOrderRequestDto.OrderItem> orderItems = order.getOrderItems();
Order orderEntity = new Order();
orderEntity.setUser(user);
orderEntity.setAddress(order.getAddress());
orderEntity.setTotalGross(order.getTotalGross());
Order savedOrder = this.orderRepository.save(orderEntity);
List<OrderProducts> orderProductList = orderItems.stream().map((item) -> {
OrderProducts op = new OrderProducts();
op.setOrder(savedOrder);
op.setQuantity(item.getQuantity());
op.setProduct(new Product(item.getProductId()));
op.setId(new OrderProducts.OrderProductId(savedOrder.getId(), item.getProductId()));
return op;
}).toList();
this.orderProductsRepository.saveAll(orderProductList);
return savedOrder.getId();
}
| package com.dulcenectar.java.services;
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
private OrderRepository orderRepository;
private final OrderProductsRepository orderProductsRepository;
public OrderServiceImpl(OrderRepository orderRepository, OrderProductsRepository orderProductsRepository) {
super();
this.orderRepository = orderRepository;
this.orderProductsRepository = orderProductsRepository;
}
public Integer createNewOrder(CreateOrderRequestDto order) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UserDetailsImpl user = (UserDetailsImpl)authentication.getPrincipal();
List<CreateOrderRequestDto.OrderItem> orderItems = order.getOrderItems();
Order orderEntity = new Order();
orderEntity.setUser(user);
orderEntity.setAddress(order.getAddress());
orderEntity.setTotalGross(order.getTotalGross());
Order savedOrder = this.orderRepository.save(orderEntity);
List<OrderProducts> orderProductList = orderItems.stream().map((item) -> {
OrderProducts op = new OrderProducts();
op.setOrder(savedOrder);
op.setQuantity(item.getQuantity());
op.setProduct(new Product(item.getProductId()));
op.setId(new OrderProducts.OrderProductId(savedOrder.getId(), item.getProductId()));
return op;
}).toList();
this.orderProductsRepository.saveAll(orderProductList);
return savedOrder.getId();
}
| public List<GetOrderResponseDto> getOrders() { | 1 | 2023-10-24 00:07:39+00:00 | 8k |
DaveScott99/ToyStore-JSP | src/main/java/br/com/toyStore/servlet/Servlet.java | [
{
"identifier": "CategoryDAO",
"path": "src/main/java/br/com/toyStore/dao/CategoryDAO.java",
"snippet": "public class CategoryDAO {\n\tprivate Connection conn;\n\tprivate PreparedStatement ps;\n\tprivate ResultSet rs;\n\tprivate Category category;\n\n\tpublic CategoryDAO(Connection conn) {\n\t\tthis.con... | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import br.com.toyStore.dao.CategoryDAO;
import br.com.toyStore.dao.ProductDAO;
import br.com.toyStore.dao.UserDAO;
import br.com.toyStore.exception.DbException;
import br.com.toyStore.model.Category;
import br.com.toyStore.model.Product;
import br.com.toyStore.model.User;
import br.com.toyStore.util.ConnectionFactory; | 6,008 | package br.com.toyStore.servlet;
@WebServlet(urlPatterns = { "/Servlet", "/home", "/catalog", "/categories",
"/selectProduct", "/selectCategory", "/insertProduct", "/insertCategory", "/login", "/admin",
"/updateProduct", "/selectProductUpdate", "/deleteProduct", "/newProduct"})
@MultipartConfig(
fileSizeThreshold = 1024 * 1024 * 1, // 1 MB
maxFileSize = 1024 * 1024 * 10, // 10 MB
maxRequestSize = 1024 * 1024 * 100 // 100 MB
)
public class Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
ProductDAO productDao = new ProductDAO(ConnectionFactory.getConnection());
CategoryDAO categoryDao = new CategoryDAO(ConnectionFactory.getConnection()); | package br.com.toyStore.servlet;
@WebServlet(urlPatterns = { "/Servlet", "/home", "/catalog", "/categories",
"/selectProduct", "/selectCategory", "/insertProduct", "/insertCategory", "/login", "/admin",
"/updateProduct", "/selectProductUpdate", "/deleteProduct", "/newProduct"})
@MultipartConfig(
fileSizeThreshold = 1024 * 1024 * 1, // 1 MB
maxFileSize = 1024 * 1024 * 10, // 10 MB
maxRequestSize = 1024 * 1024 * 100 // 100 MB
)
public class Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
ProductDAO productDao = new ProductDAO(ConnectionFactory.getConnection());
CategoryDAO categoryDao = new CategoryDAO(ConnectionFactory.getConnection()); | UserDAO userDao = new UserDAO(ConnectionFactory.getConnection()); | 2 | 2023-10-20 02:51:14+00:00 | 8k |
MYSTD/BigDataApiTest | data-governance-assessment/src/main/java/com/std/dga/governance/service/impl/GovernanceAssessDetailServiceImpl.java | [
{
"identifier": "Assessor",
"path": "data-governance-assessment/src/main/java/com/std/dga/assessor/Assessor.java",
"snippet": "public abstract class Assessor {\n\n public final GovernanceAssessDetail doAssessor(AssessParam assessParam){\n\n// System.out.println(\"Assessor 管理流程\");\n Gov... | import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.std.dga.assessor.Assessor;
import com.std.dga.dolphinscheduler.bean.TDsTaskDefinition;
import com.std.dga.dolphinscheduler.bean.TDsTaskInstance;
import com.std.dga.dolphinscheduler.service.TDsTaskDefinitionService;
import com.std.dga.dolphinscheduler.service.TDsTaskInstanceService;
import com.std.dga.governance.bean.AssessParam;
import com.std.dga.governance.bean.GovernanceAssessDetail;
import com.std.dga.governance.bean.GovernanceAssessDetailVO;
import com.std.dga.governance.bean.GovernanceMetric;
import com.std.dga.governance.mapper.GovernanceAssessDetailMapper;
import com.std.dga.governance.service.GovernanceAssessDetailService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.std.dga.governance.service.GovernanceMetricService;
import com.std.dga.meta.bean.TableMetaInfo;
import com.std.dga.meta.mapper.TableMetaInfoMapper;
import com.std.dga.util.SpringBeanProvider;
import com.sun.codemodel.internal.JForEach;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors; | 5,212 | package com.std.dga.governance.service.impl;
/**
* <p>
* 治理考评结果明细 服务实现类
* </p>
*
* @author std
* @since 2023-10-10
*/
@Service
@DS("dga") | package com.std.dga.governance.service.impl;
/**
* <p>
* 治理考评结果明细 服务实现类
* </p>
*
* @author std
* @since 2023-10-10
*/
@Service
@DS("dga") | public class GovernanceAssessDetailServiceImpl extends ServiceImpl<GovernanceAssessDetailMapper, GovernanceAssessDetail> implements GovernanceAssessDetailService { | 9 | 2023-10-20 10:13:43+00:00 | 8k |
RaulGB88/MOD-034-Microservicios-con-Java | REM20231023/demo/src/main/java/com/example/application/resources/ActorResource.java | [
{
"identifier": "ActorService",
"path": "REM20231023/catalogo/src/main/java/com/example/domains/contracts/services/ActorService.java",
"snippet": "public interface ActorService extends ProjectionDomainService<Actor, Integer> {\n\tList<Actor> novedades(Timestamp fecha);\n}"
},
{
"identifier": "Fi... | import java.net.URI;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.example.domains.contracts.services.ActorService;
import com.example.domains.entities.Film;
import com.example.domains.entities.FilmActor;
import com.example.domains.entities.dtos.ActorDTO;
import com.example.domains.entities.dtos.ActorShort;
import com.example.exceptions.BadRequestException;
import com.example.exceptions.DuplicateKeyException;
import com.example.exceptions.InvalidDataException;
import com.example.exceptions.NotFoundException;
import jakarta.validation.Valid; | 5,421 | package com.example.application.resources;
@RestController
@RequestMapping("/api/actores/v1")
public class ActorResource {
@Autowired
private ActorService srv;
@GetMapping
public List<ActorShort> getAll() {
return srv.getByProjection(ActorShort.class);
}
@GetMapping(params = "page")
public Page<ActorDTO> getAll(Pageable page) {
return srv.getByProjection(page, ActorDTO.class);
}
@GetMapping(path = "/{id}")
public ActorDTO getOne(@PathVariable int id) throws NotFoundException {
var item = srv.getOne(id);
if(item.isEmpty())
throw new NotFoundException();
return ActorDTO.from(item.get());
}
record Peli(int id, String titulo) {}
@GetMapping(path = "/{id}/pelis")
public List<Peli> getPelis(@PathVariable int id) throws NotFoundException {
var item = srv.getOne(id);
if(item.isEmpty())
throw new NotFoundException();
return item.get().getFilmActors().stream()
.map(f->new Peli(f.getFilm().getFilmId(), f.getFilm().getTitle()))
.toList();
}
@PutMapping(path = "/{id}/jubilacion")
@ResponseStatus(HttpStatus.ACCEPTED)
public void jubilate(@PathVariable int id) throws NotFoundException {
var item = srv.getOne(id);
if(item.isEmpty())
throw new NotFoundException();
item.get().jubilate();
}
@PostMapping
public ResponseEntity<Object> create(@Valid @RequestBody ActorDTO item) throws DuplicateKeyException, InvalidDataException {
var newItem = srv.add(ActorDTO.from(item));
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
.buildAndExpand(newItem.getActorId()).toUri();
return ResponseEntity.created(location).build();
}
@PutMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT) | package com.example.application.resources;
@RestController
@RequestMapping("/api/actores/v1")
public class ActorResource {
@Autowired
private ActorService srv;
@GetMapping
public List<ActorShort> getAll() {
return srv.getByProjection(ActorShort.class);
}
@GetMapping(params = "page")
public Page<ActorDTO> getAll(Pageable page) {
return srv.getByProjection(page, ActorDTO.class);
}
@GetMapping(path = "/{id}")
public ActorDTO getOne(@PathVariable int id) throws NotFoundException {
var item = srv.getOne(id);
if(item.isEmpty())
throw new NotFoundException();
return ActorDTO.from(item.get());
}
record Peli(int id, String titulo) {}
@GetMapping(path = "/{id}/pelis")
public List<Peli> getPelis(@PathVariable int id) throws NotFoundException {
var item = srv.getOne(id);
if(item.isEmpty())
throw new NotFoundException();
return item.get().getFilmActors().stream()
.map(f->new Peli(f.getFilm().getFilmId(), f.getFilm().getTitle()))
.toList();
}
@PutMapping(path = "/{id}/jubilacion")
@ResponseStatus(HttpStatus.ACCEPTED)
public void jubilate(@PathVariable int id) throws NotFoundException {
var item = srv.getOne(id);
if(item.isEmpty())
throw new NotFoundException();
item.get().jubilate();
}
@PostMapping
public ResponseEntity<Object> create(@Valid @RequestBody ActorDTO item) throws DuplicateKeyException, InvalidDataException {
var newItem = srv.add(ActorDTO.from(item));
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
.buildAndExpand(newItem.getActorId()).toUri();
return ResponseEntity.created(location).build();
}
@PutMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT) | public void update(@PathVariable int id, @Valid @RequestBody ActorDTO item) throws BadRequestException, NotFoundException, InvalidDataException { | 5 | 2023-10-24 14:35:15+00:00 | 8k |
Amir-UL-Islam/eTBManager3-Backend | src/main/java/org/msh/etbm/services/cases/filters/impl/SummaryFilter.java | [
{
"identifier": "Item",
"path": "src/main/java/org/msh/etbm/commons/Item.java",
"snippet": "public class Item<E> implements IsItem<E>, Displayable {\n\n private E id;\n private String name;\n\n /**\n * Default constructor\n */\n public Item() {\n super();\n }\n\n /**\n ... | import org.msh.etbm.commons.Item;
import org.msh.etbm.commons.Messages;
import org.msh.etbm.commons.filters.Filter;
import org.msh.etbm.commons.filters.FilterException;
import org.msh.etbm.commons.sqlquery.QueryDefs;
import org.msh.etbm.services.cases.filters.CaseFilters;
import org.msh.etbm.services.cases.summary.SummaryItem;
import org.msh.etbm.services.cases.summary.SummaryService;
import org.springframework.context.ApplicationContext;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors; | 6,072 | package org.msh.etbm.services.cases.filters.impl;
/**
* Implementation of a {@link Filter} for an specific item of the case summary
*
* Created by rmemoria on 21/9/16.
*/
public class SummaryFilter extends AbstractFilter {
private SummaryService summaryService;
private CaseFilters filters;
public SummaryFilter() {
super("summary", "${global.summary}");
}
@Override
public void initialize(ApplicationContext context) {
super.initialize(context);
summaryService = context.getBean(SummaryService.class);
filters = context.getBean(CaseFilters.class);
}
@Override
public void prepareFilterQuery(QueryDefs def, Object value, Map<String, Object> params) {
if (value == null) {
return;
}
String summaryId = value.toString();
| package org.msh.etbm.services.cases.filters.impl;
/**
* Implementation of a {@link Filter} for an specific item of the case summary
*
* Created by rmemoria on 21/9/16.
*/
public class SummaryFilter extends AbstractFilter {
private SummaryService summaryService;
private CaseFilters filters;
public SummaryFilter() {
super("summary", "${global.summary}");
}
@Override
public void initialize(ApplicationContext context) {
super.initialize(context);
summaryService = context.getBean(SummaryService.class);
filters = context.getBean(CaseFilters.class);
}
@Override
public void prepareFilterQuery(QueryDefs def, Object value, Map<String, Object> params) {
if (value == null) {
return;
}
String summaryId = value.toString();
| Optional<SummaryItem> res = summaryService.getItems().stream() | 6 | 2023-10-23 13:47:54+00:00 | 8k |
exagonsoft/drones-management-board-backend | src/test/java/exagonsoft/drones/service/DroneServiceTest.java | [
{
"identifier": "BatteryLevelDto",
"path": "src/main/java/exagonsoft/drones/dto/BatteryLevelDto.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class BatteryLevelDto {\n private int batteryLevel;\n}"
},
{
"identifier": "DroneDto",
"path": "src/main/jav... | import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.boot.test.context.SpringBootTest;
import exagonsoft.drones.dto.BatteryLevelDto;
import exagonsoft.drones.dto.DroneDto;
import exagonsoft.drones.dto.MedicationDto;
import exagonsoft.drones.entity.Drone;
import exagonsoft.drones.mock.MockData;
import exagonsoft.drones.repository.DroneRepository;
import exagonsoft.drones.service.impl.DroneServiceImpl;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*; | 3,611 | package exagonsoft.drones.service;
@SpringBootTest
public class DroneServiceTest {
@InjectMocks
private DroneServiceImpl droneService;
@Mock
private DroneRepository droneRepository;
@Mock
private DroneMedicationService droneMedicationService;
@Mock
private MedicationService medicationService;
@Test
public void testCreateDrone() {
// Arrange
DroneDto droneDto = MockData.mockDroneDto();
Drone savedDrone = MockData.mockDrone();
when(droneRepository.save(any(Drone.class))).thenReturn(savedDrone);
// Act
DroneDto createdDrone = droneService.createDrone(droneDto);
// Assert
assertNotNull(createdDrone);
assertEquals(savedDrone.getId(), createdDrone.getId());
}
@Test
public void testGetDroneByID() {
// Arrange
Long droneId = 1L;
Drone drone = MockData.mockDrone();
when(droneRepository.findById(droneId)).thenReturn(Optional.of(drone));
// Act
DroneDto retrievedDrone = droneService.getDroneByID(droneId);
// Assert
assertNotNull(retrievedDrone);
assertEquals(droneId, retrievedDrone.getId());
}
@Test
public void testListAllDrones() {
// Arrange
List<Drone> drones = Collections.singletonList(MockData.mockDrone());
when(droneRepository.findAll()).thenReturn(drones);
// Act
List<DroneDto> droneDtoList = droneService.listAllDrones();
// Assert
assertNotNull(droneDtoList);
assertEquals(1, droneDtoList.size());
}
@Test
public void testUpdateDrone() {
// Arrange
Long droneId = 1L;
DroneDto updatedDroneDto = MockData.mockUpdatedDroneDto();
Drone existingDrone = MockData.mockDrone();
when(droneRepository.findById(droneId)).thenReturn(Optional.of(existingDrone));
when(droneRepository.save(any(Drone.class))).thenReturn(existingDrone);
// Act
DroneDto updatedDrone = droneService.updateDrone(droneId, updatedDroneDto);
// Assert
assertNotNull(updatedDrone);
assertEquals(updatedDroneDto.getMax_weight(), updatedDrone.getMax_weight());
assertEquals(updatedDroneDto.getModel(), updatedDrone.getModel());
assertEquals(updatedDroneDto.getBattery_capacity(), updatedDrone.getBattery_capacity());
assertEquals(updatedDroneDto.getState(), updatedDrone.getState());
}
@Test
public void testListAvailableDrones() {
// Arrange
List<Drone> availableDrones = Collections.singletonList(MockData.mockDrone());
when(droneRepository.findAvailableDrones()).thenReturn(availableDrones);
// Act
List<DroneDto> availableDroneDtoList = droneService.listAvailableDrones();
// Assert
assertNotNull(availableDroneDtoList);
assertEquals(1, availableDroneDtoList.size());
}
@Test
public void testCheckDroneBatteryLevel() {
// Arrange
Long droneId = 1L;
Drone drone = MockData.mockDrone();
when(droneRepository.findById(droneId)).thenReturn(Optional.of(drone));
// Act | package exagonsoft.drones.service;
@SpringBootTest
public class DroneServiceTest {
@InjectMocks
private DroneServiceImpl droneService;
@Mock
private DroneRepository droneRepository;
@Mock
private DroneMedicationService droneMedicationService;
@Mock
private MedicationService medicationService;
@Test
public void testCreateDrone() {
// Arrange
DroneDto droneDto = MockData.mockDroneDto();
Drone savedDrone = MockData.mockDrone();
when(droneRepository.save(any(Drone.class))).thenReturn(savedDrone);
// Act
DroneDto createdDrone = droneService.createDrone(droneDto);
// Assert
assertNotNull(createdDrone);
assertEquals(savedDrone.getId(), createdDrone.getId());
}
@Test
public void testGetDroneByID() {
// Arrange
Long droneId = 1L;
Drone drone = MockData.mockDrone();
when(droneRepository.findById(droneId)).thenReturn(Optional.of(drone));
// Act
DroneDto retrievedDrone = droneService.getDroneByID(droneId);
// Assert
assertNotNull(retrievedDrone);
assertEquals(droneId, retrievedDrone.getId());
}
@Test
public void testListAllDrones() {
// Arrange
List<Drone> drones = Collections.singletonList(MockData.mockDrone());
when(droneRepository.findAll()).thenReturn(drones);
// Act
List<DroneDto> droneDtoList = droneService.listAllDrones();
// Assert
assertNotNull(droneDtoList);
assertEquals(1, droneDtoList.size());
}
@Test
public void testUpdateDrone() {
// Arrange
Long droneId = 1L;
DroneDto updatedDroneDto = MockData.mockUpdatedDroneDto();
Drone existingDrone = MockData.mockDrone();
when(droneRepository.findById(droneId)).thenReturn(Optional.of(existingDrone));
when(droneRepository.save(any(Drone.class))).thenReturn(existingDrone);
// Act
DroneDto updatedDrone = droneService.updateDrone(droneId, updatedDroneDto);
// Assert
assertNotNull(updatedDrone);
assertEquals(updatedDroneDto.getMax_weight(), updatedDrone.getMax_weight());
assertEquals(updatedDroneDto.getModel(), updatedDrone.getModel());
assertEquals(updatedDroneDto.getBattery_capacity(), updatedDrone.getBattery_capacity());
assertEquals(updatedDroneDto.getState(), updatedDrone.getState());
}
@Test
public void testListAvailableDrones() {
// Arrange
List<Drone> availableDrones = Collections.singletonList(MockData.mockDrone());
when(droneRepository.findAvailableDrones()).thenReturn(availableDrones);
// Act
List<DroneDto> availableDroneDtoList = droneService.listAvailableDrones();
// Assert
assertNotNull(availableDroneDtoList);
assertEquals(1, availableDroneDtoList.size());
}
@Test
public void testCheckDroneBatteryLevel() {
// Arrange
Long droneId = 1L;
Drone drone = MockData.mockDrone();
when(droneRepository.findById(droneId)).thenReturn(Optional.of(drone));
// Act | BatteryLevelDto batteryLevelDto = droneService.checkDroneBatteryLevel(droneId); | 0 | 2023-10-16 08:32:39+00:00 | 8k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.