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 |
|---|---|---|---|---|---|---|---|---|---|---|
Invadermonky/Omniwand | src/main/java/com/invadermonky/omniwand/handlers/TransformHandler.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.init.RegistryOW;
import com.invadermonky.omniwand.network.MessageRevertWand;
import com.invadermonky.omniwand.util.NBTHelper;
import com.invadermonky.omniwand.util.References;
import gnu.trove.map.hash.THashMap;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.event.entity.item.ItemTossEvent;
import net.minecraftforge.event.entity.player.PlayerDestroyItemEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.Locale;
import java.util.Map;
import java.util.function.Consumer; | 3,224 | package com.invadermonky.omniwand.handlers;
public class TransformHandler {
public static final TransformHandler INSTANCE = new TransformHandler();
public static final THashMap<String,String> modNames = new THashMap<>();
public static boolean autoMode = true;
@SubscribeEvent
public void onItemDropped(ItemTossEvent event) {
if(event.getPlayer().isSneaking()) {
EntityItem e = event.getEntityItem();
ItemStack stack = e.getItem();
TransformHandler.removeItemFromWand(e, stack, false, e::setItem);
autoMode = true;
}
}
@SubscribeEvent
public void onItemBroken(PlayerDestroyItemEvent event) {
TransformHandler.removeItemFromWand(event.getEntityPlayer(), event.getOriginal(), true, (transform) -> {
event.getEntityPlayer().setHeldItem(event.getHand(), transform);
autoMode = true;
});
}
@SideOnly(Side.CLIENT)
@SubscribeEvent
public void onPlayerSwing(PlayerInteractEvent.LeftClickEmpty event) {
ItemStack stack = event.getItemStack();
if(!ConfigHandler.crouchRevert || event.getEntityPlayer().isSneaking()) {
if (stack != null && TransformHandler.isOmniwand(stack) && stack.getItem() != RegistryOW.OMNIWAND) { | package com.invadermonky.omniwand.handlers;
public class TransformHandler {
public static final TransformHandler INSTANCE = new TransformHandler();
public static final THashMap<String,String> modNames = new THashMap<>();
public static boolean autoMode = true;
@SubscribeEvent
public void onItemDropped(ItemTossEvent event) {
if(event.getPlayer().isSneaking()) {
EntityItem e = event.getEntityItem();
ItemStack stack = e.getItem();
TransformHandler.removeItemFromWand(e, stack, false, e::setItem);
autoMode = true;
}
}
@SubscribeEvent
public void onItemBroken(PlayerDestroyItemEvent event) {
TransformHandler.removeItemFromWand(event.getEntityPlayer(), event.getOriginal(), true, (transform) -> {
event.getEntityPlayer().setHeldItem(event.getHand(), transform);
autoMode = true;
});
}
@SideOnly(Side.CLIENT)
@SubscribeEvent
public void onPlayerSwing(PlayerInteractEvent.LeftClickEmpty event) {
ItemStack stack = event.getItemStack();
if(!ConfigHandler.crouchRevert || event.getEntityPlayer().isSneaking()) {
if (stack != null && TransformHandler.isOmniwand(stack) && stack.getItem() != RegistryOW.OMNIWAND) { | Omniwand.network.sendToServer(new MessageRevertWand()); | 0 | 2023-10-16 00:48:26+00:00 | 4k |
hmcts/opal-fines-service | src/test/java/uk/gov/hmcts/opal/service/PartyServiceTest.java | [
{
"identifier": "AccountSearchDto",
"path": "src/main/java/uk/gov/hmcts/opal/dto/AccountSearchDto.java",
"snippet": "@Data\n@Builder\npublic class AccountSearchDto implements ToJsonString {\n /** The court (CT) or MET (metropolitan area). */\n private String court;\n /** Defendant Surname, Comp... | 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 uk.gov.hmcts.opal.dto.AccountSearchDto;
import uk.gov.hmcts.opal.dto.PartyDto;
import uk.gov.hmcts.opal.entity.PartyEntity;
import uk.gov.hmcts.opal.entity.PartySummary;
import uk.gov.hmcts.opal.repository.PartyRepository;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collections;
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; | 1,849 | package uk.gov.hmcts.opal.service;
@ExtendWith(MockitoExtension.class)
class PartyServiceTest {
@Mock
private PartyRepository partyRepository;
@InjectMocks
private PartyService partyService;
@Test
void testSaveParty() {
PartyDto partyDto = buildPartyDto();
PartyEntity partyEntity = buildPartyEntity();
when(partyRepository.save(any(PartyEntity.class))).thenReturn(partyEntity);
// Act
PartyDto savedPartyDto = partyService.saveParty(partyDto);
// Assert
assertEquals(partyEntity.getPartyId(), savedPartyDto.getPartyId());
verify(partyRepository, times(1)).save(any(PartyEntity.class));
}
@Test
void testGetParty() {
PartyEntity partyEntity = buildPartyEntity();
when(partyRepository.getReferenceById(any(Long.class))).thenReturn(partyEntity);
// Act
PartyDto savedPartyDto = partyService.getParty(1L);
// Assert
assertEquals(partyEntity.getPartyId(), savedPartyDto.getPartyId());
verify(partyRepository, times(1)).getReferenceById(any(Long.class));
}
@Test
void testSearchForParty() {
List<PartySummary> partyEntity = Collections.<PartySummary>emptyList();
when(partyRepository.findBySurnameContaining(any())).thenReturn(partyEntity);
// Act | package uk.gov.hmcts.opal.service;
@ExtendWith(MockitoExtension.class)
class PartyServiceTest {
@Mock
private PartyRepository partyRepository;
@InjectMocks
private PartyService partyService;
@Test
void testSaveParty() {
PartyDto partyDto = buildPartyDto();
PartyEntity partyEntity = buildPartyEntity();
when(partyRepository.save(any(PartyEntity.class))).thenReturn(partyEntity);
// Act
PartyDto savedPartyDto = partyService.saveParty(partyDto);
// Assert
assertEquals(partyEntity.getPartyId(), savedPartyDto.getPartyId());
verify(partyRepository, times(1)).save(any(PartyEntity.class));
}
@Test
void testGetParty() {
PartyEntity partyEntity = buildPartyEntity();
when(partyRepository.getReferenceById(any(Long.class))).thenReturn(partyEntity);
// Act
PartyDto savedPartyDto = partyService.getParty(1L);
// Assert
assertEquals(partyEntity.getPartyId(), savedPartyDto.getPartyId());
verify(partyRepository, times(1)).getReferenceById(any(Long.class));
}
@Test
void testSearchForParty() {
List<PartySummary> partyEntity = Collections.<PartySummary>emptyList();
when(partyRepository.findBySurnameContaining(any())).thenReturn(partyEntity);
// Act | List<PartySummary> partySummaries = partyService.searchForParty(AccountSearchDto.builder().build()); | 0 | 2023-10-23 14:12:11+00:00 | 4k |
IronRiders/MockSeason23-24 | src/main/java/org/ironriders/commands/RobotCommands.java | [
{
"identifier": "Arm",
"path": "src/main/java/org/ironriders/constants/Arm.java",
"snippet": "public class Arm {\n public static final double LENGTH_FROM_ORIGIN = Units.inchesToMeters(39);\n public static final double TOLERANCE = 1;\n public static final double FAILSAFE_DIFFERENCE = 7;\n pub... | import com.pathplanner.lib.auto.AutoBuilder;
import com.pathplanner.lib.auto.NamedCommands;
import edu.wpi.first.wpilibj2.command.Command;
import edu.wpi.first.wpilibj2.command.Commands;
import org.ironriders.constants.Arm;
import org.ironriders.constants.Manipulator;
import org.ironriders.subsystems.ArmSubsystem;
import org.ironriders.subsystems.DriveSubsystem;
import org.ironriders.subsystems.ManipulatorSubsystem;
import org.ironriders.subsystems.VisionSubsystem;
import java.util.Set;
import static org.ironriders.constants.Game.Field.AprilTagLocation;
import static org.ironriders.constants.Vision.WAIT_TIME; | 3,279 | package org.ironriders.commands;
public class RobotCommands {
private final ArmCommands arm;
private final DriveCommands drive;
private final DriveSubsystem driveSubsystem;
private final VisionSubsystem vision;
private final ManipulatorCommands manipulator;
| package org.ironriders.commands;
public class RobotCommands {
private final ArmCommands arm;
private final DriveCommands drive;
private final DriveSubsystem driveSubsystem;
private final VisionSubsystem vision;
private final ManipulatorCommands manipulator;
| public RobotCommands(ArmSubsystem arm, DriveSubsystem drive, ManipulatorSubsystem manipulator) { | 4 | 2023-10-23 20:31:46+00:00 | 4k |
ChrisGenti/DiscordTickets | src/main/java/com/github/chrisgenti/discordtickets/managers/TicketManager.java | [
{
"identifier": "Ticket",
"path": "src/main/java/com/github/chrisgenti/discordtickets/objects/Ticket.java",
"snippet": "public class Ticket {\n private final int id;\n private final TicketType ticketType;\n private final String userID, channelID;\n private final Date openDate;\n private D... | import com.github.chrisgenti.discordtickets.objects.Ticket;
import com.github.chrisgenti.discordtickets.DiscordTickets;
import com.github.chrisgenti.discordtickets.managers.mongo.MongoManager;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors; | 2,436 | package com.github.chrisgenti.discordtickets.managers;
public class TicketManager {
private int lastNumber;
private final List<Ticket> ticketCache;
public TicketManager(DiscordTickets discord) {
this.ticketCache = new ArrayList<>();
| package com.github.chrisgenti.discordtickets.managers;
public class TicketManager {
private int lastNumber;
private final List<Ticket> ticketCache;
public TicketManager(DiscordTickets discord) {
this.ticketCache = new ArrayList<>();
| MongoManager mongoManager = discord.getMongoManager(); | 2 | 2023-10-23 13:24:05+00:00 | 4k |
moonstoneid/aero-cast | apps/feed-aggregator/src/main/java/com/moonstoneid/aerocast/aggregator/controller/SSEController.java | [
{
"identifier": "Subscriber",
"path": "apps/feed-aggregator/src/main/java/com/moonstoneid/aerocast/aggregator/model/Subscriber.java",
"snippet": "@Data\n@Entity\n@Table(name = \"subscriber\")\npublic class Subscriber implements Serializable {\n\n @Id\n @Column(name = \"account_address\", length = ... | import com.moonstoneid.aerocast.aggregator.model.Subscriber;
import com.moonstoneid.aerocast.aggregator.service.SubscriberService;
import com.moonstoneid.aerocast.aggregator.service.SSEService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; | 2,510 | package com.moonstoneid.aerocast.aggregator.controller;
/**
* Implements a controller for Server Sent Events (SSE). This allows a client-side EventSource to
* establish a persistent connection through which updates can be sent.
*/
@RestController
@RequestMapping(path = "/sse")
public class SSEController {
| package com.moonstoneid.aerocast.aggregator.controller;
/**
* Implements a controller for Server Sent Events (SSE). This allows a client-side EventSource to
* establish a persistent connection through which updates can be sent.
*/
@RestController
@RequestMapping(path = "/sse")
public class SSEController {
| private final SSEService sseService; | 2 | 2023-10-23 20:33:07+00:00 | 4k |
UnityFoundation-io/Libre311 | app/src/main/java/app/service/service/ServiceService.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.model.service.Service;
import app.model.service.ServiceRepository;
import app.service.storage.StorageService;
import io.micronaut.data.model.Page;
import io.micronaut.data.model.Pageable;
import io.micronaut.http.HttpResponse;
import jakarta.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
import java.util.Optional; | 2,082 | // 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.service.service;
@Singleton
public class ServiceService {
private static final Logger LOG = LoggerFactory.getLogger(ServiceService.class);
private final ServiceRepository serviceRepository;
public ServiceService(ServiceRepository serviceRepository) {
this.serviceRepository = serviceRepository;
}
public Page<ServiceDTO> findAll(Pageable pageable, String jurisdictionId) { | // 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.service.service;
@Singleton
public class ServiceService {
private static final Logger LOG = LoggerFactory.getLogger(ServiceService.class);
private final ServiceRepository serviceRepository;
public ServiceService(ServiceRepository serviceRepository) {
this.serviceRepository = serviceRepository;
}
public Page<ServiceDTO> findAll(Pageable pageable, String jurisdictionId) { | Page<Service> servicePage; | 1 | 2023-10-18 15:37:36+00:00 | 4k |
JonnyOnlineYT/xenza | src/minecraft/viamcp/ViaMCP.java | [
{
"identifier": "MCPBackwardsLoader",
"path": "src/minecraft/viamcp/loader/MCPBackwardsLoader.java",
"snippet": "public class MCPBackwardsLoader implements ViaBackwardsPlatform {\n private final File file;\n\n public MCPBackwardsLoader(File file) {\n this.init(this.file = new File(file, \"ViaBa... | import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.viaversion.viaversion.ViaManagerImpl;
import com.viaversion.viaversion.api.Via;
import com.viaversion.viaversion.api.data.MappingDataLoader;
import io.netty.channel.EventLoop;
import io.netty.channel.local.LocalEventLoopGroup;
import java.io.File;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.logging.Logger;
import viamcp.loader.MCPBackwardsLoader;
import viamcp.loader.MCPRewindLoader;
import viamcp.loader.MCPViaLoader;
import viamcp.platform.MCPViaInjector;
import viamcp.platform.MCPViaPlatform;
import viamcp.utils.JLoggerToLog4j; | 2,521 | package viamcp;
public class ViaMCP {
public static final int PROTOCOL_VERSION = 47;
private static final ViaMCP instance = new ViaMCP();
private final Logger jLogger = new JLoggerToLog4j(new net.augustus.utils.Logger());
private final CompletableFuture<Void> INIT_FUTURE = new CompletableFuture<>();
private ExecutorService ASYNC_EXEC;
private EventLoop EVENT_LOOP;
private File file;
private int version;
private String lastServer;
public static ViaMCP getInstance() {
return instance;
}
public void start() {
ThreadFactory factory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat("ViaMCP-%d").build();
this.ASYNC_EXEC = Executors.newFixedThreadPool(8, factory);
this.EVENT_LOOP = new LocalEventLoopGroup(1, factory).next();
this.EVENT_LOOP.submit(this.INIT_FUTURE::join);
this.setVersion(47);
this.file = new File("ViaMCP");
if (this.file.mkdir()) {
this.getjLogger().info("Creating ViaMCP Folder");
}
| package viamcp;
public class ViaMCP {
public static final int PROTOCOL_VERSION = 47;
private static final ViaMCP instance = new ViaMCP();
private final Logger jLogger = new JLoggerToLog4j(new net.augustus.utils.Logger());
private final CompletableFuture<Void> INIT_FUTURE = new CompletableFuture<>();
private ExecutorService ASYNC_EXEC;
private EventLoop EVENT_LOOP;
private File file;
private int version;
private String lastServer;
public static ViaMCP getInstance() {
return instance;
}
public void start() {
ThreadFactory factory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat("ViaMCP-%d").build();
this.ASYNC_EXEC = Executors.newFixedThreadPool(8, factory);
this.EVENT_LOOP = new LocalEventLoopGroup(1, factory).next();
this.EVENT_LOOP.submit(this.INIT_FUTURE::join);
this.setVersion(47);
this.file = new File("ViaMCP");
if (this.file.mkdir()) {
this.getjLogger().info("Creating ViaMCP Folder");
}
| Via.init(ViaManagerImpl.builder().injector(new MCPViaInjector()).loader(new MCPViaLoader()).platform(new MCPViaPlatform(this.file)).build()); | 2 | 2023-10-15 00:21:15+00:00 | 4k |
logicaalternativa/algebraictypes | src/test/java/com/logicaalternativa/algebraictypes/examples/ExampleSerializerDeserializerTest.java | [
{
"identifier": "AlgebraDsl",
"path": "src/main/java/com/logicaalternativa/algebraictypes/dsl/AlgebraDsl.java",
"snippet": "public sealed interface AlgebraDsl extends Serializable {\n \n record Number( int value ) implements AlgebraDsl{} \n \n record Addition( AlgebraDsl sumand1, AlgebraDsl ... | import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.logicaalternativa.algebraictypes.dsl.AlgebraDsl;
import com.logicaalternativa.algebraictypes.dsl.interpreter.AlgebraSerializer;
import com.logicaalternativa.algebraictypes.dsl.interpreter.InterpreterInt;
import com.logicaalternativa.algebraictypes.dsl.json.AlgebraDeserializer;
import com.logicaalternativa.algebraictypes.examples.mother.AlgebraExample; | 1,733 | package com.logicaalternativa.algebraictypes.examples;
public class ExampleSerializerDeserializerTest {
private final Gson gson = initGson();
@Test
@DisplayName("Example of serializer/deserializer data")
void test() {
final Queue<String> messageBroker = new ConcurrentLinkedQueue<>();
simulatePublisher(messageBroker);
final var res = simulateSubscriber(messageBroker);
assertEquals(-45, res);
}
private void simulatePublisher(Queue<String> messageBroker) {
final var myProgramSerialized = AlgebraSerializer.interpreterJson( | package com.logicaalternativa.algebraictypes.examples;
public class ExampleSerializerDeserializerTest {
private final Gson gson = initGson();
@Test
@DisplayName("Example of serializer/deserializer data")
void test() {
final Queue<String> messageBroker = new ConcurrentLinkedQueue<>();
simulatePublisher(messageBroker);
final var res = simulateSubscriber(messageBroker);
assertEquals(-45, res);
}
private void simulatePublisher(Queue<String> messageBroker) {
final var myProgramSerialized = AlgebraSerializer.interpreterJson( | AlgebraExample.EXAMPLE_PROGRAM); | 4 | 2023-10-21 20:03:49+00:00 | 4k |
Radekyspec/TasksMaster | src/main/java/view/schedule/AddNewEventView.java | [
{
"identifier": "ViewManagerModel",
"path": "src/main/java/interface_adapter/ViewManagerModel.java",
"snippet": "public class ViewManagerModel {\n private final PropertyChangeSupport support = new PropertyChangeSupport(this);\n private String activeViewName;\n\n public String getActiveView() {\... | import interface_adapter.ViewManagerModel;
import interface_adapter.schedule.ScheduleViewModel;
import interface_adapter.schedule.event.AddEventController;
import interface_adapter.schedule.event.AddEventState;
import interface_adapter.schedule.event.AddEventViewModel;
import view.JButtonWithFont;
import view.JLabelWithFont;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Objects; | 2,623 | package view.schedule;
public class AddNewEventView extends JPanel implements ActionListener, PropertyChangeListener {
private final ViewManagerModel viewManagerModel;
private final AddEventViewModel addEventViewModel;
private final AddEventController addEventController;
private final ScheduleViewModel scheduleViewModel;
private final JPanel eventNameInfo = new JPanel();
private final JPanel eventNoteInfo = new JPanel();
private final JPanel eventStartInfo = new JPanel();
private final JPanel eventEndInfo = new JPanel();
private final JPanel eventAllDayInfo = new JPanel();
private final JPanel eventUserWithInfo = new JPanel();
private final JTextField eventNameInputField = new JTextField(30);
private final JTextField eventNoteInputField = new JTextField(30);
private final JTextField eventStartInputField = new JTextField(30);
private final JTextField eventEndInputField = new JTextField(30);
private final JTextField eventAllDayInputField = new JTextField(30);
private final JTextField eventUserWithInputField = new JTextField(30);
private final JButton postButton;
public AddNewEventView(ViewManagerModel viewManagerModel, AddEventViewModel addEventViewModel, ScheduleViewModel scheduleViewModel, AddEventController addEventController) {
this.viewManagerModel = viewManagerModel;
this.addEventViewModel = addEventViewModel;
this.addEventController = addEventController;
this.scheduleViewModel = scheduleViewModel;
addEventViewModel.addPropertyChangeListener(this);
eventNameInputField.setFont(new Font("Times New Roman", Font.PLAIN, 26));
eventNoteInputField.setFont(new Font("Times New Roman", Font.PLAIN, 26));
;
eventStartInputField.setFont(new Font("Times New Roman", Font.PLAIN, 26));
eventEndInputField.setFont(new Font("Times New Roman", Font.PLAIN, 26));
eventAllDayInputField.setFont(new Font("Times New Roman", Font.PLAIN, 26));
// eventUserWithInputField.setFont(new Font("Times New Roman", Font.PLAIN, 26));
| package view.schedule;
public class AddNewEventView extends JPanel implements ActionListener, PropertyChangeListener {
private final ViewManagerModel viewManagerModel;
private final AddEventViewModel addEventViewModel;
private final AddEventController addEventController;
private final ScheduleViewModel scheduleViewModel;
private final JPanel eventNameInfo = new JPanel();
private final JPanel eventNoteInfo = new JPanel();
private final JPanel eventStartInfo = new JPanel();
private final JPanel eventEndInfo = new JPanel();
private final JPanel eventAllDayInfo = new JPanel();
private final JPanel eventUserWithInfo = new JPanel();
private final JTextField eventNameInputField = new JTextField(30);
private final JTextField eventNoteInputField = new JTextField(30);
private final JTextField eventStartInputField = new JTextField(30);
private final JTextField eventEndInputField = new JTextField(30);
private final JTextField eventAllDayInputField = new JTextField(30);
private final JTextField eventUserWithInputField = new JTextField(30);
private final JButton postButton;
public AddNewEventView(ViewManagerModel viewManagerModel, AddEventViewModel addEventViewModel, ScheduleViewModel scheduleViewModel, AddEventController addEventController) {
this.viewManagerModel = viewManagerModel;
this.addEventViewModel = addEventViewModel;
this.addEventController = addEventController;
this.scheduleViewModel = scheduleViewModel;
addEventViewModel.addPropertyChangeListener(this);
eventNameInputField.setFont(new Font("Times New Roman", Font.PLAIN, 26));
eventNoteInputField.setFont(new Font("Times New Roman", Font.PLAIN, 26));
;
eventStartInputField.setFont(new Font("Times New Roman", Font.PLAIN, 26));
eventEndInputField.setFont(new Font("Times New Roman", Font.PLAIN, 26));
eventAllDayInputField.setFont(new Font("Times New Roman", Font.PLAIN, 26));
// eventUserWithInputField.setFont(new Font("Times New Roman", Font.PLAIN, 26));
| eventNameInfo.add(new JLabelWithFont(AddEventViewModel.EVENT_NAME)); | 6 | 2023-10-23 15:17:21+00:00 | 4k |
denis-vp/toy-language-interpreter | src/main/java/repository/Repository.java | [
{
"identifier": "IDictionary",
"path": "src/main/java/adt/IDictionary.java",
"snippet": "public interface IDictionary<K, V> {\n void add(K key, V value);\n\n void remove(K key);\n\n V get(K key);\n\n void update(K key, V value);\n\n boolean search(K key);\n\n int size();\n\n boolean... | import adt.IDictionary;
import adt.IHeap;
import exception.ADTException;
import exception.RepositoryException;
import model.ProgramState;
import model.statement.CompoundStatement;
import model.value.Value;
import java.io.*;
import java.util.ArrayList;
import java.util.List; | 1,733 | package repository;
public class Repository implements IRepository {
private final List<ProgramState> programStateList = new ArrayList<ProgramState>();
private final String logFilePath;
public Repository(ProgramState initialProgram, String logFilePath) {
this.programStateList.add(initialProgram);
this.logFilePath = logFilePath;
}
@Override
public List<ProgramState> getProgramStateList() {
return List.copyOf(this.programStateList);
}
@Override
public void setProgramStateList(List<ProgramState> programStateList) {
this.programStateList.clear();
this.programStateList.addAll(programStateList);
}
@Override
public IHeap getHeap() {
return this.programStateList.get(0).getHeap();
}
@Override | package repository;
public class Repository implements IRepository {
private final List<ProgramState> programStateList = new ArrayList<ProgramState>();
private final String logFilePath;
public Repository(ProgramState initialProgram, String logFilePath) {
this.programStateList.add(initialProgram);
this.logFilePath = logFilePath;
}
@Override
public List<ProgramState> getProgramStateList() {
return List.copyOf(this.programStateList);
}
@Override
public void setProgramStateList(List<ProgramState> programStateList) {
this.programStateList.clear();
this.programStateList.addAll(programStateList);
}
@Override
public IHeap getHeap() {
return this.programStateList.get(0).getHeap();
}
@Override | public IDictionary<String, Value> getSymbolTable() { | 6 | 2023-10-21 18:08:59+00:00 | 4k |
PrzemyslawMusial242473/GreenGame | src/main/java/org/io/GreenGame/user/service/implementation/AuthServiceImplementation.java | [
{
"identifier": "SecurityConfig",
"path": "src/main/java/org/io/GreenGame/config/SecurityConfig.java",
"snippet": "@Configuration\n@EnableWebSecurity\npublic class SecurityConfig {\n\n @Autowired\n private UserDetailsService userDetailsService;\n\n @Bean\n public static PasswordEncoder passw... | import org.io.GreenGame.config.SecurityConfig;
import org.io.GreenGame.user.model.GreenGameUser;
import org.io.GreenGame.user.model.Role;
import org.io.GreenGame.user.model.Security;
import org.io.GreenGame.user.model.UserRegisterForm;
import org.io.GreenGame.user.repository.RoleRepository;
import org.io.GreenGame.user.repository.UserRepository;
import org.io.GreenGame.user.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Objects;
import java.util.Random; | 1,612 | package org.io.GreenGame.user.service.implementation;
@Service
@ComponentScan
public class AuthServiceImplementation implements AuthService {
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Override
public Boolean registerUser(UserRegisterForm userRegisterForm) {
Long id = new Random().nextLong();
LocalDateTime creationDate = LocalDateTime.now();
while (userRepository.checkIfIdIsInDatabase(id) != 0) {
id = new Random().nextLong();
}
Boolean doPasswordsMatch = Objects.equals(userRegisterForm.getPassword(), userRegisterForm.getRepeatedPassword());
Long isUsernameInDatabase = userRepository.checkIfUsernameIsInDatabase(userRegisterForm.getUsername());
Long isEmailInDatabase = userRepository.checkIfEmailIsInDatabase(userRegisterForm.getEmail());
if (isUsernameInDatabase != 0 || isEmailInDatabase != 0 || !doPasswordsMatch) {
return false;
} else {
String hashPw = SecurityConfig.passwordEncoder().encode(userRegisterForm.getPassword());
Security security = new Security(creationDate, null, hashPw);
Role role = roleRepository.findByName("ROLE_USER");
if (role == null) {
role = addUserRole();
} | package org.io.GreenGame.user.service.implementation;
@Service
@ComponentScan
public class AuthServiceImplementation implements AuthService {
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Override
public Boolean registerUser(UserRegisterForm userRegisterForm) {
Long id = new Random().nextLong();
LocalDateTime creationDate = LocalDateTime.now();
while (userRepository.checkIfIdIsInDatabase(id) != 0) {
id = new Random().nextLong();
}
Boolean doPasswordsMatch = Objects.equals(userRegisterForm.getPassword(), userRegisterForm.getRepeatedPassword());
Long isUsernameInDatabase = userRepository.checkIfUsernameIsInDatabase(userRegisterForm.getUsername());
Long isEmailInDatabase = userRepository.checkIfEmailIsInDatabase(userRegisterForm.getEmail());
if (isUsernameInDatabase != 0 || isEmailInDatabase != 0 || !doPasswordsMatch) {
return false;
} else {
String hashPw = SecurityConfig.passwordEncoder().encode(userRegisterForm.getPassword());
Security security = new Security(creationDate, null, hashPw);
Role role = roleRepository.findByName("ROLE_USER");
if (role == null) {
role = addUserRole();
} | GreenGameUser greenGameUser = new GreenGameUser(id, userRegisterForm.getUsername(), userRegisterForm.getEmail(), creationDate, creationDate, Collections.singletonList(role), security); | 1 | 2023-10-23 09:21:30+00:00 | 4k |
NewStudyGround/NewStudyGround | server/src/main/java/com/codestates/server/global/security/oauth2/service/KakaoOAuthService.java | [
{
"identifier": "Member",
"path": "server/src/main/java/com/codestates/server/domain/member/entity/Member.java",
"snippet": "@Getter\n@Setter\n@RequiredArgsConstructor\n@Entity\npublic class Member {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long memberId;\n\n p... | import com.codestates.server.domain.member.entity.Member;
import com.codestates.server.domain.member.repository.MemberRepository;
import com.codestates.server.global.exception.BusinessLogicException;
import com.codestates.server.global.exception.ExceptionCode;
import com.codestates.server.global.security.auth.jwt.JwtTokenizer;
import com.codestates.server.global.security.auth.utils.CustomAuthorityUtils;
import com.codestates.server.global.security.oauth2.config.KakaoOAuthConfig;
import com.codestates.server.global.security.oauth2.dto.KakaoMemberInfoDto;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;
import java.util.*; | 3,420 | package com.codestates.server.global.security.oauth2.service;
@AllArgsConstructor
@Service
@Transactional
@Slf4j
public class KakaoOAuthService {
private final KakaoOAuthConfig kakaoOAuthConfig; | package com.codestates.server.global.security.oauth2.service;
@AllArgsConstructor
@Service
@Transactional
@Slf4j
public class KakaoOAuthService {
private final KakaoOAuthConfig kakaoOAuthConfig; | private final MemberRepository memberRepository; | 1 | 2023-10-23 09:41:00+00:00 | 4k |
metacosm/quarkus-power | runtime/src/main/java/io/quarkiverse/power/runtime/sensors/PowerSensorProducer.java | [
{
"identifier": "SensorMeasure",
"path": "runtime/src/main/java/io/quarkiverse/power/runtime/SensorMeasure.java",
"snippet": "public interface SensorMeasure {\n\n double total();\n\n SensorMetadata metadata();\n}"
},
{
"identifier": "IntelRAPLSensor",
"path": "runtime/src/main/java/io/... | import jakarta.enterprise.inject.Produces;
import jakarta.inject.Singleton;
import io.quarkiverse.power.runtime.SensorMeasure;
import io.quarkiverse.power.runtime.sensors.linux.rapl.IntelRAPLSensor;
import io.quarkiverse.power.runtime.sensors.macos.powermetrics.MacOSPowermetricsSensor; | 2,492 | package io.quarkiverse.power.runtime.sensors;
@Singleton
public class PowerSensorProducer {
@Produces
public PowerSensor<?> sensor() {
return determinePowerSensor();
}
| package io.quarkiverse.power.runtime.sensors;
@Singleton
public class PowerSensorProducer {
@Produces
public PowerSensor<?> sensor() {
return determinePowerSensor();
}
| public static PowerSensor<? extends SensorMeasure> determinePowerSensor() { | 0 | 2023-10-23 16:44:57+00:00 | 4k |
LeGhast/Miniaturise | src/main/java/de/leghast/miniaturise/command/DeleteCommand.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.util.Util;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull; | 2,748 | package de.leghast.miniaturise.command;
public class DeleteCommand implements CommandExecutor {
private Miniaturise main;
public DeleteCommand(Miniaturise main){
this.main = main;
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String s, @NotNull String[] args) {
if(sender instanceof Player player){
if(player.hasPermission("miniaturise.use")) {
if (main.getMiniatureManager().hasMiniature(player.getUniqueId())) {
PlacedMiniature placedMiniature;
placedMiniature = main.getMiniatureManager().getPlacedMiniature(player.getUniqueId());
int deletedEntities = 0;
if (placedMiniature != null) {
deletedEntities = placedMiniature.getBlockCount();
placedMiniature.remove();
main.getMiniatureManager().getPlacedMiniatures().replace(player.getUniqueId(), null); | package de.leghast.miniaturise.command;
public class DeleteCommand implements CommandExecutor {
private Miniaturise main;
public DeleteCommand(Miniaturise main){
this.main = main;
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String s, @NotNull String[] args) {
if(sender instanceof Player player){
if(player.hasPermission("miniaturise.use")) {
if (main.getMiniatureManager().hasMiniature(player.getUniqueId())) {
PlacedMiniature placedMiniature;
placedMiniature = main.getMiniatureManager().getPlacedMiniature(player.getUniqueId());
int deletedEntities = 0;
if (placedMiniature != null) {
deletedEntities = placedMiniature.getBlockCount();
placedMiniature.remove();
main.getMiniatureManager().getPlacedMiniatures().replace(player.getUniqueId(), null); | player.sendMessage(Util.PREFIX + "§aThe placed miniature was deleted §e(" + deletedEntities + | 2 | 2023-10-15 09:08:33+00:00 | 4k |
HenryAWE/tcreate | src/main/java/henryawe/tcreate/create/fans/processing/SkySlimeType.java | [
{
"identifier": "TCreate",
"path": "src/main/java/henryawe/tcreate/TCreate.java",
"snippet": "@Mod(\"tcreate\")\npublic final class TCreate {\n /**\n * The mod id.\n */\n public static final String MODID = \"tcreate\";\n\n /**\n * Logger of this class.\n */\n private static f... | import com.simibubi.create.content.kinetics.fan.processing.FanProcessingType;
import com.simibubi.create.foundation.recipe.RecipeApplier;
import henryawe.tcreate.TCreate;
import henryawe.tcreate.TCreateTasks;
import henryawe.tcreate.pattern.PatternMatcher;
import henryawe.tcreate.pattern.TCreatePattern;
import henryawe.tcreate.register.TCreateRecipeTypes;
import henryawe.tcreate.create.fans.recipes.SkySlimeRecipe;
import net.minecraft.core.BlockPos;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.monster.Skeleton;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.phys.Vec3;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.stream.Stream;
import static net.minecraft.world.entity.EntityType.STRAY;
import static slimeknights.tconstruct.fluids.TinkerFluids.skySlime; | 2,276 | package henryawe.tcreate.create.fans.processing;
public class SkySlimeType implements FanProcessingType, PatternMatcher<FluidState> {
static final SkySlimeRecipe.Wrapper WRAPPER = new SkySlimeRecipe.Wrapper();
public static final String CONVERT_FROM_SKYSLIME_TAG = "TCreate_from_skyslime_type";
| package henryawe.tcreate.create.fans.processing;
public class SkySlimeType implements FanProcessingType, PatternMatcher<FluidState> {
static final SkySlimeRecipe.Wrapper WRAPPER = new SkySlimeRecipe.Wrapper();
public static final String CONVERT_FROM_SKYSLIME_TAG = "TCreate_from_skyslime_type";
| private final Collection<TCreatePattern<FluidState>> patterns = new ArrayDeque<>(); | 3 | 2023-10-16 14:42:49+00:00 | 4k |
RacoonDog/Simple-Chat-Emojis | src/main/java/io/github/racoondog/emoji/simplechatemojis/mixin/DrawContextMixin.java | [
{
"identifier": "Emoji",
"path": "src/main/java/io/github/racoondog/emoji/simplechatemojis/Emoji.java",
"snippet": "public class Emoji {\n private static final Emoji MISSING = new Emoji(\n MissingSprite.getMissingSpriteId(),\n MissingSprite.getMissingSpriteId().getPath(),\n ... | import io.github.racoondog.emoji.simplechatemojis.Emoji;
import io.github.racoondog.emoji.simplechatemojis.SimpleChatEmojis;
import io.github.racoondog.emoji.simplechatemojis.Utils;
import it.unimi.dsi.fastutil.Pair;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.font.TextRenderer;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.text.OrderedText;
import net.minecraft.text.Style;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.List;
import java.util.regex.Matcher; | 1,740 | package io.github.racoondog.emoji.simplechatemojis.mixin;
@Environment(EnvType.CLIENT)
@Mixin(DrawContext.class)
public abstract class DrawContextMixin {
@Shadow public abstract int drawText(TextRenderer textRenderer, OrderedText text, int x, int y, int color, boolean shadow);
@Inject(method = "drawTextWithShadow(Lnet/minecraft/client/font/TextRenderer;Lnet/minecraft/text/OrderedText;III)I", at = @At("HEAD"), cancellable = true)
private void injectDrawWithShadow(TextRenderer renderer, OrderedText text, int x, int y, int color, CallbackInfoReturnable<Integer> cir) { | package io.github.racoondog.emoji.simplechatemojis.mixin;
@Environment(EnvType.CLIENT)
@Mixin(DrawContext.class)
public abstract class DrawContextMixin {
@Shadow public abstract int drawText(TextRenderer textRenderer, OrderedText text, int x, int y, int color, boolean shadow);
@Inject(method = "drawTextWithShadow(Lnet/minecraft/client/font/TextRenderer;Lnet/minecraft/text/OrderedText;III)I", at = @At("HEAD"), cancellable = true)
private void injectDrawWithShadow(TextRenderer renderer, OrderedText text, int x, int y, int color, CallbackInfoReturnable<Integer> cir) { | List<Pair<String, Style>> dissected = Utils.dissect(text); | 2 | 2023-10-17 03:03:32+00:00 | 4k |
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; | 3,580 | 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();
| 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; | 0 | 2023-10-21 19:36:50+00:00 | 4k |
tuna-pizza/GraphXings | src/GraphXings/Game/GameInstance/PlanarGameInstanceFactory.java | [
{
"identifier": "IntegerMaths",
"path": "src/GraphXings/Algorithms/IntegerMaths.java",
"snippet": "public class IntegerMaths\n{\n\t/**\n\t * Computes the power of an int.\n\t * @param base An integer base.\n\t * @param exp An integer exponent.\n\t * @return The integer power.\n\t */\n\tpublic static int... | import GraphXings.Algorithms.IntegerMaths;
import GraphXings.Data.Edge;
import GraphXings.Data.Graph;
import GraphXings.Data.Vertex;
import java.util.LinkedList;
import java.util.Random; | 2,564 | package GraphXings.Game.GameInstance;
/**
* A GameInstance factory creating random planar graphs.
* Each graph is one of:
* mode 0 - a planar triangulation
* mode 1 - the dual of a planar triangulation (i.e., a triconnected cubic planar graph)
* mode 2 - a random subgraph of mode 0, where each edge is selected with a probability prob
*/
public class PlanarGameInstanceFactory implements GameInstanceFactory
{
/**
* Random number generator for random sampling.
*/
Random r;
/**
* Probability for choosing an edge. Default: 0.8.
*/
double prob;
/**
* Constructs a PlanarGameInstanceFactory.
* @param seed Seed for the random number generator.
*/
public PlanarGameInstanceFactory(long seed)
{
r = new Random(seed);
prob = 0.8;
}
@Override
public GameInstance getGameInstance()
{
int n_exp = r.nextInt(3) + 2;
int n = r.nextInt(IntegerMaths.pow(10,n_exp-1)*9)+IntegerMaths.pow(10,n_exp-1);
boolean dual;
boolean randomEdge;
int mode = r.nextInt(4);
switch (mode)
{
case 0:
{
dual = false;
randomEdge = false;
break;
}
case 1:
{
dual = true;
randomEdge = false;
break;
}
default:
{
dual = false;
randomEdge = true;
break;
}
}
Graph g = createPlanarGraph(n,dual,randomEdge);
if (dual)
{
n = 2*n-4;
}
int width = 0;
int height = 0;
while (width*height < 10*n)
{
int w_exp = r.nextInt(4) + 1;
int h_exp;
boolean roughlySquare = r.nextBoolean();
if (roughlySquare)
{
h_exp = w_exp;
}
else
{
h_exp = r.nextInt(4) + 1;
}
width = r.nextInt(IntegerMaths.pow(10,w_exp-1)*9)+IntegerMaths.pow(10,w_exp-1);
height = r.nextInt(IntegerMaths.pow(10,h_exp-1)*9)+IntegerMaths.pow(10,h_exp-1);
}
return new GameInstance(g,width,height);
}
/**
* Sets the probability for choosing each edge in mode 2.
* @param prob The probability for choosing an edge. Must be in range (0,1).
*/
public void setEdgeProbability (double prob)
{
if (prob > 0 || prob < 1)
{
this.prob = prob;
}
}
/**
* Constructs a random planar graph.
* @param n The desired number of vertices. If dual is true, the output will have 2n-4 vertices.
* @param dual If true, provides the dual graph of a triangulation on n vertices instead.
* @param randomEdge If true, each edge of the primal graph is added with probability prob.
* @return A random planar graph according to the specification.
*/
private Graph createPlanarGraph(int n, boolean dual, boolean randomEdge)
{
Graph g = new Graph();
Graph d = new Graph(); | package GraphXings.Game.GameInstance;
/**
* A GameInstance factory creating random planar graphs.
* Each graph is one of:
* mode 0 - a planar triangulation
* mode 1 - the dual of a planar triangulation (i.e., a triconnected cubic planar graph)
* mode 2 - a random subgraph of mode 0, where each edge is selected with a probability prob
*/
public class PlanarGameInstanceFactory implements GameInstanceFactory
{
/**
* Random number generator for random sampling.
*/
Random r;
/**
* Probability for choosing an edge. Default: 0.8.
*/
double prob;
/**
* Constructs a PlanarGameInstanceFactory.
* @param seed Seed for the random number generator.
*/
public PlanarGameInstanceFactory(long seed)
{
r = new Random(seed);
prob = 0.8;
}
@Override
public GameInstance getGameInstance()
{
int n_exp = r.nextInt(3) + 2;
int n = r.nextInt(IntegerMaths.pow(10,n_exp-1)*9)+IntegerMaths.pow(10,n_exp-1);
boolean dual;
boolean randomEdge;
int mode = r.nextInt(4);
switch (mode)
{
case 0:
{
dual = false;
randomEdge = false;
break;
}
case 1:
{
dual = true;
randomEdge = false;
break;
}
default:
{
dual = false;
randomEdge = true;
break;
}
}
Graph g = createPlanarGraph(n,dual,randomEdge);
if (dual)
{
n = 2*n-4;
}
int width = 0;
int height = 0;
while (width*height < 10*n)
{
int w_exp = r.nextInt(4) + 1;
int h_exp;
boolean roughlySquare = r.nextBoolean();
if (roughlySquare)
{
h_exp = w_exp;
}
else
{
h_exp = r.nextInt(4) + 1;
}
width = r.nextInt(IntegerMaths.pow(10,w_exp-1)*9)+IntegerMaths.pow(10,w_exp-1);
height = r.nextInt(IntegerMaths.pow(10,h_exp-1)*9)+IntegerMaths.pow(10,h_exp-1);
}
return new GameInstance(g,width,height);
}
/**
* Sets the probability for choosing each edge in mode 2.
* @param prob The probability for choosing an edge. Must be in range (0,1).
*/
public void setEdgeProbability (double prob)
{
if (prob > 0 || prob < 1)
{
this.prob = prob;
}
}
/**
* Constructs a random planar graph.
* @param n The desired number of vertices. If dual is true, the output will have 2n-4 vertices.
* @param dual If true, provides the dual graph of a triangulation on n vertices instead.
* @param randomEdge If true, each edge of the primal graph is added with probability prob.
* @return A random planar graph according to the specification.
*/
private Graph createPlanarGraph(int n, boolean dual, boolean randomEdge)
{
Graph g = new Graph();
Graph d = new Graph(); | LinkedList<Vertex> outerface = new LinkedList<>(); | 3 | 2023-10-18 12:11:38+00:00 | 4k |
instrumental-id/iiq-common-public | src/com/identityworksllc/iiq/common/AggregationOutcome.java | [
{
"identifier": "Outcome",
"path": "src/com/identityworksllc/iiq/common/vo/Outcome.java",
"snippet": "@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)\npublic class Outcome implements AutoCloseable, Serializable {\n\n /**\n * Create and start a new Outcome object. This is intended... | import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.identityworksllc.iiq.common.vo.Outcome;
import com.identityworksllc.iiq.common.vo.OutcomeType;
import sailpoint.api.SailPointContext;
import sailpoint.object.TaskResult;
import sailpoint.tools.GeneralException;
import sailpoint.tools.Message;
import sailpoint.tools.Util;
import sailpoint.tools.xml.AbstractXmlObject;
import java.util.StringJoiner; | 2,866 | package com.identityworksllc.iiq.common;
/**
* A data class for returning the outcome of the aggregation event
*/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class AggregationOutcome extends Outcome {
/**
* An optional error message (can be null);
*/
private String errorMessage;
/**
* Aggregator TaskResults outputs
*/
@JsonIgnore
private String serializedTaskResult;
/**
* Default construct, to be used by Jackson to determine field defaults
*/
@Deprecated
public AggregationOutcome() {
this(null, null);
}
/**
* @param appl The application
* @param ni The native Identity
*/
public AggregationOutcome(String appl, String ni) {
this(appl, ni, null, null);
}
/**
* @param appl The application
* @param ni The native Identity
* @param o The aggregation outcome
*/ | package com.identityworksllc.iiq.common;
/**
* A data class for returning the outcome of the aggregation event
*/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class AggregationOutcome extends Outcome {
/**
* An optional error message (can be null);
*/
private String errorMessage;
/**
* Aggregator TaskResults outputs
*/
@JsonIgnore
private String serializedTaskResult;
/**
* Default construct, to be used by Jackson to determine field defaults
*/
@Deprecated
public AggregationOutcome() {
this(null, null);
}
/**
* @param appl The application
* @param ni The native Identity
*/
public AggregationOutcome(String appl, String ni) {
this(appl, ni, null, null);
}
/**
* @param appl The application
* @param ni The native Identity
* @param o The aggregation outcome
*/ | public AggregationOutcome(String appl, String ni, OutcomeType o) { | 1 | 2023-10-20 15:20:16+00:00 | 4k |
mosaic-addons/traffic-state-estimation | src/main/java/com/dcaiti/mosaic/app/fxd/FxdTransmitterApp.java | [
{
"identifier": "CFxdTransmitterApp",
"path": "src/main/java/com/dcaiti/mosaic/app/fxd/config/CFxdTransmitterApp.java",
"snippet": "public class CFxdTransmitterApp {\n\n /**\n * The id of the unit that shall receive the packages.\n */\n public String receiverId = \"server_0\";\n\n /**\n... | import com.dcaiti.mosaic.app.fxd.config.CFxdTransmitterApp;
import com.dcaiti.mosaic.app.fxd.data.AbstractRecordBuilder;
import com.dcaiti.mosaic.app.fxd.data.FxdRecord;
import com.dcaiti.mosaic.app.fxd.messages.AbstractUpdateMessageBuilder;
import com.dcaiti.mosaic.app.fxd.messages.FxdUpdateMessage;
import org.eclipse.mosaic.fed.application.ambassador.simulation.communication.CamBuilder;
import org.eclipse.mosaic.fed.application.ambassador.simulation.communication.ReceivedAcknowledgement;
import org.eclipse.mosaic.fed.application.ambassador.simulation.communication.ReceivedV2xMessage;
import org.eclipse.mosaic.fed.application.app.ConfigurableApplication;
import org.eclipse.mosaic.fed.application.app.api.CommunicationApplication;
import org.eclipse.mosaic.fed.application.app.api.VehicleApplication;
import org.eclipse.mosaic.fed.application.app.api.os.VehicleOperatingSystem;
import org.eclipse.mosaic.interactions.communication.V2xMessageTransmission;
import org.eclipse.mosaic.lib.geo.GeoUtils;
import org.eclipse.mosaic.lib.objects.road.IConnection;
import org.eclipse.mosaic.lib.objects.v2x.MessageRouting;
import org.eclipse.mosaic.lib.objects.vehicle.VehicleData;
import org.eclipse.mosaic.lib.util.scheduling.Event;
import org.apache.commons.lang3.StringUtils;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.annotation.Nonnull;
import javax.annotation.Nullable; | 2,779 | /*
* Copyright (c) 2023 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.fxd;
public abstract class FxdTransmitterApp<
ConfigT extends CFxdTransmitterApp,
RecordT extends FxdRecord,
RecordBuilderT extends AbstractRecordBuilder<RecordBuilderT, RecordT>, | /*
* Copyright (c) 2023 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.fxd;
public abstract class FxdTransmitterApp<
ConfigT extends CFxdTransmitterApp,
RecordT extends FxdRecord,
RecordBuilderT extends AbstractRecordBuilder<RecordBuilderT, RecordT>, | UpdateT extends FxdUpdateMessage<RecordT>, | 4 | 2023-10-23 16:39:40+00:00 | 4k |
dont-doubt/Neodym | src/main/neodym/NeodymVisitor.java | [
{
"identifier": "NeodymBaseListener",
"path": "src/gen/neodym/antlr/NeodymBaseListener.java",
"snippet": "@SuppressWarnings(\"CheckReturnValue\")\npublic class NeodymBaseListener implements NeodymListener {\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation does nothing.</p>\n\t */\n\t... | import neodym.antlr.NeodymBaseListener;
import neodym.antlr.NeodymParser.ProgContext;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ErrorNode;
import org.antlr.v4.runtime.tree.TerminalNode; | 1,933 | package neodym;
public class NeodymVisitor extends NeodymBaseListener {
@Override | package neodym;
public class NeodymVisitor extends NeodymBaseListener {
@Override | public void enterProg(ProgContext ctx) { | 1 | 2023-10-17 12:28:25+00:00 | 4k |
Primogem-Craft-Development/Primogem-Craft-Fabric | src/main/java/com/primogemstudio/primogemcraft/mixin/MobEffectInstanceMixin.java | [
{
"identifier": "PrimogemCraftBlocks",
"path": "src/main/java/com/primogemstudio/primogemcraft/blocks/PrimogemCraftBlocks.java",
"snippet": "public class PrimogemCraftBlocks {\n public static final DendroCoreBlock DENDRO_CORE_BLOCK = registerWithItem(\"dendro_core_block\", new DendroCoreBlock());\n ... | import com.primogemstudio.primogemcraft.blocks.PrimogemCraftBlocks;
import net.minecraft.core.BlockPos;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.level.Level;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import static com.primogemstudio.primogemcraft.effects.PrimogemCraftMobEffects.ABNORMAL_DISEASE; | 2,745 | package com.primogemstudio.primogemcraft.mixin;
@Mixin(MobEffectInstance.class)
public class MobEffectInstanceMixin {
@Unique
private int tick = 0;
@Inject(method = "applyEffect", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/effect/MobEffect;applyEffectTick(Lnet/minecraft/world/entity/LivingEntity;I)V"))
private void applyEffect(LivingEntity entity, CallbackInfo ci) {
if (effect == ABNORMAL_DISEASE) {
var level = entity.level();
if (!level.isClientSide) {
if (tick == 160) {
level.explode(null, entity.getX(), entity.getY(), entity.getZ(), 8.0F, Level.ExplosionInteraction.TNT);
level.playSound(null, BlockPos.containing(entity.getX(), entity.getY(), entity.getZ()), SoundEvents.GLASS_BREAK, SoundSource.NEUTRAL, 10.0F, 0.5F); | package com.primogemstudio.primogemcraft.mixin;
@Mixin(MobEffectInstance.class)
public class MobEffectInstanceMixin {
@Unique
private int tick = 0;
@Inject(method = "applyEffect", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/effect/MobEffect;applyEffectTick(Lnet/minecraft/world/entity/LivingEntity;I)V"))
private void applyEffect(LivingEntity entity, CallbackInfo ci) {
if (effect == ABNORMAL_DISEASE) {
var level = entity.level();
if (!level.isClientSide) {
if (tick == 160) {
level.explode(null, entity.getX(), entity.getY(), entity.getZ(), 8.0F, Level.ExplosionInteraction.TNT);
level.playSound(null, BlockPos.containing(entity.getX(), entity.getY(), entity.getZ()), SoundEvents.GLASS_BREAK, SoundSource.NEUTRAL, 10.0F, 0.5F); | level.setBlock(entity.blockPosition(), PrimogemCraftBlocks.PRIMOGEM_ORE.defaultBlockState(), 3); | 0 | 2023-10-15 08:07:06+00:00 | 4k |
turtleisaac/PokEditor | src/main/java/io/github/turtleisaac/pokeditor/gui/sheets/tables/FormatModel.java | [
{
"identifier": "DataManager",
"path": "src/main/java/io/github/turtleisaac/pokeditor/DataManager.java",
"snippet": "public class DataManager\n{\n public static final String SHEET_STRINGS_PATH = \"pokeditor/sheet_strings\";\n\n public static DefaultSheetPanel<PersonalData, ?> createPersonalSheet(P... | import io.github.turtleisaac.pokeditor.DataManager;
import io.github.turtleisaac.pokeditor.formats.GenericFileData;
import io.github.turtleisaac.pokeditor.formats.text.TextBankData;
import io.github.turtleisaac.pokeditor.gui.editors.data.EditorDataModel;
import io.github.turtleisaac.pokeditor.gui.sheets.tables.cells.CellTypes;
import javax.swing.table.AbstractTableModel;
import java.util.List;
import java.util.ResourceBundle; | 3,180 | package io.github.turtleisaac.pokeditor.gui.sheets.tables;
public abstract class FormatModel<G extends GenericFileData, E extends Enum<E>> extends AbstractTableModel implements EditorDataModel<E>
{
private final List<G> data;
private final List<TextBankData> textBankData;
private final String[] columnNames;
private boolean copyPasteModeEnabled;
public FormatModel(List<G> data, List<TextBankData> textBankData)
{
this.data = data;
this.textBankData = textBankData;
this.columnNames = new String[getColumnCount() + getNumFrozenColumns()];
ResourceBundle bundle = ResourceBundle.getBundle(DataManager.SHEET_STRINGS_PATH);
int lastValid = 0;
for (int idx = 0; idx < columnNames.length; idx++)
{
int adjusted = idx-getNumFrozenColumns();
String columnNameKey = getColumnNameKey(adjusted);
if (columnNameKey == null)
{
columnNames[idx] = bundle.getString(getColumnNameKey(adjusted % (lastValid + 1))); // this will cause columns to repeat as much as needed for the sheets which need them
}
else {
columnNames[idx] = bundle.getString(columnNameKey);
lastValid = adjusted;
}
}
copyPasteModeEnabled = false;
}
public int getNumFrozenColumns() {
return 0;
}
public abstract String getColumnNameKey(int columnIndex);
@Override
public String getColumnName(int column)
{
return columnNames[column + getNumFrozenColumns()];
}
public void toggleCopyPasteMode(boolean state)
{
copyPasteModeEnabled = state;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex)
{
return !copyPasteModeEnabled;
}
@Override
public int getRowCount()
{
return getEntryCount();
}
@Override
public int getEntryCount()
{
return data.size();
}
@Override
public String getEntryName(int entryIdx)
{
return "" + entryIdx;
}
public List<G> getData()
{
return data;
}
public List<TextBankData> getTextBankData()
{
return textBankData;
}
| package io.github.turtleisaac.pokeditor.gui.sheets.tables;
public abstract class FormatModel<G extends GenericFileData, E extends Enum<E>> extends AbstractTableModel implements EditorDataModel<E>
{
private final List<G> data;
private final List<TextBankData> textBankData;
private final String[] columnNames;
private boolean copyPasteModeEnabled;
public FormatModel(List<G> data, List<TextBankData> textBankData)
{
this.data = data;
this.textBankData = textBankData;
this.columnNames = new String[getColumnCount() + getNumFrozenColumns()];
ResourceBundle bundle = ResourceBundle.getBundle(DataManager.SHEET_STRINGS_PATH);
int lastValid = 0;
for (int idx = 0; idx < columnNames.length; idx++)
{
int adjusted = idx-getNumFrozenColumns();
String columnNameKey = getColumnNameKey(adjusted);
if (columnNameKey == null)
{
columnNames[idx] = bundle.getString(getColumnNameKey(adjusted % (lastValid + 1))); // this will cause columns to repeat as much as needed for the sheets which need them
}
else {
columnNames[idx] = bundle.getString(columnNameKey);
lastValid = adjusted;
}
}
copyPasteModeEnabled = false;
}
public int getNumFrozenColumns() {
return 0;
}
public abstract String getColumnNameKey(int columnIndex);
@Override
public String getColumnName(int column)
{
return columnNames[column + getNumFrozenColumns()];
}
public void toggleCopyPasteMode(boolean state)
{
copyPasteModeEnabled = state;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex)
{
return !copyPasteModeEnabled;
}
@Override
public int getRowCount()
{
return getEntryCount();
}
@Override
public int getEntryCount()
{
return data.size();
}
@Override
public String getEntryName(int entryIdx)
{
return "" + entryIdx;
}
public List<G> getData()
{
return data;
}
public List<TextBankData> getTextBankData()
{
return textBankData;
}
| protected CellTypes getCellType(int columnIndex) | 2 | 2023-10-15 05:00:57+00:00 | 4k |
dashorst/funwithflags | src/main/java/fwf/web/FunWithFlagsWebSocket.java | [
{
"identifier": "ApplicationStatus",
"path": "src/main/java/fwf/ApplicationStatus.java",
"snippet": "public interface ApplicationStatus {\n\n int numberOfGames();\n}"
},
{
"identifier": "FunWithFlagsGame",
"path": "src/main/java/fwf/FunWithFlagsGame.java",
"snippet": "@TemplateGlobal\... | import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import fwf.ApplicationStatus;
import fwf.FunWithFlagsGame;
import fwf.country.Country;
import fwf.game.Game;
import fwf.game.GameFinished;
import fwf.game.GameStarted;
import fwf.guess.Guess;
import fwf.lobby.Lobby;
import fwf.lobby.LobbyFilled;
import fwf.player.Player;
import fwf.player.PlayerRegistered;
import fwf.player.PlayerUnregistered;
import fwf.turn.Turn;
import fwf.turn.TurnClockTicked;
import fwf.turn.TurnFinished;
import fwf.turn.TurnGuessRecorded;
import fwf.turn.TurnStarted;
import io.quarkus.logging.Log;
import io.quarkus.qute.CheckedTemplate;
import io.quarkus.qute.TemplateInstance;
import io.quarkus.scheduler.Scheduled;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnError;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint; | 2,968 | package fwf.web;
@ServerEndpoint("/game/{player}")
@ApplicationScoped
public class FunWithFlagsWebSocket {
@CheckedTemplate
public static class Templates {
public static native TemplateInstance submissionPartial(Country choice);
| package fwf.web;
@ServerEndpoint("/game/{player}")
@ApplicationScoped
public class FunWithFlagsWebSocket {
@CheckedTemplate
public static class Templates {
public static native TemplateInstance submissionPartial(Country choice);
| public static native TemplateInstance game$countdownPartial(Player receiver, Game game, Turn turn); | 5 | 2023-10-17 19:10:37+00:00 | 4k |
Amanastel/Hotel-Management-Microservices | User/src/main/java/com/lcwd/user/service/Service/service/Impl/WalletServicesImpl.java | [
{
"identifier": "TransactionType",
"path": "User/src/main/java/com/lcwd/user/service/Service/entities/TransactionType.java",
"snippet": "public enum TransactionType {\n DEBIT, CREDIT\n}"
},
{
"identifier": "Transactions",
"path": "User/src/main/java/com/lcwd/user/service/Service/entities/... | import com.lcwd.user.service.Service.entities.TransactionType;
import com.lcwd.user.service.Service.entities.Transactions;
import com.lcwd.user.service.Service.entities.User;
import com.lcwd.user.service.Service.entities.Wallet;
import com.lcwd.user.service.Service.exception.UserException;
import com.lcwd.user.service.Service.exception.WalletException;
import com.lcwd.user.service.Service.repository.UserRepository;
import com.lcwd.user.service.Service.repository.WalletRepository;
import com.lcwd.user.service.Service.service.WalletServices;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List; | 2,003 | package com.lcwd.user.service.Service.service.Impl;
@Service
@Slf4j
public class WalletServicesImpl implements WalletServices {
@Autowired
private WalletRepository wrepo;
@Autowired
private UserRepository urepo;
/**
* Adds money to a wallet.
*
* @param walletId The ID of the wallet to add money to.
* @param amount The amount of money to add.
* @return The updated wallet details.
*/
@Override
public Wallet addMoney(Integer walletId, Float amount) {
if(walletId==null || amount == null)
throw new WalletException("Invalid Details");
Wallet ob= wrepo.findById(walletId).orElseThrow(()->new WalletException("No Wallet Found"));
ob.setBalance(ob.getBalance()+amount);
Transactions trans= new Transactions();
trans.setTransactionDate(LocalDateTime.now());
trans.setAmount(amount);
trans.setType(TransactionType.CREDIT);
trans.setCurrentBalance(ob.getBalance());
ob.getTransactions().add(trans);
Wallet res= wrepo.save(ob);
return res;
}
/**
* Retrieves all transactions associated with a wallet.
*
* @param walletId The ID of the wallet to retrieve transactions for.
* @return A list of transactions associated with the wallet.
*/
@Override
public List<Transactions> getAllTranactions(Integer walletId) {
if(walletId==null )
throw new WalletException("Invalid Details");
Wallet ob= wrepo.findById(walletId).orElseThrow(()->new WalletException("No Wallet Found"));
List<Transactions> list= ob.getTransactions();
return list;
}
/**
* Pays a ride bill using a wallet.
*
* @param walletId The ID of the wallet to pay the bill from.
* @param bill The bill amount to be paid.
* @return The updated wallet details.
*/
@Override
public Wallet payRideBill(Integer walletId, Float bill) {
if(walletId==null || bill == null)
throw new WalletException("Invalid Details");
Wallet ob= wrepo.findById(walletId).orElseThrow(()->new WalletException("No Wallet Found"));
if(ob.getBalance()<bill)
{
float required= bill - ob.getBalance();
throw new WalletException("Wallet Balance is low please add "+required+" amount first into your wallet");
}
ob.setBalance(ob.getBalance()-bill);
Transactions trans= new Transactions();
trans.setTransactionDate(LocalDateTime.now());
trans.setAmount(bill);
trans.setType(TransactionType.DEBIT);
trans.setCurrentBalance(ob.getBalance());
ob.getTransactions().add(trans);
Wallet res= wrepo.save(ob);
return res;
}
/**
* Creates a new wallet for a user with the given email.
*
* @param email The email of the user for whom to create a wallet.
* @return The created wallet details.
*/
@Override
public Wallet createWallet(String email) {
if(email==null )
throw new WalletException("Invalid Details");
User user= urepo.findByEmail(email);
if(user==null) | package com.lcwd.user.service.Service.service.Impl;
@Service
@Slf4j
public class WalletServicesImpl implements WalletServices {
@Autowired
private WalletRepository wrepo;
@Autowired
private UserRepository urepo;
/**
* Adds money to a wallet.
*
* @param walletId The ID of the wallet to add money to.
* @param amount The amount of money to add.
* @return The updated wallet details.
*/
@Override
public Wallet addMoney(Integer walletId, Float amount) {
if(walletId==null || amount == null)
throw new WalletException("Invalid Details");
Wallet ob= wrepo.findById(walletId).orElseThrow(()->new WalletException("No Wallet Found"));
ob.setBalance(ob.getBalance()+amount);
Transactions trans= new Transactions();
trans.setTransactionDate(LocalDateTime.now());
trans.setAmount(amount);
trans.setType(TransactionType.CREDIT);
trans.setCurrentBalance(ob.getBalance());
ob.getTransactions().add(trans);
Wallet res= wrepo.save(ob);
return res;
}
/**
* Retrieves all transactions associated with a wallet.
*
* @param walletId The ID of the wallet to retrieve transactions for.
* @return A list of transactions associated with the wallet.
*/
@Override
public List<Transactions> getAllTranactions(Integer walletId) {
if(walletId==null )
throw new WalletException("Invalid Details");
Wallet ob= wrepo.findById(walletId).orElseThrow(()->new WalletException("No Wallet Found"));
List<Transactions> list= ob.getTransactions();
return list;
}
/**
* Pays a ride bill using a wallet.
*
* @param walletId The ID of the wallet to pay the bill from.
* @param bill The bill amount to be paid.
* @return The updated wallet details.
*/
@Override
public Wallet payRideBill(Integer walletId, Float bill) {
if(walletId==null || bill == null)
throw new WalletException("Invalid Details");
Wallet ob= wrepo.findById(walletId).orElseThrow(()->new WalletException("No Wallet Found"));
if(ob.getBalance()<bill)
{
float required= bill - ob.getBalance();
throw new WalletException("Wallet Balance is low please add "+required+" amount first into your wallet");
}
ob.setBalance(ob.getBalance()-bill);
Transactions trans= new Transactions();
trans.setTransactionDate(LocalDateTime.now());
trans.setAmount(bill);
trans.setType(TransactionType.DEBIT);
trans.setCurrentBalance(ob.getBalance());
ob.getTransactions().add(trans);
Wallet res= wrepo.save(ob);
return res;
}
/**
* Creates a new wallet for a user with the given email.
*
* @param email The email of the user for whom to create a wallet.
* @return The created wallet details.
*/
@Override
public Wallet createWallet(String email) {
if(email==null )
throw new WalletException("Invalid Details");
User user= urepo.findByEmail(email);
if(user==null) | throw new UserException("No User Found"); | 4 | 2023-10-17 19:25:18+00:00 | 4k |
xiezhihui98/GAT1400 | src/main/java/com/cz/viid/be/task/action/VIIDServerAction.java | [
{
"identifier": "VIIDServerClient",
"path": "src/main/java/com/cz/viid/rpc/VIIDServerClient.java",
"snippet": "@FeignClient(name = \"VIIDServerClient\", url = \"http://127.0.0.254\")\npublic interface VIIDServerClient {\n\n @PostMapping(\"/VIID/System/Register\")\n Response register(URI uri, @Requ... | import com.cz.viid.rpc.VIIDServerClient;
import com.cz.viid.framework.exception.VIIDRuntimeException;
import com.cz.viid.framework.security.DigestData;
import com.cz.viid.framework.domain.dto.DeviceIdObject;
import com.cz.viid.framework.domain.dto.ResponseStatusObject;
import com.cz.viid.framework.domain.entity.VIIDServer;
import com.cz.viid.framework.domain.vo.KeepaliveRequest;
import com.cz.viid.framework.domain.vo.RegisterRequest;
import com.cz.viid.framework.domain.vo.UnRegisterRequest;
import com.cz.viid.framework.domain.vo.VIIDBaseResponse;
import com.cz.viid.framework.service.VIIDServerService;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Objects;
import java.util.Optional; | 3,342 | package com.cz.viid.be.task.action;
@Component
public class VIIDServerAction {
@Autowired
ObjectMapper objectMapper;
@Autowired | package com.cz.viid.be.task.action;
@Component
public class VIIDServerAction {
@Autowired
ObjectMapper objectMapper;
@Autowired | VIIDServerClient viidServerClient; | 0 | 2023-10-23 11:25:43+00:00 | 4k |
eclipse-egit/egit | org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/synchronize/mapping/GitChangeSetDropAdapterAssistant.java | [
{
"identifier": "runCommand",
"path": "org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/CommonUtils.java",
"snippet": "public static boolean runCommand(String commandId,\n\t\tIStructuredSelection selection) {\n\treturn runCommand(commandId, selection, null);\n}"
},
{
"identifier": "ADD_TO_IN... | import static org.eclipse.egit.ui.internal.CommonUtils.runCommand;
import static org.eclipse.egit.ui.internal.actions.ActionCommands.ADD_TO_INDEX;
import static org.eclipse.egit.ui.internal.actions.ActionCommands.REMOVE_FROM_INDEX;
import java.util.Iterator;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.egit.ui.internal.synchronize.model.GitModelCache;
import org.eclipse.egit.ui.internal.synchronize.model.GitModelCacheFile;
import org.eclipse.egit.ui.internal.synchronize.model.GitModelCacheTree;
import org.eclipse.egit.ui.internal.synchronize.model.GitModelWorkingFile;
import org.eclipse.egit.ui.internal.synchronize.model.GitModelWorkingTree;
import org.eclipse.jface.util.LocalSelectionTransfer;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.TransferData;
import org.eclipse.swt.dnd.URLTransfer;
import org.eclipse.ui.navigator.CommonDropAdapter;
import org.eclipse.ui.navigator.CommonDropAdapterAssistant; | 3,288 | /*******************************************************************************
* Copyright (C) 2011, Dariusz Luksza <dariusz@luksza.org>
*
* 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
*******************************************************************************/
package org.eclipse.egit.ui.internal.synchronize.mapping;
/**
* Drop Adapter Assistant for the Git Change Set model
*/
public class GitChangeSetDropAdapterAssistant extends
CommonDropAdapterAssistant {
private static final URLTransfer SELECTION_TRANSFER = URLTransfer
.getInstance();
/**
* Stage operation type
*/
private static final String STAGE_OP = "STAGE"; //$NON-NLS-1$
/**
* Unstage operation type
*/
private static final String UNSTAGE_OP = "UNSTAGE"; //$NON-NLS-1$
/**
* Unsupported operation type
*/
private static final String UNSUPPORTED_OP = "UNSUPPORTED"; //$NON-NLS-1$
@Override
public IStatus validateDrop(Object target, int operationCode,
TransferData transferType) {
TreeSelection selection = (TreeSelection) LocalSelectionTransfer
.getTransfer().getSelection();
String operation = getOperationType(selection);
if (!UNSUPPORTED_OP.equals(operation)) {
if (target instanceof GitModelWorkingTree) {
if (UNSTAGE_OP.equals(operation))
return Status.OK_STATUS;
} else if (STAGE_OP.equals(operation)
&& target instanceof GitModelCache)
return Status.OK_STATUS;
}
return Status.CANCEL_STATUS;
}
@Override
public IStatus handleDrop(CommonDropAdapter aDropAdapter,
DropTargetEvent aDropTargetEvent, Object aTarget) {
TreeSelection selection = (TreeSelection) LocalSelectionTransfer
.getTransfer().getSelection();
String operation = getOperationType(selection);
if (STAGE_OP.equals(operation))
runCommand(ADD_TO_INDEX, selection);
else if (UNSTAGE_OP.equals(operation))
runCommand(REMOVE_FROM_INDEX, selection);
return Status.OK_STATUS;
}
@Override
public boolean isSupportedType(TransferData aTransferType) {
return SELECTION_TRANSFER.isSupportedType(aTransferType);
}
private String getOperationType(TreeSelection selection) {
String operation = null;
for (Iterator<?> i = selection.iterator(); i.hasNext();) {
String tmpOperation = null;
Object next = i.next(); | /*******************************************************************************
* Copyright (C) 2011, Dariusz Luksza <dariusz@luksza.org>
*
* 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
*******************************************************************************/
package org.eclipse.egit.ui.internal.synchronize.mapping;
/**
* Drop Adapter Assistant for the Git Change Set model
*/
public class GitChangeSetDropAdapterAssistant extends
CommonDropAdapterAssistant {
private static final URLTransfer SELECTION_TRANSFER = URLTransfer
.getInstance();
/**
* Stage operation type
*/
private static final String STAGE_OP = "STAGE"; //$NON-NLS-1$
/**
* Unstage operation type
*/
private static final String UNSTAGE_OP = "UNSTAGE"; //$NON-NLS-1$
/**
* Unsupported operation type
*/
private static final String UNSUPPORTED_OP = "UNSUPPORTED"; //$NON-NLS-1$
@Override
public IStatus validateDrop(Object target, int operationCode,
TransferData transferType) {
TreeSelection selection = (TreeSelection) LocalSelectionTransfer
.getTransfer().getSelection();
String operation = getOperationType(selection);
if (!UNSUPPORTED_OP.equals(operation)) {
if (target instanceof GitModelWorkingTree) {
if (UNSTAGE_OP.equals(operation))
return Status.OK_STATUS;
} else if (STAGE_OP.equals(operation)
&& target instanceof GitModelCache)
return Status.OK_STATUS;
}
return Status.CANCEL_STATUS;
}
@Override
public IStatus handleDrop(CommonDropAdapter aDropAdapter,
DropTargetEvent aDropTargetEvent, Object aTarget) {
TreeSelection selection = (TreeSelection) LocalSelectionTransfer
.getTransfer().getSelection();
String operation = getOperationType(selection);
if (STAGE_OP.equals(operation))
runCommand(ADD_TO_INDEX, selection);
else if (UNSTAGE_OP.equals(operation))
runCommand(REMOVE_FROM_INDEX, selection);
return Status.OK_STATUS;
}
@Override
public boolean isSupportedType(TransferData aTransferType) {
return SELECTION_TRANSFER.isSupportedType(aTransferType);
}
private String getOperationType(TreeSelection selection) {
String operation = null;
for (Iterator<?> i = selection.iterator(); i.hasNext();) {
String tmpOperation = null;
Object next = i.next(); | if (next instanceof GitModelWorkingFile) | 6 | 2023-10-20 15:17:51+00:00 | 4k |
leforero4-ui/unico_proyecto_con_todos_los_patrones_de_diseno_en_java | src/main/application/driver/adapter/usecase/factory_enemies/EnemyHighMethod.java | [
{
"identifier": "EnemyMethod",
"path": "src/main/application/driver/port/usecase/EnemyMethod.java",
"snippet": "public interface EnemyMethod {\n\tList<Enemy> createEnemies();\n\tFavorableEnvironment createFavorableEnvironments();\n}"
},
{
"identifier": "ArmyFactory",
"path": "src/main/domain... | import java.util.ArrayList;
import java.util.List;
import main.application.driver.port.usecase.EnemyMethod;
import main.domain.model.ArmyFactory;
import main.domain.model.Enemy;
import main.domain.model.FavorableEnvironment;
import main.domain.model.Fort;
import main.domain.model.Soldier;
import main.domain.model.Supreme;
import main.domain.model.environment.City;
import main.domain.model.environment.Cold;
import main.domain.model.environment.Heat;
import main.domain.model.environment.Jungle;
import main.domain.model.environment.Rainy;
import main.domain.model.skill.Bang;
import main.domain.model.skill.MultipleShots;
import main.domain.model.skill.Poison; | 3,059 | package main.application.driver.adapter.usecase.factory_enemies;
public class EnemyHighMethod implements EnemyMethod {
private final ArmyFactory armyFactory;
public EnemyHighMethod(final ArmyFactory armyFactory) {
this.armyFactory = armyFactory;
}
@Override
public List<Enemy> createEnemies() {
final List<Enemy> enemies = new ArrayList<>();
final int lifeSoldier = 25;
final int attackLevelSoldier = 5;
final Soldier soldierEnemyBase = armyFactory.createSoldier(lifeSoldier, attackLevelSoldier, new Bang(3));
// supreme
Supreme supreme = armyFactory.getSupreme();
enemies.add(supreme);
// soldiers
final int quantitySoldiers = 5;
for (int created = 1; created <= quantitySoldiers; created++) {
final Soldier soldierEnemy = soldierEnemyBase.clone();
enemies.add(soldierEnemy);
supreme.addProtector(soldierEnemy);
}
// soldiers with fort
final int quantitySoldiersWithFork = 2;
for (int created = 1; created <= quantitySoldiersWithFork; created++) {
enemies.add(new Fort(soldierEnemyBase.clone()));
}
// infantry
final int quantitySquadron = 2;
final int quantitySoldiersForSquadron = 3;
final List<Enemy> squadronsAndSoldiers = new ArrayList<>();
for (int createdSquadron = 1; createdSquadron <= quantitySquadron; createdSquadron++) {
final List<Enemy> soldiers = new ArrayList<>();
for (int created = 1; created <= quantitySoldiersForSquadron; created++) {
soldiers.add(soldierEnemyBase.clone());
}
Enemy squadron = armyFactory.createSquadron(soldiers, new MultipleShots(2));
if (createdSquadron == 1) {
squadron = new Fort(squadron);
}
squadronsAndSoldiers.add(squadron);
}
final int quantitySoldiersInSquadron = 4;
for (int created = 1; created <= quantitySoldiersInSquadron; created++) {
squadronsAndSoldiers.add(soldierEnemyBase.clone());
}
final Enemy infantry = armyFactory.createSquadron(squadronsAndSoldiers, new Poison());
enemies.add(infantry);
return enemies;
}
@Override
public FavorableEnvironment createFavorableEnvironments() {
final FavorableEnvironment favorableEnvironmentFirst = new Heat();
final FavorableEnvironment favorableEnvironmentSecond = new Cold();
final FavorableEnvironment favorableEnvironmentThird = new Rainy(); | package main.application.driver.adapter.usecase.factory_enemies;
public class EnemyHighMethod implements EnemyMethod {
private final ArmyFactory armyFactory;
public EnemyHighMethod(final ArmyFactory armyFactory) {
this.armyFactory = armyFactory;
}
@Override
public List<Enemy> createEnemies() {
final List<Enemy> enemies = new ArrayList<>();
final int lifeSoldier = 25;
final int attackLevelSoldier = 5;
final Soldier soldierEnemyBase = armyFactory.createSoldier(lifeSoldier, attackLevelSoldier, new Bang(3));
// supreme
Supreme supreme = armyFactory.getSupreme();
enemies.add(supreme);
// soldiers
final int quantitySoldiers = 5;
for (int created = 1; created <= quantitySoldiers; created++) {
final Soldier soldierEnemy = soldierEnemyBase.clone();
enemies.add(soldierEnemy);
supreme.addProtector(soldierEnemy);
}
// soldiers with fort
final int quantitySoldiersWithFork = 2;
for (int created = 1; created <= quantitySoldiersWithFork; created++) {
enemies.add(new Fort(soldierEnemyBase.clone()));
}
// infantry
final int quantitySquadron = 2;
final int quantitySoldiersForSquadron = 3;
final List<Enemy> squadronsAndSoldiers = new ArrayList<>();
for (int createdSquadron = 1; createdSquadron <= quantitySquadron; createdSquadron++) {
final List<Enemy> soldiers = new ArrayList<>();
for (int created = 1; created <= quantitySoldiersForSquadron; created++) {
soldiers.add(soldierEnemyBase.clone());
}
Enemy squadron = armyFactory.createSquadron(soldiers, new MultipleShots(2));
if (createdSquadron == 1) {
squadron = new Fort(squadron);
}
squadronsAndSoldiers.add(squadron);
}
final int quantitySoldiersInSquadron = 4;
for (int created = 1; created <= quantitySoldiersInSquadron; created++) {
squadronsAndSoldiers.add(soldierEnemyBase.clone());
}
final Enemy infantry = armyFactory.createSquadron(squadronsAndSoldiers, new Poison());
enemies.add(infantry);
return enemies;
}
@Override
public FavorableEnvironment createFavorableEnvironments() {
final FavorableEnvironment favorableEnvironmentFirst = new Heat();
final FavorableEnvironment favorableEnvironmentSecond = new Cold();
final FavorableEnvironment favorableEnvironmentThird = new Rainy(); | final FavorableEnvironment favorableEnvironmentFourth = new Jungle(12); | 10 | 2023-10-20 18:36:47+00:00 | 4k |
Squawkykaka/when_pigs_fly | src/main/java/com/squawkykaka/when_pigs_fly/commands/Spawn.java | [
{
"identifier": "CommandBase",
"path": "src/main/java/com/squawkykaka/when_pigs_fly/util/CommandBase.java",
"snippet": "public abstract class CommandBase extends BukkitCommand implements CommandExecutor {\n private List<String> delayedPlayers = null;\n private int delay = 0;\n private final int... | import com.squawkykaka.when_pigs_fly.util.CommandBase;
import com.squawkykaka.when_pigs_fly.util.EventUtil;
import com.squawkykaka.when_pigs_fly.util.Msg;
import com.squawkykaka.when_pigs_fly.WhenPigsFly;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player; | 1,618 | package com.squawkykaka.when_pigs_fly.commands;
public class Spawn {
private Location spawn = null;
public Spawn(WhenPigsFly plugin) {
FileConfiguration config = plugin.getConfig();
String worldName = config.getString("spawn.world");
if (worldName == null) {
Bukkit.getLogger().warning("spawn.world does not exist within config.yml");
return;
}
World world = Bukkit.getWorld(worldName);
if (world == null) {
Bukkit.getLogger().severe("World \"" + worldName + "\" does not exist.");
return;
}
int x = config.getInt("spawn.x");
int y = config.getInt("spawn.y");
int z = config.getInt("spawn.z");
float yaw = (float) config.getDouble("spawn.yaw");
float pitch = (float) config.getDouble("spawn.pitch");
spawn = new Location(world, x, y, z, yaw, pitch);
| package com.squawkykaka.when_pigs_fly.commands;
public class Spawn {
private Location spawn = null;
public Spawn(WhenPigsFly plugin) {
FileConfiguration config = plugin.getConfig();
String worldName = config.getString("spawn.world");
if (worldName == null) {
Bukkit.getLogger().warning("spawn.world does not exist within config.yml");
return;
}
World world = Bukkit.getWorld(worldName);
if (world == null) {
Bukkit.getLogger().severe("World \"" + worldName + "\" does not exist.");
return;
}
int x = config.getInt("spawn.x");
int y = config.getInt("spawn.y");
int z = config.getInt("spawn.z");
float yaw = (float) config.getDouble("spawn.yaw");
float pitch = (float) config.getDouble("spawn.pitch");
spawn = new Location(world, x, y, z, yaw, pitch);
| new CommandBase("setspawn", true) { | 0 | 2023-10-17 02:07:39+00:00 | 4k |
greatwqs/finance-manager | src/main/java/com/github/greatwqs/app/controller/TicketController.java | [
{
"identifier": "RequestComponent",
"path": "src/main/java/com/github/greatwqs/app/component/RequestComponent.java",
"snippet": "@Slf4j\n@Component\npublic class RequestComponent {\n\n public HttpServletRequest getRequest() {\n if (getRequestAttributes() != null) {\n return getReque... | import com.github.greatwqs.app.component.RequestComponent;
import com.github.greatwqs.app.domain.dto.TicketTypeDto;
import com.github.greatwqs.app.domain.po.TicketTypePo;
import com.github.greatwqs.app.domain.po.UserPo;
import com.github.greatwqs.app.domain.vo.SubjectVo;
import com.github.greatwqs.app.domain.vo.TicketTypeVo;
import com.github.greatwqs.app.interceptor.annotation.LoginRequired;
import com.github.greatwqs.app.manager.TicketTypeManager;
import com.github.greatwqs.app.service.TicketTypeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List; | 1,898 | package com.github.greatwqs.app.controller;
/**
* 票据类型
*
* @author greatwqs
* Create on 2020/6/27
*/
@RestController
@RequestMapping("ticket")
public class TicketController {
@Autowired
private TicketTypeManager ticketTypeManager;
@Autowired
private TicketTypeService ticketTypeService;
@Autowired | package com.github.greatwqs.app.controller;
/**
* 票据类型
*
* @author greatwqs
* Create on 2020/6/27
*/
@RestController
@RequestMapping("ticket")
public class TicketController {
@Autowired
private TicketTypeManager ticketTypeManager;
@Autowired
private TicketTypeService ticketTypeService;
@Autowired | private RequestComponent requestComponent; | 0 | 2023-10-16 12:45:57+00:00 | 4k |
Wind-Gone/Vodka | code/src/main/java/benchmark/olap/OLAPClient.java | [
{
"identifier": "OrderLine",
"path": "code/src/main/java/bean/OrderLine.java",
"snippet": "@Getter\npublic class OrderLine {\n public Timestamp ol_delivery_d;\n public Timestamp ol_receipdate;\n public Timestamp ol_commitdate;\n\n public OrderLine(Timestamp ol_delivery_d, Timestamp ol_commit... | import bean.OrderLine;
import bean.ReservoirSamplingSingleton;
import benchmark.olap.query.baseQuery;
import config.CommonConfig;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.*;
import java.util.Arrays;
import java.util.Properties;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger; | 1,696 | package benchmark.olap;
public class OLAPClient {
private static Logger log = Logger.getLogger(OLAPClient.class);
private static Properties dbProps;
private static Integer queryNumber = 22;
private static Integer seed = 2023;
public static double[] filterRate = { 0.700, 1, 0.3365, 0.2277, 0.3040,
0.2098, 0.3156, 0.4555, 1, 0.2659,
1, 0.2054, 1, 0.3857, 0.4214,
1, 1, 1, 1, 0.2098,
1, 1, 1 };
public static void initFilterRatio(String database, Properties dbProps, int dbType) {
log.info("Initiating filter rate ...");
try {
Connection con = DriverManager.getConnection(database, dbProps);
Statement stmt = con.createStatement();
if (dbType == CommonConfig.DB_POSTGRES) {
stmt.execute("SET max_parallel_workers_per_gather = 64;");
}
ResultSet result;
for (int i = 0; i < queryNumber; i++) {
String filterSQLPath = "filterQuery/" + (i + 1) + ".sql";
if (dbType == CommonConfig.DB_POSTGRES || dbType == CommonConfig.DB_POLARDB)
filterSQLPath = "filterQuery/pg/" + (i + 1) + ".sql";
if (i == 0 || i == 2 || i == 3 | i == 4 || i == 5 || i == 6 || i == 7 || i == 9 || i == 11 || i == 13
|| i == 14 || i == 19) {
String filterSQLQuery = OLAPClient.readSQL(filterSQLPath);
System.out.println("We are executing query: " + filterSQLQuery);
result = stmt.executeQuery(filterSQLQuery);
if (result.next())
filterRate[i] = Double.parseDouble(result.getString(1));
} else
filterRate[i] = 1;
}
System.out.println(
"We are executing query: select count(*) from vodka_order_line where ol_delivery_d IS NOT NULL;");
result = stmt.executeQuery("select count(*) from vodka_order_line where ol_delivery_d IS NOT NULL;");
if (result.next()) | package benchmark.olap;
public class OLAPClient {
private static Logger log = Logger.getLogger(OLAPClient.class);
private static Properties dbProps;
private static Integer queryNumber = 22;
private static Integer seed = 2023;
public static double[] filterRate = { 0.700, 1, 0.3365, 0.2277, 0.3040,
0.2098, 0.3156, 0.4555, 1, 0.2659,
1, 0.2054, 1, 0.3857, 0.4214,
1, 1, 1, 1, 0.2098,
1, 1, 1 };
public static void initFilterRatio(String database, Properties dbProps, int dbType) {
log.info("Initiating filter rate ...");
try {
Connection con = DriverManager.getConnection(database, dbProps);
Statement stmt = con.createStatement();
if (dbType == CommonConfig.DB_POSTGRES) {
stmt.execute("SET max_parallel_workers_per_gather = 64;");
}
ResultSet result;
for (int i = 0; i < queryNumber; i++) {
String filterSQLPath = "filterQuery/" + (i + 1) + ".sql";
if (dbType == CommonConfig.DB_POSTGRES || dbType == CommonConfig.DB_POLARDB)
filterSQLPath = "filterQuery/pg/" + (i + 1) + ".sql";
if (i == 0 || i == 2 || i == 3 | i == 4 || i == 5 || i == 6 || i == 7 || i == 9 || i == 11 || i == 13
|| i == 14 || i == 19) {
String filterSQLQuery = OLAPClient.readSQL(filterSQLPath);
System.out.println("We are executing query: " + filterSQLQuery);
result = stmt.executeQuery(filterSQLQuery);
if (result.next())
filterRate[i] = Double.parseDouble(result.getString(1));
} else
filterRate[i] = 1;
}
System.out.println(
"We are executing query: select count(*) from vodka_order_line where ol_delivery_d IS NOT NULL;");
result = stmt.executeQuery("select count(*) from vodka_order_line where ol_delivery_d IS NOT NULL;");
if (result.next()) | baseQuery.olNotnullSize = Integer.parseInt(result.getString(1)); | 2 | 2023-10-22 11:22:32+00:00 | 4k |
Onuraktasj/stock-tracking-system | src/main/java/com/onuraktas/stocktrackingsystem/impl/CategoryServiceImpl.java | [
{
"identifier": "CategoryProducer",
"path": "src/main/java/com/onuraktas/stocktrackingsystem/amqp/producer/CategoryProducer.java",
"snippet": "@Component\npublic class CategoryProducer {\n\n private final RabbitTemplate rabbitTemplate;\n\n\n public CategoryProducer(RabbitTemplate rabbitTemplate) {... | import com.onuraktas.stocktrackingsystem.amqp.producer.CategoryProducer;
import com.onuraktas.stocktrackingsystem.dto.amqp.DeletedCategoryMessage;
import com.onuraktas.stocktrackingsystem.dto.entity.CategoryDto;
import com.onuraktas.stocktrackingsystem.dto.request.CreateCategoryRequest;
import com.onuraktas.stocktrackingsystem.dto.request.UpdateCategoryNameRequest;
import com.onuraktas.stocktrackingsystem.dto.response.CreateCategoryResponse;
import com.onuraktas.stocktrackingsystem.dto.response.DeleteCategoryResponse;
import com.onuraktas.stocktrackingsystem.entity.Category;
import com.onuraktas.stocktrackingsystem.entity.enums.Status;
import com.onuraktas.stocktrackingsystem.exception.CategoryAlreadyExistsException;
import com.onuraktas.stocktrackingsystem.exception.CategoryBadRequestException;
import com.onuraktas.stocktrackingsystem.exception.CategoryNotFoundException;
import com.onuraktas.stocktrackingsystem.mapper.CategoryMapper;
import com.onuraktas.stocktrackingsystem.message.CategoryMessages;
import com.onuraktas.stocktrackingsystem.repository.CategoryRepository;
import com.onuraktas.stocktrackingsystem.service.CategoryService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.UUID; | 2,219 | package com.onuraktas.stocktrackingsystem.impl;
@Service
public class CategoryServiceImpl implements CategoryService {
private final CategoryRepository categoryRepository;
private final CategoryProducer categoryProducer;
public CategoryServiceImpl(CategoryRepository categoryRepository, CategoryProducer categoryProducer){
this.categoryRepository = categoryRepository;
this.categoryProducer = categoryProducer;
}
@Override
public CreateCategoryResponse createCategory(CreateCategoryRequest categoryRequest) {
this.checkCategoryNameExists(categoryRequest.getCategoryName());
Category category = this.categoryRepository.save(CategoryMapper.toEntity(categoryRequest));
CreateCategoryResponse createCategoryResponse = CategoryMapper.toCreateCategoryResponse(category);
createCategoryResponse.setStatus(Status.OK.getStatus());
return createCategoryResponse;
}
private void checkCategoryNameExists(String categoryName) {
Category existCategory = categoryRepository.findByCategoryName(categoryName);
if (Objects.nonNull(existCategory)) | package com.onuraktas.stocktrackingsystem.impl;
@Service
public class CategoryServiceImpl implements CategoryService {
private final CategoryRepository categoryRepository;
private final CategoryProducer categoryProducer;
public CategoryServiceImpl(CategoryRepository categoryRepository, CategoryProducer categoryProducer){
this.categoryRepository = categoryRepository;
this.categoryProducer = categoryProducer;
}
@Override
public CreateCategoryResponse createCategory(CreateCategoryRequest categoryRequest) {
this.checkCategoryNameExists(categoryRequest.getCategoryName());
Category category = this.categoryRepository.save(CategoryMapper.toEntity(categoryRequest));
CreateCategoryResponse createCategoryResponse = CategoryMapper.toCreateCategoryResponse(category);
createCategoryResponse.setStatus(Status.OK.getStatus());
return createCategoryResponse;
}
private void checkCategoryNameExists(String categoryName) {
Category existCategory = categoryRepository.findByCategoryName(categoryName);
if (Objects.nonNull(existCategory)) | throw new CategoryAlreadyExistsException(CategoryMessages.CATEGORY_ALREADY_EXIST); | 13 | 2023-10-23 19:00:09+00:00 | 4k |
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; | 2,722 | 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()); | 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()); | 3 | 2023-10-18 16:03:09+00:00 | 4k |
bowbahdoe/java-audio-stack | tritonus-share/src/main/java/dev/mccue/tritonus/share/sampled/convert/TMatrixFormatConversionProvider.java | [
{
"identifier": "ArraySet",
"path": "tritonus-share/src/main/java/dev/mccue/tritonus/share/ArraySet.java",
"snippet": "public class ArraySet<E>\r\nextends ArrayList<E>\r\nimplements Set<E>\r\n{\r\n\tprivate static final long serialVersionUID = 1;\r\n\r\n\tpublic ArraySet()\r\n\t{\r\n\t\tsuper();\r\n\t}\... | import java.util.Iterator;
import javax.sound.sampled.AudioFormat;
import dev.mccue.tritonus.share.ArraySet;
import dev.mccue.tritonus.share.sampled.AudioFormats;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
| 1,950 | /*
* TMatrixFormatConversionProvider.java
*/
/*
* Copyright (c) 1999, 2000 by Matthias Pfisterer <Matthias.Pfisterer@gmx.de>
*
*
* 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.
*
*/
package dev.mccue.tritonus.share.sampled.convert;
/**
* Base class for arbitrary formatConversionProviders.
*
* @author Matthias Pfisterer
*/
@SuppressWarnings("unchecked")
public abstract class TMatrixFormatConversionProvider
extends TSimpleFormatConversionProvider
{
/*
* keys: source AudioFormat
* values: collection of possible target encodings
*
* Note that accessing values with get() is not appropriate,
* since the equals() method in AudioFormat is not overloaded.
* The hashtable is just used as a convenient storage
* organization.
*/
private Map m_targetEncodingsFromSourceFormat;
/*
* keys: source AudioFormat
* values: a Map that contains a mapping from target encodings
* (keys) to a collection of target formats (values).
*
* Note that accessing values with get() is not appropriate,
* since the equals() method in AudioFormat is not overloaded.
* The hashtable is just used as a convenient storage
* organization.
*/
private Map m_targetFormatsFromSourceFormat;
protected TMatrixFormatConversionProvider(
List sourceFormats,
List targetFormats,
boolean[][] abConversionPossible)
{
super(sourceFormats,
targetFormats);
m_targetEncodingsFromSourceFormat = new HashMap();
m_targetFormatsFromSourceFormat = new HashMap();
for (int nSourceFormat = 0;
nSourceFormat < sourceFormats.size();
nSourceFormat++)
{
AudioFormat sourceFormat = (AudioFormat) sourceFormats.get(nSourceFormat);
| /*
* TMatrixFormatConversionProvider.java
*/
/*
* Copyright (c) 1999, 2000 by Matthias Pfisterer <Matthias.Pfisterer@gmx.de>
*
*
* 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.
*
*/
package dev.mccue.tritonus.share.sampled.convert;
/**
* Base class for arbitrary formatConversionProviders.
*
* @author Matthias Pfisterer
*/
@SuppressWarnings("unchecked")
public abstract class TMatrixFormatConversionProvider
extends TSimpleFormatConversionProvider
{
/*
* keys: source AudioFormat
* values: collection of possible target encodings
*
* Note that accessing values with get() is not appropriate,
* since the equals() method in AudioFormat is not overloaded.
* The hashtable is just used as a convenient storage
* organization.
*/
private Map m_targetEncodingsFromSourceFormat;
/*
* keys: source AudioFormat
* values: a Map that contains a mapping from target encodings
* (keys) to a collection of target formats (values).
*
* Note that accessing values with get() is not appropriate,
* since the equals() method in AudioFormat is not overloaded.
* The hashtable is just used as a convenient storage
* organization.
*/
private Map m_targetFormatsFromSourceFormat;
protected TMatrixFormatConversionProvider(
List sourceFormats,
List targetFormats,
boolean[][] abConversionPossible)
{
super(sourceFormats,
targetFormats);
m_targetEncodingsFromSourceFormat = new HashMap();
m_targetFormatsFromSourceFormat = new HashMap();
for (int nSourceFormat = 0;
nSourceFormat < sourceFormats.size();
nSourceFormat++)
{
AudioFormat sourceFormat = (AudioFormat) sourceFormats.get(nSourceFormat);
| List supportedTargetEncodings = new ArraySet();
| 0 | 2023-10-19 14:09:37+00:00 | 4k |
dvillavicencio/Riven-of-a-Thousand-Servers | src/test/java/com/danielvm/destiny2bot/service/WeeklyActivitiesServiceTest.java | [
{
"identifier": "BungieClient",
"path": "src/main/java/com/danielvm/destiny2bot/client/BungieClient.java",
"snippet": "public interface BungieClient {\n\n /**\n * Gets the membership info for the current user\n *\n * @param bearerToken The user's bearer token\n * @return {@link MembershipRespon... | import static org.mockito.Mockito.when;
import com.danielvm.destiny2bot.client.BungieClient;
import com.danielvm.destiny2bot.client.BungieClientWrapper;
import com.danielvm.destiny2bot.dto.WeeklyActivity;
import com.danielvm.destiny2bot.dto.destiny.GenericResponse;
import com.danielvm.destiny2bot.dto.destiny.manifest.DisplayProperties;
import com.danielvm.destiny2bot.dto.destiny.manifest.ResponseFields;
import com.danielvm.destiny2bot.dto.destiny.milestone.ActivitiesDto;
import com.danielvm.destiny2bot.dto.destiny.milestone.MilestoneEntry;
import com.danielvm.destiny2bot.enums.ActivityMode;
import com.danielvm.destiny2bot.enums.ManifestEntity;
import com.danielvm.destiny2bot.exception.ResourceNotFoundException;
import java.time.ZonedDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.DisplayName;
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 reactor.core.publisher.Mono;
import reactor.test.StepVerifier; | 2,389 | package com.danielvm.destiny2bot.service;
@ExtendWith(MockitoExtension.class)
public class WeeklyActivitiesServiceTest {
@Mock
private BungieClient bungieClient;
@Mock
private BungieClientWrapper bungieClientWrapper;
@InjectMocks
private WeeklyActivitiesService sut;
@Test
@DisplayName("Retrieve weekly raid works successfully")
public void retrieveWeeklyRaidWorksSuccessfully() {
// given: an activity mode
ActivityMode activity = ActivityMode.RAID;
var startTime = ZonedDateTime.now();
var endTime = ZonedDateTime.now().plusDays(2L);
var activitiesNoWeekly = List.of(new ActivitiesDto("1262462921", Collections.emptyList()));
var activitiesWeekly = List.of(new ActivitiesDto("2823159265", List.of("897950155")));
var milestoneResponse = new GenericResponse<>(
Map.of(
"526718853", new MilestoneEntry("526718853",
startTime, endTime, activitiesNoWeekly),
"3618845105", new MilestoneEntry("3618845105",
startTime, endTime, activitiesWeekly),
"2029743966", new MilestoneEntry("2029743966",
startTime, endTime, null)
)
);
when(bungieClient.getPublicMilestonesRx())
.thenReturn(Mono.just(milestoneResponse));
| package com.danielvm.destiny2bot.service;
@ExtendWith(MockitoExtension.class)
public class WeeklyActivitiesServiceTest {
@Mock
private BungieClient bungieClient;
@Mock
private BungieClientWrapper bungieClientWrapper;
@InjectMocks
private WeeklyActivitiesService sut;
@Test
@DisplayName("Retrieve weekly raid works successfully")
public void retrieveWeeklyRaidWorksSuccessfully() {
// given: an activity mode
ActivityMode activity = ActivityMode.RAID;
var startTime = ZonedDateTime.now();
var endTime = ZonedDateTime.now().plusDays(2L);
var activitiesNoWeekly = List.of(new ActivitiesDto("1262462921", Collections.emptyList()));
var activitiesWeekly = List.of(new ActivitiesDto("2823159265", List.of("897950155")));
var milestoneResponse = new GenericResponse<>(
Map.of(
"526718853", new MilestoneEntry("526718853",
startTime, endTime, activitiesNoWeekly),
"3618845105", new MilestoneEntry("3618845105",
startTime, endTime, activitiesWeekly),
"2029743966", new MilestoneEntry("2029743966",
startTime, endTime, null)
)
);
when(bungieClient.getPublicMilestonesRx())
.thenReturn(Mono.just(milestoneResponse));
| var activityWithType = new ResponseFields(); | 5 | 2023-10-20 05:53:03+00:00 | 4k |
MinecraftForge/ModLauncher | src/main/java/cpw/mods/modlauncher/TransformingClassLoader.java | [
{
"identifier": "IEnvironment",
"path": "src/main/java/cpw/mods/modlauncher/api/IEnvironment.java",
"snippet": "public interface IEnvironment {\n /**\n * Get a property from the Environment\n * @param key to find\n * @param <T> Type of key\n * @return the value\n */\n <T> Optio... | import cpw.mods.cl.ModuleClassLoader;
import cpw.mods.modlauncher.api.IEnvironment;
import cpw.mods.modlauncher.api.ITransformerActivity;
import cpw.mods.modlauncher.api.IModuleLayerManager.Layer;
import java.lang.module.Configuration;
import java.util.*; | 1,785 | /*
* Copyright (c) Forge Development LLC
* SPDX-License-Identifier: LGPL-3.0-only
*/
package cpw.mods.modlauncher;
/**
* Module transforming class loader
*/
public class TransformingClassLoader extends ModuleClassLoader {
static {
ClassLoader.registerAsParallelCapable();
}
private final ClassTransformer classTransformer;
private static ModuleLayer get(ModuleLayerHandler layers, Layer layer) {
return layers.getLayer(layer).orElseThrow(() -> new NullPointerException("Failed to find " + layer.name() + " layer"));
}
public TransformingClassLoader(TransformStore transformStore, LaunchPluginHandler pluginHandler, ModuleLayerHandler layers) {
super("TRANSFORMER", get(layers, Layer.GAME).configuration(), List.of(get(layers, Layer.SERVICE)));
this.classTransformer = new ClassTransformer(transformStore, pluginHandler, this);
}
TransformingClassLoader(String name, ClassLoader parent, Configuration config, List<ModuleLayer> parentLayers, List<ClassLoader> parentLoaders,
TransformStore transformStore, LaunchPluginHandler pluginHandler, Environment environment) {
super(name, parent, config, parentLayers, parentLoaders, true);
TransformerAuditTrail tat = new TransformerAuditTrail(); | /*
* Copyright (c) Forge Development LLC
* SPDX-License-Identifier: LGPL-3.0-only
*/
package cpw.mods.modlauncher;
/**
* Module transforming class loader
*/
public class TransformingClassLoader extends ModuleClassLoader {
static {
ClassLoader.registerAsParallelCapable();
}
private final ClassTransformer classTransformer;
private static ModuleLayer get(ModuleLayerHandler layers, Layer layer) {
return layers.getLayer(layer).orElseThrow(() -> new NullPointerException("Failed to find " + layer.name() + " layer"));
}
public TransformingClassLoader(TransformStore transformStore, LaunchPluginHandler pluginHandler, ModuleLayerHandler layers) {
super("TRANSFORMER", get(layers, Layer.GAME).configuration(), List.of(get(layers, Layer.SERVICE)));
this.classTransformer = new ClassTransformer(transformStore, pluginHandler, this);
}
TransformingClassLoader(String name, ClassLoader parent, Configuration config, List<ModuleLayer> parentLayers, List<ClassLoader> parentLoaders,
TransformStore transformStore, LaunchPluginHandler pluginHandler, Environment environment) {
super(name, parent, config, parentLayers, parentLoaders, true);
TransformerAuditTrail tat = new TransformerAuditTrail(); | environment.computePropertyIfAbsent(IEnvironment.Keys.AUDITTRAIL.get(), v->tat); | 0 | 2023-10-18 17:56:01+00:00 | 4k |
Kyrotechnic/KyroClient | Client/src/main/java/me/kyroclient/commands/impl/FriendCommand.java | [
{
"identifier": "KyroClient",
"path": "Client/src/main/java/me/kyroclient/KyroClient.java",
"snippet": "public class KyroClient {\n //Vars\n public static final String MOD_ID = \"dankers\";\n public static String VERSION = \"0.2-b3\";\n public static List<String> changelog;\n public stati... | import me.kyroclient.KyroClient;
import me.kyroclient.commands.Command;
import java.util.stream.Collectors; | 1,834 | package me.kyroclient.commands.impl;
public class FriendCommand extends Command {
public FriendCommand()
{
super("friend");
}
@Override
public void execute(String[] args) throws Exception {
if (args.length != 3)
{
printFriends();
return;
}
switch (args[1])
{
case "add": | package me.kyroclient.commands.impl;
public class FriendCommand extends Command {
public FriendCommand()
{
super("friend");
}
@Override
public void execute(String[] args) throws Exception {
if (args.length != 3)
{
printFriends();
return;
}
switch (args[1])
{
case "add": | KyroClient.friendManager.add(args[2]); | 0 | 2023-10-15 16:24:51+00:00 | 4k |
ssap-rainbow/SSAP-BackEnd | src/main/java/ssap/ssap/service/BidService.java | [
{
"identifier": "Auction",
"path": "src/main/java/ssap/ssap/domain/Auction.java",
"snippet": "@Getter\n@Setter\n@Entity\npublic class Auction {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n private LocalDateTime startTime;\n private LocalDateTime endTi... | import jakarta.persistence.EntityNotFoundException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ssap.ssap.domain.Auction;
import ssap.ssap.domain.Bid;
import ssap.ssap.domain.Task;
import ssap.ssap.domain.User;
import ssap.ssap.dto.BidRequestDto;
import ssap.ssap.dto.BidResponseDto;
import ssap.ssap.repository.AuctionRepository;
import ssap.ssap.repository.BidRepository;
import ssap.ssap.repository.TaskRepository;
import ssap.ssap.repository.UserRepository;
import java.time.LocalDateTime; | 2,229 | package ssap.ssap.service;
@Slf4j
@Service
public class BidService {
private final TaskRepository taskRepository;
private final UserRepository userRepository;
private final BidRepository bidRepository;
private final AuctionRepository auctionRepository;
@Autowired
public BidService(TaskRepository taskRepository, UserRepository userRepository, BidRepository bidRepository, AuctionRepository auctionRepository) {
this.taskRepository = taskRepository;
this.userRepository = userRepository;
this.bidRepository = bidRepository;
this.auctionRepository = auctionRepository;
}
@Transactional
public String placeBid(BidRequestDto bidRequest) {
log.info("입찰 요청 처리 시작: {}", bidRequest);
Task task = taskRepository.findById(bidRequest.getTaskId())
.orElseThrow(() -> new EntityNotFoundException("심부름을 찾을 수 없습니다: " + bidRequest.getTaskId()));
log.debug("심부름 조회 성공: {}", task);
User user = userRepository.findByEmail(bidRequest.getUserEmail())
.orElseThrow(() -> new EntityNotFoundException("사용자를 찾을 수 없습니다: " + bidRequest.getUserEmail()));
log.debug("사용자 조회 성공: {}", user);
// 경매 상태 및 입찰 가능 여부 검증
Auction auction = auctionRepository.findById(bidRequest.getAuctionId())
.orElseThrow(() -> new EntityNotFoundException("경매를 찾을 수 없습니다: " + bidRequest.getAuctionId()));
log.debug("경매 조회 성공: {}", auction);
if (LocalDateTime.now().isAfter(auction.getEndTime())) {
throw new IllegalArgumentException("이미 종료된 경매에는 입찰할 수 없습니다.");
}
// 최저 입찰 금액 검증
Integer currentLowestBid = bidRepository.findLowestBidAmountByAuctionId(auction.getId());
Integer taskFee = Integer.valueOf(task.getFee());
if (currentLowestBid != null) {
if (bidRequest.getBidAmount() >= currentLowestBid) {
log.error("입찰 실패: 입찰 금액 ({})은 현재 최저 입찰 금액 ({})보다 낮아야 함", bidRequest.getBidAmount(), currentLowestBid);
throw new IllegalArgumentException("입찰 금액은 현재 최저 입찰 금액보다 낮아야 합니다.");
}
} else if (bidRequest.getBidAmount() >= taskFee) {
// 최초 입찰인 경우, 입찰 금액이 Task의 fee보다 낮아야 함
log.error("입찰 실패: 입찰 금액 ({})은 Task의 fee 금액 ({})보다 낮아야 함", bidRequest.getBidAmount(), taskFee);
throw new IllegalArgumentException("입찰 금액은 현재 최저 입찰 금액보다 낮아야 합니다.");
}
// 입찰 처리 | package ssap.ssap.service;
@Slf4j
@Service
public class BidService {
private final TaskRepository taskRepository;
private final UserRepository userRepository;
private final BidRepository bidRepository;
private final AuctionRepository auctionRepository;
@Autowired
public BidService(TaskRepository taskRepository, UserRepository userRepository, BidRepository bidRepository, AuctionRepository auctionRepository) {
this.taskRepository = taskRepository;
this.userRepository = userRepository;
this.bidRepository = bidRepository;
this.auctionRepository = auctionRepository;
}
@Transactional
public String placeBid(BidRequestDto bidRequest) {
log.info("입찰 요청 처리 시작: {}", bidRequest);
Task task = taskRepository.findById(bidRequest.getTaskId())
.orElseThrow(() -> new EntityNotFoundException("심부름을 찾을 수 없습니다: " + bidRequest.getTaskId()));
log.debug("심부름 조회 성공: {}", task);
User user = userRepository.findByEmail(bidRequest.getUserEmail())
.orElseThrow(() -> new EntityNotFoundException("사용자를 찾을 수 없습니다: " + bidRequest.getUserEmail()));
log.debug("사용자 조회 성공: {}", user);
// 경매 상태 및 입찰 가능 여부 검증
Auction auction = auctionRepository.findById(bidRequest.getAuctionId())
.orElseThrow(() -> new EntityNotFoundException("경매를 찾을 수 없습니다: " + bidRequest.getAuctionId()));
log.debug("경매 조회 성공: {}", auction);
if (LocalDateTime.now().isAfter(auction.getEndTime())) {
throw new IllegalArgumentException("이미 종료된 경매에는 입찰할 수 없습니다.");
}
// 최저 입찰 금액 검증
Integer currentLowestBid = bidRepository.findLowestBidAmountByAuctionId(auction.getId());
Integer taskFee = Integer.valueOf(task.getFee());
if (currentLowestBid != null) {
if (bidRequest.getBidAmount() >= currentLowestBid) {
log.error("입찰 실패: 입찰 금액 ({})은 현재 최저 입찰 금액 ({})보다 낮아야 함", bidRequest.getBidAmount(), currentLowestBid);
throw new IllegalArgumentException("입찰 금액은 현재 최저 입찰 금액보다 낮아야 합니다.");
}
} else if (bidRequest.getBidAmount() >= taskFee) {
// 최초 입찰인 경우, 입찰 금액이 Task의 fee보다 낮아야 함
log.error("입찰 실패: 입찰 금액 ({})은 Task의 fee 금액 ({})보다 낮아야 함", bidRequest.getBidAmount(), taskFee);
throw new IllegalArgumentException("입찰 금액은 현재 최저 입찰 금액보다 낮아야 합니다.");
}
// 입찰 처리 | Bid newBid = new Bid(); | 1 | 2023-10-17 08:45:39+00:00 | 4k |
AstroDev2023/2023-studio-1-but-better | source/core/src/main/com/csse3200/game/entities/EntityIndicator.java | [
{
"identifier": "CameraComponent",
"path": "source/core/src/main/com/csse3200/game/components/CameraComponent.java",
"snippet": "public class CameraComponent extends Component {\n\tprivate final Camera camera;\n\tprivate Vector2 lastPosition;\n\tprivate Entity trackEntity;\n\n\t/**\n\t * Creates a new C... | import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.csse3200.game.components.CameraComponent;
import com.csse3200.game.services.ServiceLocator;
import com.csse3200.game.ui.UIComponent; | 3,515 | package com.csse3200.game.entities;
/**
* A UI component responsible for indicating the direction of an entity which is off-screen
*/
public class EntityIndicator extends UIComponent {
/**
* Indicator image
*/
private Image indicator;
/**
* Indicator asset path
*/
private String indicatorAssetPath;
/**
* The hostile entity being tracked
*/
private Entity entityToTractor;
/**
* The camera component of the game
*/
private CameraComponent cameraComponent;
/**
* Distance from center
*/
private static final float INDICATOR_DISTANCE = 175;
/**
* Initialise a new indicator for the given entity
*
* @param entity: the entity which will be tracked
*/
public EntityIndicator(Entity entity) {
this(entity, "images/hostile_indicator.png");
}
/**
* Initialise a new indicator for the given entity
*
* @param entity: the entity which will be tracked
* @param indicatorAssetPath: path for the indicator asset
*/
public EntityIndicator(Entity entity, String indicatorAssetPath) {
this.indicatorAssetPath = indicatorAssetPath;
this.entityToTractor = entity; | package com.csse3200.game.entities;
/**
* A UI component responsible for indicating the direction of an entity which is off-screen
*/
public class EntityIndicator extends UIComponent {
/**
* Indicator image
*/
private Image indicator;
/**
* Indicator asset path
*/
private String indicatorAssetPath;
/**
* The hostile entity being tracked
*/
private Entity entityToTractor;
/**
* The camera component of the game
*/
private CameraComponent cameraComponent;
/**
* Distance from center
*/
private static final float INDICATOR_DISTANCE = 175;
/**
* Initialise a new indicator for the given entity
*
* @param entity: the entity which will be tracked
*/
public EntityIndicator(Entity entity) {
this(entity, "images/hostile_indicator.png");
}
/**
* Initialise a new indicator for the given entity
*
* @param entity: the entity which will be tracked
* @param indicatorAssetPath: path for the indicator asset
*/
public EntityIndicator(Entity entity, String indicatorAssetPath) {
this.indicatorAssetPath = indicatorAssetPath;
this.entityToTractor = entity; | cameraComponent = ServiceLocator.getCameraComponent(); | 1 | 2023-10-17 22:34:04+00:00 | 4k |
moeinfatehi/PassiveDigger | src/PassiveDigger/vulnerability.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.IHttpRequestResponse;
import burp.IParameter;
import burp.IRequestInfo;
import burp.BurpExtender; | 2,354 | /*
* 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 PassiveDigger;
/**
*
* @author moein
*/
public class vulnerability {
IHttpRequestResponse reqResp; | /*
* 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 PassiveDigger;
/**
*
* @author moein
*/
public class vulnerability {
IHttpRequestResponse reqResp; | IParameter param; | 2 | 2023-10-23 12:13:00+00:00 | 4k |
LuckPerms/rest-api-java-client | src/main/java/net/luckperms/rest/service/GroupService.java | [
{
"identifier": "CreateGroupRequest",
"path": "src/main/java/net/luckperms/rest/model/CreateGroupRequest.java",
"snippet": "public class CreateGroupRequest extends AbstractModel {\n private final String name;\n\n public CreateGroupRequest(String name) {\n this.name = name;\n }\n\n pub... | import net.luckperms.rest.model.CreateGroupRequest;
import net.luckperms.rest.model.Group;
import net.luckperms.rest.model.GroupSearchResult;
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.TemporaryNodeMergeStrategy;
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; | 1,835 | /*
* 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 GroupService {
@GET("/group")
Call<Set<String>> list();
@POST("/group") | /*
* 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 GroupService {
@GET("/group")
Call<Set<String>> list();
@POST("/group") | Call<Group> create(@Body CreateGroupRequest req); | 1 | 2023-10-22 16:07:30+00:00 | 4k |
EvanAatrox/hubbo | hubbo/src/test/java/cn/hubbo/unit/UtilsUnitTest.java | [
{
"identifier": "User",
"path": "hubbo-domain/src/main/java/cn/hubbo/domain/dos/User.java",
"snippet": "@Data\n@Accessors(chain = true)\n@Entity(name = \"t_user\")\n@Table(indexes = {@Index(name = \"user_name_index\", columnList = \"user_name\", unique = true),\n @Index(name = \"phone_index\", co... | import cn.hubbo.domain.dos.User;
import cn.hubbo.utils.common.base.JsonUtils;
import cn.hubbo.utils.common.security.JWTUtils;
import org.junit.jupiter.api.Test;
import java.util.UUID; | 2,006 | package cn.hubbo.unit;
/**
* @author 张晓华
* @version V1.0
* @Package cn.hubbo.unit
* @date 2023/10/18 22:05
* @Copyright © 2016-2017 版权所有,未经授权均为剽窃,作者保留一切权利
*/
public class UtilsUnitTest {
@Test
public void testGenerateToken() { | package cn.hubbo.unit;
/**
* @author 张晓华
* @version V1.0
* @Package cn.hubbo.unit
* @date 2023/10/18 22:05
* @Copyright © 2016-2017 版权所有,未经授权均为剽窃,作者保留一切权利
*/
public class UtilsUnitTest {
@Test
public void testGenerateToken() { | User user = new User().setUsername("user1"); | 0 | 2023-10-18 09:38:29+00:00 | 4k |
Xernas78/menu-lib | src/main/java/dev/xernas/menulib/utils/ItemBuilder.java | [
{
"identifier": "Menu",
"path": "src/main/java/dev/xernas/menulib/Menu.java",
"snippet": "public abstract class Menu implements InventoryHolder {\n\n private final Player owner;\n\n public Menu(Player owner) {\n this.owner = owner;\n }\n\n @NotNull\n public abstract String getName(... | import dev.xernas.menulib.Menu;
import dev.xernas.menulib.MenuLib;
import dev.xernas.menulib.PaginatedMenu;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataContainer;
import org.bukkit.persistence.PersistentDataType;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer; | 1,846 | package dev.xernas.menulib.utils;
public class ItemBuilder extends ItemStack {
private final Menu itemMenu;
private ItemMeta meta;
public ItemBuilder(Menu itemMenu, Material material) {
this(itemMenu, material, null);
}
public ItemBuilder(Menu itemMenu, ItemStack item) {
this(itemMenu, item, null);
}
public ItemBuilder(Menu itemMenu, Material material, Consumer<ItemMeta> itemMeta) {
this(itemMenu, new ItemStack(material), itemMeta);
}
public ItemBuilder(Menu itemMenu, ItemStack item, Consumer<ItemMeta> itemMeta) {
super(item);
this.itemMenu = itemMenu;
meta = getItemMeta();
if (itemMeta != null) {
itemMeta.accept(meta);
}
setItemMeta(meta);
}
public ItemBuilder setItemId(String itemId) {
PersistentDataContainer dataContainer = meta.getPersistentDataContainer(); | package dev.xernas.menulib.utils;
public class ItemBuilder extends ItemStack {
private final Menu itemMenu;
private ItemMeta meta;
public ItemBuilder(Menu itemMenu, Material material) {
this(itemMenu, material, null);
}
public ItemBuilder(Menu itemMenu, ItemStack item) {
this(itemMenu, item, null);
}
public ItemBuilder(Menu itemMenu, Material material, Consumer<ItemMeta> itemMeta) {
this(itemMenu, new ItemStack(material), itemMeta);
}
public ItemBuilder(Menu itemMenu, ItemStack item, Consumer<ItemMeta> itemMeta) {
super(item);
this.itemMenu = itemMenu;
meta = getItemMeta();
if (itemMeta != null) {
itemMeta.accept(meta);
}
setItemMeta(meta);
}
public ItemBuilder setItemId(String itemId) {
PersistentDataContainer dataContainer = meta.getPersistentDataContainer(); | dataContainer.set(MenuLib.getItemIdKey(), PersistentDataType.STRING, itemId.toLowerCase()); | 1 | 2023-10-23 16:02:26+00:00 | 4k |
samdsk/lab-sweng | e03-2023giu/src/main/java/it/unimi/di/sweng/esame/Main.java | [
{
"identifier": "ObservableModel",
"path": "e01-2023gen/src/main/java/it/unimi/di/sweng/esame/model/ObservableModel.java",
"snippet": "public class ObservableModel extends Model implements Observable<List<Partenza>> {\n\tprivate final List<Observer<List<Partenza>>> observers = new ArrayList<>();\n\n\tpu... | import it.unimi.di.sweng.esame.model.ObservableModel;
import it.unimi.di.sweng.esame.presenters.InputPresenter;
import it.unimi.di.sweng.esame.presenters.SegnalazioniAperte;
import it.unimi.di.sweng.esame.presenters.SegnalazioniRisolte;
import it.unimi.di.sweng.esame.views.CentralStationView;
import it.unimi.di.sweng.esame.views.DisplayView;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage; | 2,724 | package it.unimi.di.sweng.esame;
public class Main extends Application {
final public static int PANEL_SIZE = 8;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Autostrade");
CentralStationView stationView = new CentralStationView();
DisplayView leftSideView = new DisplayView("Segnalazioni Attive", PANEL_SIZE);
DisplayView rightSideView = new DisplayView("Segnalazioni Chiuse", PANEL_SIZE);
GridPane gridPane = new GridPane();
gridPane.setBackground(new Background(new BackgroundFill(Color.DARKOLIVEGREEN, CornerRadii.EMPTY, Insets.EMPTY)));
gridPane.setPadding(new Insets(10, 10, 10, 10));
gridPane.add(stationView, 0, 0);
GridPane.setColumnSpan(stationView, GridPane.REMAINING);
gridPane.add(leftSideView, 0, 1);
gridPane.add(rightSideView, 1, 1);
//TODO creare presenters e connettere model e view
ObservableModel model = new ObservableModel();
new SegnalazioniAperte(model,leftSideView); | package it.unimi.di.sweng.esame;
public class Main extends Application {
final public static int PANEL_SIZE = 8;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Autostrade");
CentralStationView stationView = new CentralStationView();
DisplayView leftSideView = new DisplayView("Segnalazioni Attive", PANEL_SIZE);
DisplayView rightSideView = new DisplayView("Segnalazioni Chiuse", PANEL_SIZE);
GridPane gridPane = new GridPane();
gridPane.setBackground(new Background(new BackgroundFill(Color.DARKOLIVEGREEN, CornerRadii.EMPTY, Insets.EMPTY)));
gridPane.setPadding(new Insets(10, 10, 10, 10));
gridPane.add(stationView, 0, 0);
GridPane.setColumnSpan(stationView, GridPane.REMAINING);
gridPane.add(leftSideView, 0, 1);
gridPane.add(rightSideView, 1, 1);
//TODO creare presenters e connettere model e view
ObservableModel model = new ObservableModel();
new SegnalazioniAperte(model,leftSideView); | new SegnalazioniRisolte(model,rightSideView); | 3 | 2023-10-19 06:28:13+00:00 | 4k |
RoessinghResearch/senseeact | ExampleSenSeeActClient/src/main/java/nl/rrd/senseeact/exampleclient/project/ExampleProjectRepository.java | [
{
"identifier": "BaseProject",
"path": "SenSeeActClient/src/main/java/nl/rrd/senseeact/client/project/BaseProject.java",
"snippet": "public abstract class BaseProject {\n\tprivate final String code;\n\tprivate final String name;\n\n\t/**\n\t * Constructs a new project.\n\t * \n\t * @param code the proje... | import nl.rrd.senseeact.client.project.BaseProject;
import nl.rrd.senseeact.client.project.ProjectRepository;
import nl.rrd.senseeact.exampleclient.project.defaultproject.DefaultProject;
import java.util.List; | 2,117 | package nl.rrd.senseeact.exampleclient.project;
public class ExampleProjectRepository extends ProjectRepository {
@Override | package nl.rrd.senseeact.exampleclient.project;
public class ExampleProjectRepository extends ProjectRepository {
@Override | protected List<BaseProject> createProjects() { | 0 | 2023-10-24 09:36:50+00:00 | 4k |
Spectrum3847/SpectrumTraining | src/main/java/frc/spectrumLib/swerve/SimDrivetrain.java | [
{
"identifier": "ModuleConfig",
"path": "src/main/java/frc/spectrumLib/swerve/config/ModuleConfig.java",
"snippet": "public class ModuleConfig {\n public enum SwerveModuleSteerFeedbackType {\n RemoteCANcoder,\n FusedCANcoder,\n SyncCANcoder,\n }\n\n /** CAN ID of the drive ... | import com.ctre.phoenix6.hardware.Pigeon2;
import com.ctre.phoenix6.sim.CANcoderSimState;
import com.ctre.phoenix6.sim.Pigeon2SimState;
import com.ctre.phoenix6.sim.TalonFXSimState;
import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.math.geometry.Translation2d;
import edu.wpi.first.math.geometry.Twist2d;
import edu.wpi.first.math.kinematics.SwerveDriveKinematics;
import edu.wpi.first.math.kinematics.SwerveModulePosition;
import edu.wpi.first.math.system.plant.DCMotor;
import edu.wpi.first.wpilibj.simulation.DCMotorSim;
import frc.spectrumLib.swerve.config.ModuleConfig;
import frc.spectrumLib.swerve.config.SwerveConfig; | 2,761 | package frc.spectrumLib.swerve;
/**
* Extremely simplified swerve drive simulation class.
*
* <p>This class assumes that the swerve drive is perfect, meaning that there is no scrub and the
* wheels do not slip.
*
* <p>In addition, it assumes the inertia of the robot is governed only by the inertia of the steer
* module and the individual drive wheels. Robot-wide inertia is not accounted for, and neither is
* translational vs rotational inertia of the robot.
*
* <p>These assumptions provide a simplified example that can demonstrate the behavior of a swerve
* drive in simulation. Users are encouraged to expand this model for their own use.
*/
public class SimDrivetrain {
public class SimSwerveModule {
/* Reference to motor simulation for the steer motor */
public final DCMotorSim SteerMotor;
/* Reference to motor simulation for drive motor */
public final DCMotorSim DriveMotor;
/* Refernece to steer gearing for updating CANcoder */
public final double SteerGearing;
/* Refernece to steer gearing for updating CANcoder */
public final double DriveGearing;
public SimSwerveModule(
double steerGearing,
double steerInertia,
double driveGearing,
double driveInertia) {
SteerMotor = new DCMotorSim(DCMotor.getFalcon500(1), steerGearing, steerInertia);
DriveMotor = new DCMotorSim(DCMotor.getFalcon500(1), driveGearing, driveInertia);
SteerGearing = steerGearing;
DriveGearing = driveGearing;
}
}
public final Pigeon2SimState PigeonSim;
protected final SimSwerveModule[] m_modules;
protected final SwerveModulePosition[] m_lastPositions;
private final int ModuleCount;
public final SwerveDriveKinematics Kinem;
public Rotation2d LastAngle = new Rotation2d();
public SimDrivetrain(
Translation2d[] wheelLocations,
Pigeon2 pigeon, | package frc.spectrumLib.swerve;
/**
* Extremely simplified swerve drive simulation class.
*
* <p>This class assumes that the swerve drive is perfect, meaning that there is no scrub and the
* wheels do not slip.
*
* <p>In addition, it assumes the inertia of the robot is governed only by the inertia of the steer
* module and the individual drive wheels. Robot-wide inertia is not accounted for, and neither is
* translational vs rotational inertia of the robot.
*
* <p>These assumptions provide a simplified example that can demonstrate the behavior of a swerve
* drive in simulation. Users are encouraged to expand this model for their own use.
*/
public class SimDrivetrain {
public class SimSwerveModule {
/* Reference to motor simulation for the steer motor */
public final DCMotorSim SteerMotor;
/* Reference to motor simulation for drive motor */
public final DCMotorSim DriveMotor;
/* Refernece to steer gearing for updating CANcoder */
public final double SteerGearing;
/* Refernece to steer gearing for updating CANcoder */
public final double DriveGearing;
public SimSwerveModule(
double steerGearing,
double steerInertia,
double driveGearing,
double driveInertia) {
SteerMotor = new DCMotorSim(DCMotor.getFalcon500(1), steerGearing, steerInertia);
DriveMotor = new DCMotorSim(DCMotor.getFalcon500(1), driveGearing, driveInertia);
SteerGearing = steerGearing;
DriveGearing = driveGearing;
}
}
public final Pigeon2SimState PigeonSim;
protected final SimSwerveModule[] m_modules;
protected final SwerveModulePosition[] m_lastPositions;
private final int ModuleCount;
public final SwerveDriveKinematics Kinem;
public Rotation2d LastAngle = new Rotation2d();
public SimDrivetrain(
Translation2d[] wheelLocations,
Pigeon2 pigeon, | SwerveConfig swerveConfig, | 1 | 2023-10-23 17:01:53+00:00 | 4k |
imart302/DulceNectar-BE | src/main/java/com/dulcenectar/java/controllers/ProductController.java | [
{
"identifier": "CreateProductRequestDto",
"path": "src/main/java/com/dulcenectar/java/dtos/product/CreateProductRequestDto.java",
"snippet": "public class CreateProductRequestDto implements RequestDto <Product>{\n\t\n\tprivate String name;\n\tprivate String info;\n\tprivate Float gram;\n\tprivate Strin... | import java.util.ArrayList;
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.RestController;
import com.dulcenectar.java.dtos.product.CreateProductRequestDto;
import com.dulcenectar.java.dtos.product.CreateProductResponseDto;
import com.dulcenectar.java.services.interfaces.ProductService; | 1,702 | package com.dulcenectar.java.controllers;
@RestController
@RequestMapping(path = "/product")
public class ProductController {
private final ProductService productServices;
public ProductController(ProductService productServices) {
super();
this.productServices = productServices;
}
@GetMapping() | package com.dulcenectar.java.controllers;
@RestController
@RequestMapping(path = "/product")
public class ProductController {
private final ProductService productServices;
public ProductController(ProductService productServices) {
super();
this.productServices = productServices;
}
@GetMapping() | public ResponseEntity< ArrayList <CreateProductResponseDto>> getProductsList(){ | 1 | 2023-10-24 00:07:39+00:00 | 4k |
CMarcoo/RuntimeLib | src/main/java/top/cmarco/runtimelib/RuntimeLib.java | [
{
"identifier": "RuntimeLibConfig",
"path": "src/main/java/top/cmarco/runtimelib/config/RuntimeLibConfig.java",
"snippet": "@RequiredArgsConstructor\npublic final class RuntimeLibConfig {\n\n private final RuntimeLib runtimeLib;\n private FileConfiguration configuration = null;\n\n public void ... | import lombok.Getter;
import org.bukkit.plugin.java.JavaPlugin;
import top.cmarco.runtimelib.config.RuntimeLibConfig;
import top.cmarco.runtimelib.loader.RuntimePluginDiscovery; | 1,605 | package top.cmarco.runtimelib;
/**
* The `RuntimeLib` class is a Minecraft plugin that manages the discovery, loading, and operation
* of runtime plugins within the server. It extends the `JavaPlugin` class and provides methods to
* load and manage runtime plugins, along with loading and managing its own configuration.
*
* @author Marco C.
* @version 1.0.0
* @since 15 Oct. 2023
*/
public final class RuntimeLib extends JavaPlugin {
private RuntimePluginDiscovery pluginDiscovery = null; | package top.cmarco.runtimelib;
/**
* The `RuntimeLib` class is a Minecraft plugin that manages the discovery, loading, and operation
* of runtime plugins within the server. It extends the `JavaPlugin` class and provides methods to
* load and manage runtime plugins, along with loading and managing its own configuration.
*
* @author Marco C.
* @version 1.0.0
* @since 15 Oct. 2023
*/
public final class RuntimeLib extends JavaPlugin {
private RuntimePluginDiscovery pluginDiscovery = null; | @Getter private RuntimeLibConfig runtimeLibConfig; | 0 | 2023-10-17 17:41:29+00:00 | 4k |
DaveScott99/ToyStore-JSP | src/main/java/br/com/toyStore/dao/ProductDAO.java | [
{
"identifier": "DbException",
"path": "src/main/java/br/com/toyStore/exception/DbException.java",
"snippet": "public class DbException extends RuntimeException {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic DbException(String msg) {\n\t\tsuper(msg);\n\t}\n\t\n}"
},
{
"ident... | 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 br.com.toyStore.exception.DbException;
import br.com.toyStore.model.Category;
import br.com.toyStore.model.Product;
import br.com.toyStore.util.ConnectionFactory; | 2,128 | package br.com.toyStore.dao;
public class ProductDAO {
private Connection conn;
private PreparedStatement ps;
private ResultSet rs;
private Product product;
public ProductDAO(Connection conn) {
this.conn = conn;
}
public void insert(Product product) {
try {
if (product != null) {
String SQL = "INSERT INTO TOY_STORE.PRODUCT (NAME_PRODUCT, PRICE_PRODUCT, DESCRIPTION_PRODUCT, IMAGE_NAME_PRODUCT, BRAND_PRODUCT, ID_CATEGORY) values "
+ "(?, ?, ?, ?, ?, ?)";
ps = conn.prepareStatement(SQL);
ps.setString(1, product.getName());
ps.setDouble(2, product.getPrice());
ps.setString(3, product.getDescription());
ps.setString(4, product.getImageName());
ps.setString(5, product.getBrand());
ps.setLong(6, product.getCategory().getId());
ps.executeUpdate();
}
} catch (SQLException sqle) {
throw new DbException("Erro ao inserir dados " + sqle);
} finally {
ConnectionFactory.closeStatement(ps);
}
}
public void update(Product product) {
try {
if (product != null) {
String SQL = "UPDATE TOY_STORE.PRODUCT set NAME_PRODUCT=?, PRICE_PRODUCT=?, DESCRIPTION_PRODUCT=?, IMAGE_NAME_PRODUCT=?, ID_CATEGORY=?, BRAND_PRODUCT=? WHERE ID_PRODUCT=?";
ps = conn.prepareStatement(SQL);
ps.setString(1, product.getName());
ps.setDouble(2, product.getPrice());
ps.setString(3, product.getDescription());
ps.setString(4, product.getImageName());
ps.setLong(5, product.getCategory().getId());
ps.setString(6, product.getBrand());
ps.setLong(7, product.getId());
ps.executeUpdate();
}
} catch (SQLException sqle) {
throw new DbException("Erro ao alterar dados " + sqle);
} finally {
ConnectionFactory.closeStatement(ps);
}
}
public void delete(Integer idProduct) {
try {
String SQL = "DELETE FROM TOY_STORE.PRODUCT AS PROD WHERE PROD.ID_PRODUCT =?";
ps = conn.prepareStatement(SQL);
ps.setInt(1, idProduct);
ps.executeUpdate();
} catch (SQLException sqle) {
throw new DbException("Erro ao excluir dados " + sqle);
} finally {
ConnectionFactory.closeStatement(ps);
}
}
public Product findById(int idProduct) {
try {
String SQL = "SELECT * FROM TOY_STORE.PRODUCT AS PROD INNER JOIN TOY_STORE.CATEGORY AS CAT ON PROD.ID_CATEGORY = CAT.ID_CATEGORY WHERE PROD.ID_PRODUCT =?";
ps = conn.prepareStatement(SQL);
ps.setInt(1, idProduct);
rs = ps.executeQuery();
if (rs.next()) {
long id = rs.getInt("id_product");
String name = rs.getString("name_product");
String description = rs.getString("description_product");
double price = rs.getDouble("price_product");
String image = rs.getString("image_name_product");
String brand = rs.getString("brand_product");
long idCategory = rs.getInt("id_category");
String nameCategory = rs.getString("name_category");
String imageCategory = rs.getString("image_name_category");
product = new Product();
product.setId(id);
product.setName(name);
product.setPrice(price);
product.setDescription(description);
product.setImageName(image);
product.setBrand(brand);
| package br.com.toyStore.dao;
public class ProductDAO {
private Connection conn;
private PreparedStatement ps;
private ResultSet rs;
private Product product;
public ProductDAO(Connection conn) {
this.conn = conn;
}
public void insert(Product product) {
try {
if (product != null) {
String SQL = "INSERT INTO TOY_STORE.PRODUCT (NAME_PRODUCT, PRICE_PRODUCT, DESCRIPTION_PRODUCT, IMAGE_NAME_PRODUCT, BRAND_PRODUCT, ID_CATEGORY) values "
+ "(?, ?, ?, ?, ?, ?)";
ps = conn.prepareStatement(SQL);
ps.setString(1, product.getName());
ps.setDouble(2, product.getPrice());
ps.setString(3, product.getDescription());
ps.setString(4, product.getImageName());
ps.setString(5, product.getBrand());
ps.setLong(6, product.getCategory().getId());
ps.executeUpdate();
}
} catch (SQLException sqle) {
throw new DbException("Erro ao inserir dados " + sqle);
} finally {
ConnectionFactory.closeStatement(ps);
}
}
public void update(Product product) {
try {
if (product != null) {
String SQL = "UPDATE TOY_STORE.PRODUCT set NAME_PRODUCT=?, PRICE_PRODUCT=?, DESCRIPTION_PRODUCT=?, IMAGE_NAME_PRODUCT=?, ID_CATEGORY=?, BRAND_PRODUCT=? WHERE ID_PRODUCT=?";
ps = conn.prepareStatement(SQL);
ps.setString(1, product.getName());
ps.setDouble(2, product.getPrice());
ps.setString(3, product.getDescription());
ps.setString(4, product.getImageName());
ps.setLong(5, product.getCategory().getId());
ps.setString(6, product.getBrand());
ps.setLong(7, product.getId());
ps.executeUpdate();
}
} catch (SQLException sqle) {
throw new DbException("Erro ao alterar dados " + sqle);
} finally {
ConnectionFactory.closeStatement(ps);
}
}
public void delete(Integer idProduct) {
try {
String SQL = "DELETE FROM TOY_STORE.PRODUCT AS PROD WHERE PROD.ID_PRODUCT =?";
ps = conn.prepareStatement(SQL);
ps.setInt(1, idProduct);
ps.executeUpdate();
} catch (SQLException sqle) {
throw new DbException("Erro ao excluir dados " + sqle);
} finally {
ConnectionFactory.closeStatement(ps);
}
}
public Product findById(int idProduct) {
try {
String SQL = "SELECT * FROM TOY_STORE.PRODUCT AS PROD INNER JOIN TOY_STORE.CATEGORY AS CAT ON PROD.ID_CATEGORY = CAT.ID_CATEGORY WHERE PROD.ID_PRODUCT =?";
ps = conn.prepareStatement(SQL);
ps.setInt(1, idProduct);
rs = ps.executeQuery();
if (rs.next()) {
long id = rs.getInt("id_product");
String name = rs.getString("name_product");
String description = rs.getString("description_product");
double price = rs.getDouble("price_product");
String image = rs.getString("image_name_product");
String brand = rs.getString("brand_product");
long idCategory = rs.getInt("id_category");
String nameCategory = rs.getString("name_category");
String imageCategory = rs.getString("image_name_category");
product = new Product();
product.setId(id);
product.setName(name);
product.setPrice(price);
product.setDescription(description);
product.setImageName(image);
product.setBrand(brand);
| product.setCategory(new Category(idCategory, nameCategory, imageCategory)); | 1 | 2023-10-20 02:51:14+00:00 | 4k |
Lewoaragao/filetransfer | src/main/java/com/filetransfer/controller/FileController.java | [
{
"identifier": "FileResponse",
"path": "src/main/java/com/filetransfer/response/FileResponse.java",
"snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class FileResponse {\n\n\tprivate Integer index;\n\tprivate String message;\n\tprivate String fileName;\n\n\tpublic FileRespon... | import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.filetransfer.response.FileResponse;
import com.filetransfer.response.FilesResponse;
import com.filetransfer.service.FileService;
import com.filetransfer.util.Util;
import com.filetransfer.vo.FileVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor; | 1,610 | package com.filetransfer.controller;
@RestController
@CrossOrigin("*")
@RequestMapping("/api/file")
@RequiredArgsConstructor
@Api(tags = "Operações com arquivo do tipo File")
public class FileController {
@Autowired
FileService service;
public int index = 0;
@GetMapping("/")
@ApiOperation(value = "Verificação de funcionamento do Controller")
public ResponseEntity<String> verificacaoController() {
return ResponseEntity.ok("Conferindo se o FileController está configurado corretamente!");
}
@PostMapping("/upload")
@ApiOperation(value = "Upload de um único arquivo") | package com.filetransfer.controller;
@RestController
@CrossOrigin("*")
@RequestMapping("/api/file")
@RequiredArgsConstructor
@Api(tags = "Operações com arquivo do tipo File")
public class FileController {
@Autowired
FileService service;
public int index = 0;
@GetMapping("/")
@ApiOperation(value = "Verificação de funcionamento do Controller")
public ResponseEntity<String> verificacaoController() {
return ResponseEntity.ok("Conferindo se o FileController está configurado corretamente!");
}
@PostMapping("/upload")
@ApiOperation(value = "Upload de um único arquivo") | public ResponseEntity<FileResponse> uploadFile(@RequestParam("file") MultipartFile file) throws IOException { | 0 | 2023-10-24 11:43:46+00:00 | 4k |
yallerocha/Estruturas-de-Dados-e-Algoritmos | src/main/java/com/dataStructures/avltree/countAndFill/AVLCountAndFillImpl.java | [
{
"identifier": "AVLTreeImpl",
"path": "src/main/java/com/dataStructures/avltree/AVLTreeImpl.java",
"snippet": "public class AVLTreeImpl<T extends Comparable<T>> extends BSTImpl<T> implements AVLTree<T> {\n\n\t// TODO Do not forget: you must override the methods insert and remove\n\t// conveniently.\n\n... | import java.util.*;
import com.dataStructures.avltree.AVLTreeImpl;
import com.dataStructures.binarySearchTree.BSTNode;
import com.dataStructures.binarySearchTree.binaryTree.UtilRotation; | 2,424 | package com.dataStructures.avltree.countAndFill;
public class AVLCountAndFillImpl<T extends Comparable<T>> extends AVLTreeImpl<T> implements AVLCountAndFill<T> {
private int LLcounter;
private int LRcounter;
private int RRcounter;
private int RLcounter;
public AVLCountAndFillImpl() {
this.LLcounter = 0;
this.LRcounter = 0;
this.RRcounter = 0;
this.RLcounter = 0;
}
@Override
public int LLcount() {
return LLcounter;
}
@Override
public int LRcount() {
return LRcounter;
}
@Override
public int RRcount() {
return RRcounter;
}
@Override
public int RLcount() {
return RLcounter;
}
@Override
protected void rebalance (BSTNode<T> node) {
BSTNode<T> newRoot = null;
int balance = this.calculateBalance(node);
if (Math.abs(balance) > 1) {
if (balance > 1) {
if (this.calculateBalance((BSTNode<T>) node.getLeft()) >= 0) { | package com.dataStructures.avltree.countAndFill;
public class AVLCountAndFillImpl<T extends Comparable<T>> extends AVLTreeImpl<T> implements AVLCountAndFill<T> {
private int LLcounter;
private int LRcounter;
private int RRcounter;
private int RLcounter;
public AVLCountAndFillImpl() {
this.LLcounter = 0;
this.LRcounter = 0;
this.RRcounter = 0;
this.RLcounter = 0;
}
@Override
public int LLcount() {
return LLcounter;
}
@Override
public int LRcount() {
return LRcounter;
}
@Override
public int RRcount() {
return RRcounter;
}
@Override
public int RLcount() {
return RLcounter;
}
@Override
protected void rebalance (BSTNode<T> node) {
BSTNode<T> newRoot = null;
int balance = this.calculateBalance(node);
if (Math.abs(balance) > 1) {
if (balance > 1) {
if (this.calculateBalance((BSTNode<T>) node.getLeft()) >= 0) { | newRoot = UtilRotation.rightRotation(node); | 2 | 2023-10-21 21:39:25+00:00 | 4k |
MYSTD/BigDataApiTest | data-governance-assessment/src/main/java/com/std/dga/governance/bean/AssessParam.java | [
{
"identifier": "TDsTaskDefinition",
"path": "data-governance-assessment/src/main/java/com/std/dga/dolphinscheduler/bean/TDsTaskDefinition.java",
"snippet": "@Data\n@TableName(\"t_ds_task_definition\")\npublic class TDsTaskDefinition implements Serializable {\n\n private static final long serialVersi... | import com.std.dga.dolphinscheduler.bean.TDsTaskDefinition;
import com.std.dga.dolphinscheduler.bean.TDsTaskInstance;
import com.std.dga.meta.bean.TableMetaInfo;
import lombok.Data;
import java.util.List;
import java.util.Map; | 2,478 | package com.std.dga.governance.bean;
/**
* ClassName:AssessParam
* Description:
*
* @date:2023/10/10 16:31
* @author:STD
*/
@Data
public class AssessParam {
private String assessDate ; | package com.std.dga.governance.bean;
/**
* ClassName:AssessParam
* Description:
*
* @date:2023/10/10 16:31
* @author:STD
*/
@Data
public class AssessParam {
private String assessDate ; | private TableMetaInfo tableMetaInfo ; | 2 | 2023-10-20 10:13:43+00:00 | 4k |
Jirkaach1/WooMinecraft-offline-support | src/main/java/com/plugish/woominecraft/WooMinecraft.java | [
{
"identifier": "Order",
"path": "src/main/java/com/plugish/woominecraft/pojo/Order.java",
"snippet": "public class Order {\r\n\r\n\t@SerializedName(\"player\")\r\n\t@Expose\r\n\tprivate String player;\r\n\t@SerializedName(\"order_id\")\r\n\t@Expose\r\n\tprivate Integer orderId;\r\n\t@SerializedName(\"c... | import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.plugish.woominecraft.pojo.Order;
import com.plugish.woominecraft.pojo.WMCPojo;
import com.plugish.woominecraft.pojo.WMCProcessedOrders;
import okhttp3.*;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.Sound;
| 2,395 |
package com.plugish.woominecraft;
public final class WooMinecraft extends JavaPlugin {
static WooMinecraft instance;
private YamlConfiguration l10n;
public YamlConfiguration logConfig;
private File logFile;
public static final String NL = System.getProperty("line.separator");
/**
* Stores the player data to prevent double checks.
* <p>
* i.e. name:true|false
*/
private List<String> PlayersMap = new ArrayList<>();
@Override
public void onEnable() {
instance = this;
String asciiArt =
" \n" +
" \n" +
" \n" +
" _ __ __ __ ______ ____ ____ ______\n" +
" | | / / ____ ____ / // / / ____/ __ __ ____ / __ \\ / __ \\ / ____/\n" +
" | | /| / / / __ \\ / __ \\ / // /_ / /_ / / / / / __ \\ / /_/ / / /_/ / / / __ \n" +
" | |/ |/ / / /_/ // /_/ //__ __/ / __/ / /_/ / / / / / / _, _/ / ____/ / /_/ / \n" +
" |__/|__/ \\____/ \\____/ /_/ /_/ \\__,_/ /_/ /_/ /_/ |_| /_/ \\____/\n"
+ " \n"
+ " \n"
+ " \n";
getLogger().info(asciiArt);
this.logFile = new File(this.getDataFolder(), "log.yml");
this.logConfig = YamlConfiguration.loadConfiguration(logFile);
if (this.logConfig != null) {
this.logConfig.set("loggingEnabled", true);
try {
this.logConfig.save(this.logFile);
} catch (IOException e) {
e.printStackTrace();
}
}
YamlConfiguration config = (YamlConfiguration) getConfig();
try {
saveDefaultConfig();
} catch (IllegalArgumentException e) {
getLogger().warning(e.getMessage());
}
String lang = getConfig().getString("lang");
if (lang == null) {
getLogger().warning("No default l10n set, setting to English.");
}
// Load the commands.
getCommand("woo").setExecutor(new WooCommand());
// Log when the plugin is initialized.
getLogger().info(this.getLang("log.com_init"));
BukkitRunner scheduler = new BukkitRunner(instance);
scheduler.runTaskTimerAsynchronously(instance, config.getInt( "update_interval" ) * 20, config.getInt( "update_interval" ) * 20 );
// Log when the plugin is fully enabled (setup complete).
getLogger().info(this.getLang("log.enabled"));
}
@Override
public void onDisable() {
// Disable logging on plugin shutdown
if (this.logConfig != null) {
this.logConfig.set("loggingEnabled", false);
try {
this.logConfig.save(this.logFile);
} catch (IOException e) {
e.printStackTrace();
}
}
// Log when the plugin is fully shut down.
getLogger().info(this.getLang("log.com_init"));
}
// Helper method to get localized strings
String getLang(String path) {
if (null == this.l10n) {
LangSetup lang = new LangSetup(instance);
l10n = lang.loadConfig();
}
return this.l10n.getString(path);
}
// Validates the basics needed in the config.yml file.
private void validateConfig() throws Exception {
if (1 > this.getConfig().getString("url").length()) {
throw new Exception("Server URL is empty, check config.");
} else if (this.getConfig().getString("url").equals("http://playground.dev")) {
throw new Exception("URL is still the default URL, check config.");
} else if (1 > this.getConfig().getString("key").length()) {
throw new Exception("Server Key is empty, this is insecure, check config.");
}
}
// Gets the site URL
public URL getSiteURL() throws Exception {
boolean usePrettyPermalinks = this.getConfig().getBoolean("prettyPermalinks");
String baseUrl = getConfig().getString("url") + "/wp-json/wmc/v1/server/";
if (!usePrettyPermalinks) {
baseUrl = getConfig().getString("url") + "/index.php?rest_route=/wmc/v1/server/";
String customRestUrl = this.getConfig().getString("restBasePath");
if (!customRestUrl.isEmpty()) {
baseUrl = customRestUrl;
}
}
debug_log("Checking base URL: " + baseUrl);
return new URL(baseUrl + getConfig().getString("key"));
}
// Checks all online players against the website's database looking for pending donation deliveries
boolean check() throws Exception {
// Make 100% sure the config has at least a key and url
this.validateConfig();
// Contact the server.
String pendingOrders = getPendingOrders();
debug_log("Logging website reply" + NL + pendingOrders.substring(0, Math.min(pendingOrders.length(), 64)) + "...");
// Server returned an empty response, bail here.
if (pendingOrders.isEmpty()) {
debug_log("Pending orders are completely empty", 2);
return false;
}
// Create a new object from JSON response.
Gson gson = new GsonBuilder().create();
|
package com.plugish.woominecraft;
public final class WooMinecraft extends JavaPlugin {
static WooMinecraft instance;
private YamlConfiguration l10n;
public YamlConfiguration logConfig;
private File logFile;
public static final String NL = System.getProperty("line.separator");
/**
* Stores the player data to prevent double checks.
* <p>
* i.e. name:true|false
*/
private List<String> PlayersMap = new ArrayList<>();
@Override
public void onEnable() {
instance = this;
String asciiArt =
" \n" +
" \n" +
" \n" +
" _ __ __ __ ______ ____ ____ ______\n" +
" | | / / ____ ____ / // / / ____/ __ __ ____ / __ \\ / __ \\ / ____/\n" +
" | | /| / / / __ \\ / __ \\ / // /_ / /_ / / / / / __ \\ / /_/ / / /_/ / / / __ \n" +
" | |/ |/ / / /_/ // /_/ //__ __/ / __/ / /_/ / / / / / / _, _/ / ____/ / /_/ / \n" +
" |__/|__/ \\____/ \\____/ /_/ /_/ \\__,_/ /_/ /_/ /_/ |_| /_/ \\____/\n"
+ " \n"
+ " \n"
+ " \n";
getLogger().info(asciiArt);
this.logFile = new File(this.getDataFolder(), "log.yml");
this.logConfig = YamlConfiguration.loadConfiguration(logFile);
if (this.logConfig != null) {
this.logConfig.set("loggingEnabled", true);
try {
this.logConfig.save(this.logFile);
} catch (IOException e) {
e.printStackTrace();
}
}
YamlConfiguration config = (YamlConfiguration) getConfig();
try {
saveDefaultConfig();
} catch (IllegalArgumentException e) {
getLogger().warning(e.getMessage());
}
String lang = getConfig().getString("lang");
if (lang == null) {
getLogger().warning("No default l10n set, setting to English.");
}
// Load the commands.
getCommand("woo").setExecutor(new WooCommand());
// Log when the plugin is initialized.
getLogger().info(this.getLang("log.com_init"));
BukkitRunner scheduler = new BukkitRunner(instance);
scheduler.runTaskTimerAsynchronously(instance, config.getInt( "update_interval" ) * 20, config.getInt( "update_interval" ) * 20 );
// Log when the plugin is fully enabled (setup complete).
getLogger().info(this.getLang("log.enabled"));
}
@Override
public void onDisable() {
// Disable logging on plugin shutdown
if (this.logConfig != null) {
this.logConfig.set("loggingEnabled", false);
try {
this.logConfig.save(this.logFile);
} catch (IOException e) {
e.printStackTrace();
}
}
// Log when the plugin is fully shut down.
getLogger().info(this.getLang("log.com_init"));
}
// Helper method to get localized strings
String getLang(String path) {
if (null == this.l10n) {
LangSetup lang = new LangSetup(instance);
l10n = lang.loadConfig();
}
return this.l10n.getString(path);
}
// Validates the basics needed in the config.yml file.
private void validateConfig() throws Exception {
if (1 > this.getConfig().getString("url").length()) {
throw new Exception("Server URL is empty, check config.");
} else if (this.getConfig().getString("url").equals("http://playground.dev")) {
throw new Exception("URL is still the default URL, check config.");
} else if (1 > this.getConfig().getString("key").length()) {
throw new Exception("Server Key is empty, this is insecure, check config.");
}
}
// Gets the site URL
public URL getSiteURL() throws Exception {
boolean usePrettyPermalinks = this.getConfig().getBoolean("prettyPermalinks");
String baseUrl = getConfig().getString("url") + "/wp-json/wmc/v1/server/";
if (!usePrettyPermalinks) {
baseUrl = getConfig().getString("url") + "/index.php?rest_route=/wmc/v1/server/";
String customRestUrl = this.getConfig().getString("restBasePath");
if (!customRestUrl.isEmpty()) {
baseUrl = customRestUrl;
}
}
debug_log("Checking base URL: " + baseUrl);
return new URL(baseUrl + getConfig().getString("key"));
}
// Checks all online players against the website's database looking for pending donation deliveries
boolean check() throws Exception {
// Make 100% sure the config has at least a key and url
this.validateConfig();
// Contact the server.
String pendingOrders = getPendingOrders();
debug_log("Logging website reply" + NL + pendingOrders.substring(0, Math.min(pendingOrders.length(), 64)) + "...");
// Server returned an empty response, bail here.
if (pendingOrders.isEmpty()) {
debug_log("Pending orders are completely empty", 2);
return false;
}
// Create a new object from JSON response.
Gson gson = new GsonBuilder().create();
| WMCPojo wmcPojo = gson.fromJson(pendingOrders, WMCPojo.class);
| 1 | 2023-10-17 12:56:44+00:00 | 4k |
RaulGB88/MOD-034-Microservicios-con-Java | REM20231023/demo/src/main/java/com/example/application/resources/CotillaResource.java | [
{
"identifier": "ActoresProxy",
"path": "REM20231023/demo/src/main/java/com/example/application/proxies/ActoresProxy.java",
"snippet": "public interface ActoresProxy {\n\tpublic record ActorShort(@JsonProperty(\"actorId\") int id, @Schema(description = \"Nombre del actor\") String nombre) {}\n\tpublic r... | import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
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.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;
import com.example.application.proxies.ActoresProxy;
import com.example.application.proxies.ActoresProxy.ActorEdit;
import com.example.application.proxies.ActoresProxy.ActorShort;
import com.example.application.proxies.CatalogoProxy;
import com.example.application.proxies.PhotoProxy;
import com.example.domains.entities.dtos.PelisDto;
import com.example.domains.entities.dtos.PhotoDTO;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import io.github.resilience4j.bulkhead.annotation.Bulkhead;
import io.github.resilience4j.circuitbreaker.CallNotPermittedException;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.micrometer.observation.annotation.Observed;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement; | 2,640 | rslt.add("Final: " + fin + " (" + inicio.until(fin, ChronoUnit.MILLIS) + " ms)");
return rslt;
}
@GetMapping(path = "/pelis/rt")
public List<PelisDto> getPelisRT() {
// ResponseEntity<List<PelisDto>> response = srv.exchange(
// "http://localhost:8010/peliculas/v1?mode=short",
ResponseEntity<List<PelisDto>> response = srvLB.exchange(
"lb://CATALOGO-SERVICE/peliculas/v1?mode=short",
HttpMethod.GET,
HttpEntity.EMPTY,
new ParameterizedTypeReference<List<PelisDto>>() {}
);
return response.getBody();
}
@GetMapping(path = "/pelis/{id}/rt")
public PelisDto getPelisRT(@PathVariable int id) {
return srvLB.getForObject("lb://CATALOGO-SERVICE/peliculas/v1/{key}?mode=short", PelisDto.class, id);
// return srv.getForObject("http://localhost:8010/peliculas/v1/{key}?mode=short", PelisDto.class, id);
}
@Autowired
CatalogoProxy proxy;
@GetMapping(path = "/balancea/proxy")
public List<String> getBalanceoProxy() {
List<String> rslt = new ArrayList<>();
for(int i = 0; i < 11; i++)
try {
rslt.add(proxy.getInfo());
} catch (Exception e) {
rslt.add(e.getMessage());
}
return rslt;
}
@GetMapping(path = "/pelis/proxy")
public List<PelisDto> getPelisProxy() {
return proxy.getPelis();
}
// @PreAuthorize("hasRole('ADMINISTRADORES')")
@SecurityRequirement(name = "bearerAuth")
@GetMapping(path = "/pelis/{id}/proxy")
public PelisDto getPelisProxy(@PathVariable int id) {
return proxy.getPeli(id);
}
@Autowired
private CircuitBreakerFactory cbFactory;
@GetMapping(path = "/circuit-breaker/factory")
public List<String> getCircuitBreakerFactory() {
List<String> rslt = new ArrayList<>();
LocalDateTime inicio = LocalDateTime.now();
rslt.add("Inicio: " + inicio);
for(int i = 0; i < 100; i++) {
LocalTime ini = LocalTime.now();
rslt.add(cbFactory.create("slow").run(
() -> srvLB.getForObject("lb://CATALOGO-SERVICE/actuator/info", String.class),
throwable -> "fallback: circuito abierto")
+ " (" + ini.until(LocalTime.now(), ChronoUnit.MILLIS) + " .ms)" );
}
LocalDateTime fin = LocalDateTime.now();
rslt.add("Final: " + fin + " (" + inicio.until(fin, ChronoUnit.MILLIS) + " ms)");
return rslt;
}
@GetMapping(path = "/circuit-breaker/anota")
@CircuitBreaker(name = "default", fallbackMethod = "fallback")
public List<String> getCircuitBreakerAnota() {
List<String> rslt = new ArrayList<>();
LocalDateTime inicio = LocalDateTime.now();
rslt.add("Inicio: " + inicio);
for(int i = 0; i < 100; i++)
rslt.add(getInfo(LocalTime.now()));
LocalDateTime fin = LocalDateTime.now();
rslt.add("Final: " + fin + " (" + inicio.until(fin, ChronoUnit.MILLIS) + " ms)");
return rslt;
}
@CircuitBreaker(name = "default", fallbackMethod = "fallback")
private String getInfo(LocalTime ini) {
return srvLB.getForObject("lb://CATALOGO-SERVICE/loteria", String.class)
+ " (" + ini.until(LocalTime.now(), ChronoUnit.MILLIS) + " ms)";
// return srv.getForObject("http://localhost:8010/actuator/info", String.class)
// + " (" + ini.until(LocalTime.now(), ChronoUnit.MILLIS) + " ms)";
// return srvLB.getForObject("lb://CATALOGO-SERVICE/actuator/info", String.class)
// + " (" + ini.until(LocalTime.now(), ChronoUnit.MILLIS) + " ms)";
}
private List<String> fallback(CallNotPermittedException e) {
return List.of("CircuitBreaker is open", e.getCausingCircuitBreakerName(), e.getLocalizedMessage());
}
private String fallback(LocalTime ini, CallNotPermittedException e) {
return "CircuitBreaker is open";
}
private String fallback(LocalTime ini, Exception e) {
return "Fallback: " + e.getMessage()
+ " (" + ini.until(LocalTime.now(), ChronoUnit.MILLIS) + " ms)";
}
// @org.springframework.beans.factory.annotation.Value("${server.port}")
// int port;
//
// @GetMapping(path = "/loteria", produces = {"text/plain"})
// public String getIntento() {
// if(port == 8011)
// throw new HttpServerErrorException(HttpStatusCode.valueOf(500));
// return "OK " + port;
// }
@Value("${valor.ejemplo:Valor por defecto}")
String config;
@GetMapping(path = "/config", produces = {"text/plain"})
public String getConfig() {
return config;
}
@Autowired | package com.example.application.resources;
/**
* Ejemplos de conexiones
* @author Javier
*
*/
@Observed
@RefreshScope
@RestController
@RequestMapping(path = "/cotilla")
public class CotillaResource {
@Autowired
RestTemplate srv;
@Autowired
@LoadBalanced
RestTemplate srvLB;
@Autowired
private EurekaClient discoveryEurekaClient;
@GetMapping(path = "/descubre/eureka/{nombre}")
public InstanceInfo serviceEurekaUrl(String nombre) {
InstanceInfo instance = discoveryEurekaClient.getNextServerFromEureka(nombre, false);
return instance; //.getHomePageUrl();
}
@Autowired
private DiscoveryClient discoveryClient;
@GetMapping(path = "/descubre/cloud/{nombre}")
public List<ServiceInstance> serviceUrl(String nombre) {
return discoveryClient.getInstances(nombre);
}
@GetMapping(path = "/balancea/rt")
@SecurityRequirement(name = "bearerAuth")
// @PreAuthorize("hasRole('ROLE_ADMINISTRADORES')")
public List<String> getBalanceoRT() {
List<String> rslt = new ArrayList<>();
LocalDateTime inicio = LocalDateTime.now();
rslt.add("Inicio: " + inicio);
for(int i = 0; i < 11; i++)
try {
LocalTime ini = LocalTime.now();
rslt.add(srvLB.getForObject("lb://CATALOGO-SERVICE/actuator/info", String.class)
+ " (" + ini.until(LocalTime.now(), ChronoUnit.MILLIS) + " ms)" );
} catch (Exception e) {
rslt.add(e.getMessage());
}
LocalDateTime fin = LocalDateTime.now();
rslt.add("Final: " + fin + " (" + inicio.until(fin, ChronoUnit.MILLIS) + " ms)");
return rslt;
}
@GetMapping(path = "/pelis/rt")
public List<PelisDto> getPelisRT() {
// ResponseEntity<List<PelisDto>> response = srv.exchange(
// "http://localhost:8010/peliculas/v1?mode=short",
ResponseEntity<List<PelisDto>> response = srvLB.exchange(
"lb://CATALOGO-SERVICE/peliculas/v1?mode=short",
HttpMethod.GET,
HttpEntity.EMPTY,
new ParameterizedTypeReference<List<PelisDto>>() {}
);
return response.getBody();
}
@GetMapping(path = "/pelis/{id}/rt")
public PelisDto getPelisRT(@PathVariable int id) {
return srvLB.getForObject("lb://CATALOGO-SERVICE/peliculas/v1/{key}?mode=short", PelisDto.class, id);
// return srv.getForObject("http://localhost:8010/peliculas/v1/{key}?mode=short", PelisDto.class, id);
}
@Autowired
CatalogoProxy proxy;
@GetMapping(path = "/balancea/proxy")
public List<String> getBalanceoProxy() {
List<String> rslt = new ArrayList<>();
for(int i = 0; i < 11; i++)
try {
rslt.add(proxy.getInfo());
} catch (Exception e) {
rslt.add(e.getMessage());
}
return rslt;
}
@GetMapping(path = "/pelis/proxy")
public List<PelisDto> getPelisProxy() {
return proxy.getPelis();
}
// @PreAuthorize("hasRole('ADMINISTRADORES')")
@SecurityRequirement(name = "bearerAuth")
@GetMapping(path = "/pelis/{id}/proxy")
public PelisDto getPelisProxy(@PathVariable int id) {
return proxy.getPeli(id);
}
@Autowired
private CircuitBreakerFactory cbFactory;
@GetMapping(path = "/circuit-breaker/factory")
public List<String> getCircuitBreakerFactory() {
List<String> rslt = new ArrayList<>();
LocalDateTime inicio = LocalDateTime.now();
rslt.add("Inicio: " + inicio);
for(int i = 0; i < 100; i++) {
LocalTime ini = LocalTime.now();
rslt.add(cbFactory.create("slow").run(
() -> srvLB.getForObject("lb://CATALOGO-SERVICE/actuator/info", String.class),
throwable -> "fallback: circuito abierto")
+ " (" + ini.until(LocalTime.now(), ChronoUnit.MILLIS) + " .ms)" );
}
LocalDateTime fin = LocalDateTime.now();
rslt.add("Final: " + fin + " (" + inicio.until(fin, ChronoUnit.MILLIS) + " ms)");
return rslt;
}
@GetMapping(path = "/circuit-breaker/anota")
@CircuitBreaker(name = "default", fallbackMethod = "fallback")
public List<String> getCircuitBreakerAnota() {
List<String> rslt = new ArrayList<>();
LocalDateTime inicio = LocalDateTime.now();
rslt.add("Inicio: " + inicio);
for(int i = 0; i < 100; i++)
rslt.add(getInfo(LocalTime.now()));
LocalDateTime fin = LocalDateTime.now();
rslt.add("Final: " + fin + " (" + inicio.until(fin, ChronoUnit.MILLIS) + " ms)");
return rslt;
}
@CircuitBreaker(name = "default", fallbackMethod = "fallback")
private String getInfo(LocalTime ini) {
return srvLB.getForObject("lb://CATALOGO-SERVICE/loteria", String.class)
+ " (" + ini.until(LocalTime.now(), ChronoUnit.MILLIS) + " ms)";
// return srv.getForObject("http://localhost:8010/actuator/info", String.class)
// + " (" + ini.until(LocalTime.now(), ChronoUnit.MILLIS) + " ms)";
// return srvLB.getForObject("lb://CATALOGO-SERVICE/actuator/info", String.class)
// + " (" + ini.until(LocalTime.now(), ChronoUnit.MILLIS) + " ms)";
}
private List<String> fallback(CallNotPermittedException e) {
return List.of("CircuitBreaker is open", e.getCausingCircuitBreakerName(), e.getLocalizedMessage());
}
private String fallback(LocalTime ini, CallNotPermittedException e) {
return "CircuitBreaker is open";
}
private String fallback(LocalTime ini, Exception e) {
return "Fallback: " + e.getMessage()
+ " (" + ini.until(LocalTime.now(), ChronoUnit.MILLIS) + " ms)";
}
// @org.springframework.beans.factory.annotation.Value("${server.port}")
// int port;
//
// @GetMapping(path = "/loteria", produces = {"text/plain"})
// public String getIntento() {
// if(port == 8011)
// throw new HttpServerErrorException(HttpStatusCode.valueOf(500));
// return "OK " + port;
// }
@Value("${valor.ejemplo:Valor por defecto}")
String config;
@GetMapping(path = "/config", produces = {"text/plain"})
public String getConfig() {
return config;
}
@Autowired | PhotoProxy proxyExterno; | 2 | 2023-10-24 14:35:15+00:00 | 4k |
Amir-UL-Islam/eTBManager3-Backend | src/main/java/org/msh/etbm/web/api/exceptions/ExceptionHandlingController.java | [
{
"identifier": "InvalidArgumentException",
"path": "src/main/java/org/msh/etbm/commons/InvalidArgumentException.java",
"snippet": "public class InvalidArgumentException extends RuntimeException {\n private final String property;\n private final String code;\n\n\n public InvalidArgumentExceptio... | import org.msh.etbm.commons.InvalidArgumentException;
import org.msh.etbm.commons.Messages;
import org.msh.etbm.commons.ValidationException;
import org.msh.etbm.commons.entities.EntityValidationException;
import org.msh.etbm.commons.forms.FormException;
import org.msh.etbm.services.security.ForbiddenException;
import org.msh.etbm.web.api.Message;
import org.msh.etbm.web.api.StandardResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import javax.persistence.EntityNotFoundException;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List; | 3,092 | package org.msh.etbm.web.api.exceptions;
/**
* Exception handlers to display friendly and standard messages to the client
* <p>
* Created by rmemoria on 22/8/15.
*/
@ControllerAdvice
public class ExceptionHandlingController {
@Autowired | package org.msh.etbm.web.api.exceptions;
/**
* Exception handlers to display friendly and standard messages to the client
* <p>
* Created by rmemoria on 22/8/15.
*/
@ControllerAdvice
public class ExceptionHandlingController {
@Autowired | Messages messages; | 1 | 2023-10-23 13:47:54+00:00 | 4k |
2357457057/qy-rpc | src/main/java/top/yqingyu/rpc/consumer/ProxyClassMethodExecutor.java | [
{
"identifier": "Constants",
"path": "src/main/java/top/yqingyu/rpc/Constants.java",
"snippet": "public interface Constants {\n String method = \"@\";\n String param = \"#\";\n String parameterList = \"parameterList\";\n String invokeSuccess = \"0\";\n String invokeNoSuch = \"1\";\n St... | import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.yqingyu.common.cglib.proxy.MethodInterceptor;
import top.yqingyu.common.cglib.proxy.MethodProxy;
import top.yqingyu.common.qydata.DataMap;
import top.yqingyu.common.utils.StringUtil;
import top.yqingyu.qymsg.*;
import top.yqingyu.qymsg.netty.Connection;
import top.yqingyu.rpc.Constants;
import top.yqingyu.rpc.annontation.QyRpcProducerProperties;
import top.yqingyu.rpc.exception.RemoteServerException;
import top.yqingyu.rpc.exception.RpcException;
import top.yqingyu.rpc.exception.RpcTimeOutException;
import top.yqingyu.rpc.util.RpcUtil;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap; | 1,658 | package top.yqingyu.rpc.consumer;
public class ProxyClassMethodExecutor implements MethodInterceptor {
public static final Logger logger = LoggerFactory.getLogger(ProxyClassMethodExecutor.class);
Class<?> proxyClass;
String holderName;
ConsumerHolder holder;
ConsumerHolderContext ctx;
MethodExecuteInterceptor interceptor;
ConcurrentHashMap<Method, QyRpcProducerProperties> methodPropertiesCache = new ConcurrentHashMap<>();
ConcurrentHashMap<Method, Boolean> emptyMethodPropertiesCache = new ConcurrentHashMap<>();
ConcurrentHashMap<Method, String> methodNameCache = new ConcurrentHashMap<>();
ConcurrentHashMap<Method, Object> specialMethodNameCache = new ConcurrentHashMap<>();
final static Boolean b = false;
public ProxyClassMethodExecutor(Class<?> proxyClass, String consumerName, ConsumerHolderContext ctx) {
this.proxyClass = proxyClass;
this.ctx = ctx;
holderName = consumerName;
interceptor = ctx.methodExecuteInterceptor;
}
@Override
public Object intercept(Object obj, Method method, Object[] param, MethodProxy proxy) throws Throwable {
if (holder == null) {
holder = ctx.getConsumerHolder(holderName);
if (holder == null) throw new RpcException("No consumer named {} was initialized please check", holderName);
}
interceptor.before(ctx, method, param);
Object result = specialMethodNameCache.get(method);
if (result != null) {
interceptor.completely(ctx, method, param, result);
return result;
}
String methodStrName = methodNameCache.get(method);
if (StringUtil.isEmpty(methodStrName)) {
String className = RpcUtil.getClassName(proxyClass);
String name = method.getName();
| package top.yqingyu.rpc.consumer;
public class ProxyClassMethodExecutor implements MethodInterceptor {
public static final Logger logger = LoggerFactory.getLogger(ProxyClassMethodExecutor.class);
Class<?> proxyClass;
String holderName;
ConsumerHolder holder;
ConsumerHolderContext ctx;
MethodExecuteInterceptor interceptor;
ConcurrentHashMap<Method, QyRpcProducerProperties> methodPropertiesCache = new ConcurrentHashMap<>();
ConcurrentHashMap<Method, Boolean> emptyMethodPropertiesCache = new ConcurrentHashMap<>();
ConcurrentHashMap<Method, String> methodNameCache = new ConcurrentHashMap<>();
ConcurrentHashMap<Method, Object> specialMethodNameCache = new ConcurrentHashMap<>();
final static Boolean b = false;
public ProxyClassMethodExecutor(Class<?> proxyClass, String consumerName, ConsumerHolderContext ctx) {
this.proxyClass = proxyClass;
this.ctx = ctx;
holderName = consumerName;
interceptor = ctx.methodExecuteInterceptor;
}
@Override
public Object intercept(Object obj, Method method, Object[] param, MethodProxy proxy) throws Throwable {
if (holder == null) {
holder = ctx.getConsumerHolder(holderName);
if (holder == null) throw new RpcException("No consumer named {} was initialized please check", holderName);
}
interceptor.before(ctx, method, param);
Object result = specialMethodNameCache.get(method);
if (result != null) {
interceptor.completely(ctx, method, param, result);
return result;
}
String methodStrName = methodNameCache.get(method);
if (StringUtil.isEmpty(methodStrName)) {
String className = RpcUtil.getClassName(proxyClass);
String name = method.getName();
| StringBuilder sb = new StringBuilder(className).append(Constants.method).append(name); | 0 | 2023-10-18 11:03:57+00:00 | 4k |
exagonsoft/drones-management-board-backend | src/main/java/exagonsoft/drones/service/impl/DroneServiceImpl.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 java.util.List;
import java.util.stream.Collectors;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import exagonsoft.drones.dto.BatteryLevelDto;
import exagonsoft.drones.dto.DroneDto;
import exagonsoft.drones.dto.MedicationDto;
import exagonsoft.drones.entity.Drone;
import exagonsoft.drones.entity.DroneMedications;
import exagonsoft.drones.entity.Medication;
import exagonsoft.drones.entity.Drone.StateType;
import exagonsoft.drones.exception.DuplicateSerialNumberException;
import exagonsoft.drones.exception.ResourceNotFoundException;
import exagonsoft.drones.mapper.DroneMapper;
import exagonsoft.drones.repository.DroneRepository;
import exagonsoft.drones.service.DroneMedicationService;
import exagonsoft.drones.service.DroneService;
import exagonsoft.drones.service.MedicationService;
import exagonsoft.drones.utils.UtilFunctions;
import lombok.AllArgsConstructor; | 3,230 | package exagonsoft.drones.service.impl;
@Service
@AllArgsConstructor | package exagonsoft.drones.service.impl;
@Service
@AllArgsConstructor | public class DroneServiceImpl implements DroneService { | 12 | 2023-10-16 08:32:39+00:00 | 4k |
LucassR0cha/demo-pattern-JDBC | src/model/dao/impl/SellerDaoJDBC.java | [
{
"identifier": "DB",
"path": "src/db/DB.java",
"snippet": "public class DB {\n\n\tprivate static Connection conn = null;\n\t\n\tpublic static Connection getConnection() {\n\t\tif (conn == null) {\n\t\t\ttry {\n\t\t\t\tProperties props = loadProperties();\n\t\t\t\tString url = props.getProperty(\"dburl\... | import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import db.DB;
import db.DbException;
import model.dao.SellerDao;
import model.entities.Department;
import model.entities.Seller; | 1,718 | package model.dao.impl;
public class SellerDaoJDBC implements SellerDao {
private Connection conn;
public SellerDaoJDBC(Connection conn) {
this.conn = conn;
}
@Override | package model.dao.impl;
public class SellerDaoJDBC implements SellerDao {
private Connection conn;
public SellerDaoJDBC(Connection conn) {
this.conn = conn;
}
@Override | public void insert(Seller obj) { | 4 | 2023-10-16 23:09:51+00:00 | 4k |
toel--/ocpp-backend-emulator | src/se/toel/ocpp/backendEmulator/Emulator.java | [
{
"identifier": "WebSocket",
"path": "src/org/java_websocket/WebSocket.java",
"snippet": "public interface WebSocket {\n\n /**\n * sends the closing handshake. may be send in response to an other handshake.\n *\n * @param code the closing code\n * @param message the closing message\n */\n ... | import java.net.InetSocketAddress;
import java.util.Iterator;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import se.toel.util.Dev;
import se.toel.util.FileUtils; | 1,992 | /*
* WS Emulator for the OCPP bridge
*/
package se.toel.ocpp.backendEmulator;
/**
*
* @author toel
*/
public class Emulator {
/***************************************************************************
* Constants and variables
**************************************************************************/
private final Logger log = LoggerFactory.getLogger(Emulator.class);
private final String deviceId; | /*
* WS Emulator for the OCPP bridge
*/
package se.toel.ocpp.backendEmulator;
/**
*
* @author toel
*/
public class Emulator {
/***************************************************************************
* Constants and variables
**************************************************************************/
private final Logger log = LoggerFactory.getLogger(Emulator.class);
private final String deviceId; | private final WebSocket ws; | 0 | 2023-10-16 23:10:55+00:00 | 4k |
weibocom/rill-flow | rill-flow-service/src/main/java/com/weibo/rill/flow/service/component/DAGToolConverter.java | [
{
"identifier": "TaskCategory",
"path": "rill-flow-dag/olympicene-core/src/main/java/com/weibo/rill/flow/olympicene/core/model/task/TaskCategory.java",
"snippet": "@AllArgsConstructor\n@Getter\npublic enum TaskCategory {\n // 调用函数服务的Task\n FUNCTION(\"function\", 0),\n\n // 流程控制Task,执行分支语句\n ... | import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.weibo.rill.flow.olympicene.core.model.task.TaskCategory;
import com.weibo.rill.flow.interfaces.model.task.TaskInfo;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors; | 1,920 | /*
* Copyright 2021-2023 Weibo, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.weibo.rill.flow.service.component;
public class DAGToolConverter {
private static final Map<String, String> statusMapper = ImmutableMap.of("SUCCEED", "SUCCEEDED"); | /*
* Copyright 2021-2023 Weibo, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.weibo.rill.flow.service.component;
public class DAGToolConverter {
private static final Map<String, String> statusMapper = ImmutableMap.of("SUCCEED", "SUCCEEDED"); | public static Map<String, Object> convertTaskInfo(TaskInfo taskInfo) { | 1 | 2023-11-03 03:46:01+00:00 | 4k |
Yanyutin753/fakeApiTool-One-API | rearServer/src/main/java/com/yyandywt99/fakeapitool/service/impl/apiServiceImpl.java | [
{
"identifier": "apiMapper",
"path": "rearServer/src/main/java/com/yyandywt99/fakeapitool/mapper/apiMapper.java",
"snippet": "@Mapper\npublic interface apiMapper {\n /**\n * @更新updateUrl\n * @更新oneAPi里的fakeApi调用地址\n */\n @Update(\"update channels set base_url = #{newDateUrl} where base... | import com.yyandywt99.fakeapitool.mapper.apiMapper;
import com.yyandywt99.fakeapitool.pojo.addKeyPojo;
import com.yyandywt99.fakeapitool.pojo.token;
import com.yyandywt99.fakeapitool.service.apiService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List; | 2,100 | package com.yyandywt99.fakeapitool.service.impl;
/**
* @author Yangyang
* @create 2023-11-07 14:54
*/
@Slf4j
@Service
public class apiServiceImpl implements apiService {
/**
* 拿到apiMapper,为调用做准备
*/
@Autowired
private apiMapper apiMapper;
@Value("${baseUrlWithoutPath}")
private String baseUrlWithoutPath;
// @Value("${baseUrlAutoToken}")
// private String baseUrlAutoToken;
private String session;
private String getSession(){
return this.session;
};
private void setSession(String session){
this.session = session;
}
public boolean existSession(){
if(getSession() == null || getSession().isEmpty()){
return false;
}
return true;
}
/**
*
* @param temTaken
* @return 以fk-开头的fakeApiKey
* @throws Exception
* 通过https://ai.fakeopen.com/token/register
* unique_name(apiKey名字)、access_token(token)、
* expires_i(有效期默认为0)、show_conversations(是否不隔绝对话,默认是)、
*
*/
public List<String> getKeys(token temTaken) throws Exception {
List<String> res = new ArrayList<>();
int temToken = 1;
while (temToken <= 3) {
// 替换为你的unique_name
String unique_name = temTaken.getName() + temToken;
// 请确保在Java中有token_info这个Map
String access_token = temTaken.getValue();
// 假设expires_in为0
int expires_in = 0;
boolean show_conversations = true;
String url = "https://ai.fakeopen.com/token/register";
String data = "unique_name=" + unique_name + "&access_token=" + access_token + "&expires_in=" + expires_in + "&show_conversations=" + show_conversations;
String tokenKey = "";
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为POST
con.setRequestMethod("POST");
con.setDoOutput(true);
// 发送POST数据
OutputStream os = con.getOutputStream();
os.write(data.getBytes());
os.flush();
os.close();
// 获取响应
int responseCode = con.getResponseCode();
if (responseCode == 200) {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String responseJson = response.toString();
tokenKey = new JSONObject(responseJson).getString("token_key");
} else {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String errStr = response.toString().replace("\n", "").replace("\r", "").trim();
System.out.println("share token failed: " + errStr);
return null;
}
// 使用正则表达式匹配字符串
String shareToken = tokenKey;
if (shareToken.matches("^(fk-|pk-).*")) {
log.info("open_ai_api_key has been updated to: " + shareToken);
res.add(shareToken);
}
} catch (IOException e) {
e.printStackTrace();
}
temToken ++;
}
return res;
}
/**
* 添加Key值
* 会通过Post方法访问One-Api接口/api/channel/,添加新keys
* @return "true"or"false"
*/ | package com.yyandywt99.fakeapitool.service.impl;
/**
* @author Yangyang
* @create 2023-11-07 14:54
*/
@Slf4j
@Service
public class apiServiceImpl implements apiService {
/**
* 拿到apiMapper,为调用做准备
*/
@Autowired
private apiMapper apiMapper;
@Value("${baseUrlWithoutPath}")
private String baseUrlWithoutPath;
// @Value("${baseUrlAutoToken}")
// private String baseUrlAutoToken;
private String session;
private String getSession(){
return this.session;
};
private void setSession(String session){
this.session = session;
}
public boolean existSession(){
if(getSession() == null || getSession().isEmpty()){
return false;
}
return true;
}
/**
*
* @param temTaken
* @return 以fk-开头的fakeApiKey
* @throws Exception
* 通过https://ai.fakeopen.com/token/register
* unique_name(apiKey名字)、access_token(token)、
* expires_i(有效期默认为0)、show_conversations(是否不隔绝对话,默认是)、
*
*/
public List<String> getKeys(token temTaken) throws Exception {
List<String> res = new ArrayList<>();
int temToken = 1;
while (temToken <= 3) {
// 替换为你的unique_name
String unique_name = temTaken.getName() + temToken;
// 请确保在Java中有token_info这个Map
String access_token = temTaken.getValue();
// 假设expires_in为0
int expires_in = 0;
boolean show_conversations = true;
String url = "https://ai.fakeopen.com/token/register";
String data = "unique_name=" + unique_name + "&access_token=" + access_token + "&expires_in=" + expires_in + "&show_conversations=" + show_conversations;
String tokenKey = "";
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为POST
con.setRequestMethod("POST");
con.setDoOutput(true);
// 发送POST数据
OutputStream os = con.getOutputStream();
os.write(data.getBytes());
os.flush();
os.close();
// 获取响应
int responseCode = con.getResponseCode();
if (responseCode == 200) {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String responseJson = response.toString();
tokenKey = new JSONObject(responseJson).getString("token_key");
} else {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String errStr = response.toString().replace("\n", "").replace("\r", "").trim();
System.out.println("share token failed: " + errStr);
return null;
}
// 使用正则表达式匹配字符串
String shareToken = tokenKey;
if (shareToken.matches("^(fk-|pk-).*")) {
log.info("open_ai_api_key has been updated to: " + shareToken);
res.add(shareToken);
}
} catch (IOException e) {
e.printStackTrace();
}
temToken ++;
}
return res;
}
/**
* 添加Key值
* 会通过Post方法访问One-Api接口/api/channel/,添加新keys
* @return "true"or"false"
*/ | public boolean addKey(addKeyPojo addKeyPojo) throws Exception { | 1 | 2023-11-09 08:04:54+00:00 | 4k |
aliyun/alibabacloud-compute-nest-saas-boost | boost.server/src/test/java/org/example/controller/OrderControllerTest.java | [
{
"identifier": "BaseResult",
"path": "boost.common/src/main/java/org/example/common/BaseResult.java",
"snippet": "@Data\npublic class BaseResult<T> implements Serializable {\n private static final long serialVersionUID = 5680133981298179266L;\n\n /**\n * Status code.\n */\n protected S... | import com.alipay.api.AlipayApiException;
import org.example.common.BaseResult;
import org.example.common.ListResult;
import org.example.common.dto.OrderDTO;
import org.example.common.model.UserInfoModel;
import org.example.common.param.CreateOrderParam;
import org.example.common.param.GetOrderParam;
import org.example.common.param.ListOrdersParam;
import org.example.common.param.RefundOrderParam;
import org.example.service.OrderService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.slf4j.Logger;
import java.util.Arrays;
import static org.mockito.Mockito.*; | 2,605 | /*
*Copyright (c) Alibaba Group;
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/
package org.example.controller;
class OrderControllerTest {
@Mock
OrderService orderService;
@Mock
Logger log;
@InjectMocks
OrderController orderController;
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
void testCreateOrder() throws AlipayApiException {
when(orderService.createOrder(any(), any())).thenReturn(new BaseResult<String>("code", "message", "data", "requestId"));
| /*
*Copyright (c) Alibaba Group;
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/
package org.example.controller;
class OrderControllerTest {
@Mock
OrderService orderService;
@Mock
Logger log;
@InjectMocks
OrderController orderController;
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
void testCreateOrder() throws AlipayApiException {
when(orderService.createOrder(any(), any())).thenReturn(new BaseResult<String>("code", "message", "data", "requestId"));
| BaseResult<String> result = orderController.createOrder(new UserInfoModel("sub", "name", "loginName", "aid", "uid"), new CreateOrderParam()); | 4 | 2023-11-01 08:19:34+00:00 | 4k |
softwaremill/jox | core/src/main/java/com/softwaremill/jox/Channel.java | [
{
"identifier": "CellState",
"path": "core/src/main/java/com/softwaremill/jox/Channel.java",
"snippet": "enum CellState {\n DONE,\n INTERRUPTED_SEND, // the send/receive differentiation is important for expandBuffer\n INTERRUPTED_RECEIVE,\n BROKEN,\n IN_BUFFER, // used to inform a potenti... | import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.util.Comparator;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.LockSupport;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;
import static com.softwaremill.jox.CellState.*;
import static com.softwaremill.jox.Segment.findAndMoveForward; | 2,516 | package com.softwaremill.jox;
/**
* Channel is a thread-safe data structure which exposes three basic operations:
* <p>
* - {@link Channel#send(Object)}-ing a value to the channel
* - {@link Channel#receive()}-ing a value from the channel
* - closing the channel using {@link Channel#done()} or {@link Channel#error(Throwable)}
* <p>
* There are three channel flavors:
* <p>
* - rendezvous channels, where senders and receivers must meet to exchange values
* - buffered channels, where a given number of sent elements might be buffered, before subsequent `send`s block
* - unlimited channels, where an unlimited number of elements might be buffered, hence `send` never blocks
* <p>
* The no-argument {@link Channel} constructor creates a rendezvous channel, while a buffered channel can be created
* by providing a positive integer to the constructor. A rendezvous channel behaves like a buffered channel with
* buffer size 0. An unlimited channel can be created using {@link Channel#newUnlimitedChannel()}.
* <p>
* In a rendezvous channel, senders and receivers block, until a matching party arrives (unless one is already waiting).
* Similarly, buffered channels block if the buffer is full (in case of senders), or in case of receivers, if the
* buffer is empty and there are no waiting senders.
* <p>
* All blocking operations behave properly upon interruption.
* <p>
* Channels might be closed, either because no more elements will be produced by the source (using
* {@link Channel#done()}), or because there was an error while producing or processing the received elements (using
* {@link Channel#error(Throwable)}).
* <p>
* After closing, no more elements can be sent to the channel. If the channel is "done", any pending sends will be
* completed normally. If the channel is in an "error" state, pending sends will be interrupted and will return with
* the reason for the closure.
* <p>
* In case the channel is closed, one of the {@link ChannelClosedException}s is thrown. Alternatively, you can call
* the less type-safe, but more exception-safe {@link Channel#sendSafe(Object)} and {@link Channel#receiveSafe()}
* methods, which do not throw in case the channel is closed, but return one of the {@link ChannelClosed} values.
*
* @param <T> The type of the elements processed by the channel.
*/
public final class Channel<T> {
/*
Inspired by the "Fast and Scalable Channels in Kotlin Coroutines" paper (https://arxiv.org/abs/2211.04986), and
the Kotlin implementation (https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-core/common/src/channels/BufferedChannel.kt).
Notable differences from the Kotlin implementation:
* we block (virtual) threads, instead of suspend functions
* in Kotlin's channels, the buffer stores both the elements (in even indexes), and the state for each cell (in odd
indexes). This would be also possible here, but in two-thread rendezvous tests, this is slightly slower than the
approach below: we transmit the elements inside objects representing state. This does incur an additional
allocation in case of the `Buffered` state (when there's a waiting receiver - we can't simply use a constant).
However, we add a field to `Continuation` (which is a channel-specific class, unlike in Kotlin), to avoid the
allocation when the sender suspends.
* as we don't directly store elements in the buffer, we don't need to clear them on interrupt etc. This is done
automatically when the cell's state is set to something else than a Continuation/Buffered.
* instead of the `completedExpandBuffersAndPauseFlag` counter, we maintain a counter of cells which haven't been
interrupted & processed by `expandBuffer` in each segment. The segment becomes logically removed, only once all
cells have been interrupted, processed & there are no pointers. The segment is notified that a cell is interrupted
directly from `Continuation`, and that a cell is processed after `expandBuffer` completes.
* the close procedure is a bit different - the Kotlin version does this "cooperatively", that is multiple threads
that observe that the channel is closing participate in appropriate state mutations. This doesn't seem to be
necessary in this implementation. Instead, `close()` sets the closed flag and closes the segment chain - which
constraints the number of cells to close. `send()` observes the closed status right away, `receive()` observes
it via the closed segment chain, or via closed cells. Same as in Kotlin, the cells are closed in reverse order.
All eligible cells are attempted to be closed, so it's guaranteed that each operation will observe the closing
appropriately.
Other notes:
* we need the previous pointers in segments to physically remove segments full of cells in the interrupted state.
Segments before such an interrupted segments might still hold awaiting continuations. When physically removing a
segment, we need to update the `next` pointer of the `previous` ("alive") segment. That way the memory usage is
bounded by the number of awaiting threads.
* after a `send`, if we know that R > s, or after a `receive`, when we know that S > r, we can set the `previous`
pointer in the segment to `null`, so that the previous segments can be GCd. Even if there are still ongoing
operations on these (previous) segments, and we'll end up wanting to remove such a segment, subsequent channel
operations won't use them, so the relinking won't be useful.
*/
private final int capacity;
/**
* The total number of `send` operations ever invoked, and a flag indicating if the channel is closed.
* The flag is shifted by {@link Channel#SENDERS_AND_CLOSED_FLAG_SHIFT} bits.
* <p>
* Each {@link Channel#send} invocation gets a unique cell to process.
*/
private final AtomicLong sendersAndClosedFlag = new AtomicLong(0L);
private final AtomicLong receivers = new AtomicLong(0L);
private final AtomicLong bufferEnd;
/**
* Segments holding cell states. State can be {@link CellState}, {@link Buffered}, or {@link Continuation}.
*/
private final AtomicReference<Segment> sendSegment;
private final AtomicReference<Segment> receiveSegment;
private final AtomicReference<Segment> bufferEndSegment;
private final AtomicReference<ChannelClosed> closedReason;
private final boolean isRendezvous;
private final boolean isUnlimited;
/**
* Creates a rendezvous channel.
*/
public Channel() {
this(0);
}
/**
* Creates a buffered channel (when capacity is positive), or a rendezvous channel if the capacity is 0.
*/
public Channel(int capacity) {
if (capacity < UNLIMITED_CAPACITY) {
throw new IllegalArgumentException("Capacity must be 0 (rendezvous), positive (buffered) or -1 (unlimited channels).");
}
this.capacity = capacity;
isRendezvous = capacity == 0L;
isUnlimited = capacity == UNLIMITED_CAPACITY;
var isRendezvousOrUnlimited = isRendezvous || isUnlimited;
var firstSegment = new Segment(0, null, isRendezvousOrUnlimited ? 2 : 3, isRendezvousOrUnlimited);
sendSegment = new AtomicReference<>(firstSegment);
receiveSegment = new AtomicReference<>(firstSegment);
// If the capacity is 0 or -1, buffer expansion never happens, so the buffer end segment points to a null segment,
// not the first one. This is also reflected in the pointer counter of firstSegment.
bufferEndSegment = new AtomicReference<>(isRendezvousOrUnlimited ? Segment.NULL_SEGMENT : firstSegment);
bufferEnd = new AtomicLong(capacity);
closedReason = new AtomicReference<>(null);
}
public static <T> Channel<T> newUnlimitedChannel() {
return new Channel<>(UNLIMITED_CAPACITY);
}
private static final int UNLIMITED_CAPACITY = -1;
// *******
// Sending
// *******
/**
* Send a value to the channel.
*
* @param value The value to send. Not {@code null}.
* @throws ChannelClosedException When the channel is closed.
*/
public void send(T value) throws InterruptedException {
var r = sendSafe(value);
if (r instanceof ChannelClosed c) {
throw c.toException();
}
}
/**
* Send a value to the channel. Doesn't throw exceptions when the channel is closed, but returns a value.
*
* @param value The value to send. Not {@code null}.
* @return Either {@code null}, or {@link ChannelClosed}, when the channel is closed.
*/
public Object sendSafe(T value) throws InterruptedException {
return doSend(value, null, null);
}
/**
* @return If {@code select} & {@code selectClause} is {@code null}: {@code null} when the value was sent, or
* {@link ChannelClosed}, when the channel is closed. Otherwise, might also return {@link StoredSelectClause}.
*/
private Object doSend(T value, SelectInstance select, SelectClause<?> selectClause) throws InterruptedException {
if (value == null) {
throw new NullPointerException();
}
while (true) {
// reading the segment before the counter increment - this is needed to find the required segment later
var segment = sendSegment.get();
// reserving the next cell
var scf = sendersAndClosedFlag.getAndIncrement();
if (isClosed(scf)) {
return closedReason.get();
}
var s = getSendersCounter(scf);
// calculating the segment id and the index within the segment
var id = s / Segment.SEGMENT_SIZE;
var i = (int) (s % Segment.SEGMENT_SIZE);
// check if `sendSegment` stores a previous segment, if so move the reference forward
if (segment.getId() != id) { | package com.softwaremill.jox;
/**
* Channel is a thread-safe data structure which exposes three basic operations:
* <p>
* - {@link Channel#send(Object)}-ing a value to the channel
* - {@link Channel#receive()}-ing a value from the channel
* - closing the channel using {@link Channel#done()} or {@link Channel#error(Throwable)}
* <p>
* There are three channel flavors:
* <p>
* - rendezvous channels, where senders and receivers must meet to exchange values
* - buffered channels, where a given number of sent elements might be buffered, before subsequent `send`s block
* - unlimited channels, where an unlimited number of elements might be buffered, hence `send` never blocks
* <p>
* The no-argument {@link Channel} constructor creates a rendezvous channel, while a buffered channel can be created
* by providing a positive integer to the constructor. A rendezvous channel behaves like a buffered channel with
* buffer size 0. An unlimited channel can be created using {@link Channel#newUnlimitedChannel()}.
* <p>
* In a rendezvous channel, senders and receivers block, until a matching party arrives (unless one is already waiting).
* Similarly, buffered channels block if the buffer is full (in case of senders), or in case of receivers, if the
* buffer is empty and there are no waiting senders.
* <p>
* All blocking operations behave properly upon interruption.
* <p>
* Channels might be closed, either because no more elements will be produced by the source (using
* {@link Channel#done()}), or because there was an error while producing or processing the received elements (using
* {@link Channel#error(Throwable)}).
* <p>
* After closing, no more elements can be sent to the channel. If the channel is "done", any pending sends will be
* completed normally. If the channel is in an "error" state, pending sends will be interrupted and will return with
* the reason for the closure.
* <p>
* In case the channel is closed, one of the {@link ChannelClosedException}s is thrown. Alternatively, you can call
* the less type-safe, but more exception-safe {@link Channel#sendSafe(Object)} and {@link Channel#receiveSafe()}
* methods, which do not throw in case the channel is closed, but return one of the {@link ChannelClosed} values.
*
* @param <T> The type of the elements processed by the channel.
*/
public final class Channel<T> {
/*
Inspired by the "Fast and Scalable Channels in Kotlin Coroutines" paper (https://arxiv.org/abs/2211.04986), and
the Kotlin implementation (https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-core/common/src/channels/BufferedChannel.kt).
Notable differences from the Kotlin implementation:
* we block (virtual) threads, instead of suspend functions
* in Kotlin's channels, the buffer stores both the elements (in even indexes), and the state for each cell (in odd
indexes). This would be also possible here, but in two-thread rendezvous tests, this is slightly slower than the
approach below: we transmit the elements inside objects representing state. This does incur an additional
allocation in case of the `Buffered` state (when there's a waiting receiver - we can't simply use a constant).
However, we add a field to `Continuation` (which is a channel-specific class, unlike in Kotlin), to avoid the
allocation when the sender suspends.
* as we don't directly store elements in the buffer, we don't need to clear them on interrupt etc. This is done
automatically when the cell's state is set to something else than a Continuation/Buffered.
* instead of the `completedExpandBuffersAndPauseFlag` counter, we maintain a counter of cells which haven't been
interrupted & processed by `expandBuffer` in each segment. The segment becomes logically removed, only once all
cells have been interrupted, processed & there are no pointers. The segment is notified that a cell is interrupted
directly from `Continuation`, and that a cell is processed after `expandBuffer` completes.
* the close procedure is a bit different - the Kotlin version does this "cooperatively", that is multiple threads
that observe that the channel is closing participate in appropriate state mutations. This doesn't seem to be
necessary in this implementation. Instead, `close()` sets the closed flag and closes the segment chain - which
constraints the number of cells to close. `send()` observes the closed status right away, `receive()` observes
it via the closed segment chain, or via closed cells. Same as in Kotlin, the cells are closed in reverse order.
All eligible cells are attempted to be closed, so it's guaranteed that each operation will observe the closing
appropriately.
Other notes:
* we need the previous pointers in segments to physically remove segments full of cells in the interrupted state.
Segments before such an interrupted segments might still hold awaiting continuations. When physically removing a
segment, we need to update the `next` pointer of the `previous` ("alive") segment. That way the memory usage is
bounded by the number of awaiting threads.
* after a `send`, if we know that R > s, or after a `receive`, when we know that S > r, we can set the `previous`
pointer in the segment to `null`, so that the previous segments can be GCd. Even if there are still ongoing
operations on these (previous) segments, and we'll end up wanting to remove such a segment, subsequent channel
operations won't use them, so the relinking won't be useful.
*/
private final int capacity;
/**
* The total number of `send` operations ever invoked, and a flag indicating if the channel is closed.
* The flag is shifted by {@link Channel#SENDERS_AND_CLOSED_FLAG_SHIFT} bits.
* <p>
* Each {@link Channel#send} invocation gets a unique cell to process.
*/
private final AtomicLong sendersAndClosedFlag = new AtomicLong(0L);
private final AtomicLong receivers = new AtomicLong(0L);
private final AtomicLong bufferEnd;
/**
* Segments holding cell states. State can be {@link CellState}, {@link Buffered}, or {@link Continuation}.
*/
private final AtomicReference<Segment> sendSegment;
private final AtomicReference<Segment> receiveSegment;
private final AtomicReference<Segment> bufferEndSegment;
private final AtomicReference<ChannelClosed> closedReason;
private final boolean isRendezvous;
private final boolean isUnlimited;
/**
* Creates a rendezvous channel.
*/
public Channel() {
this(0);
}
/**
* Creates a buffered channel (when capacity is positive), or a rendezvous channel if the capacity is 0.
*/
public Channel(int capacity) {
if (capacity < UNLIMITED_CAPACITY) {
throw new IllegalArgumentException("Capacity must be 0 (rendezvous), positive (buffered) or -1 (unlimited channels).");
}
this.capacity = capacity;
isRendezvous = capacity == 0L;
isUnlimited = capacity == UNLIMITED_CAPACITY;
var isRendezvousOrUnlimited = isRendezvous || isUnlimited;
var firstSegment = new Segment(0, null, isRendezvousOrUnlimited ? 2 : 3, isRendezvousOrUnlimited);
sendSegment = new AtomicReference<>(firstSegment);
receiveSegment = new AtomicReference<>(firstSegment);
// If the capacity is 0 or -1, buffer expansion never happens, so the buffer end segment points to a null segment,
// not the first one. This is also reflected in the pointer counter of firstSegment.
bufferEndSegment = new AtomicReference<>(isRendezvousOrUnlimited ? Segment.NULL_SEGMENT : firstSegment);
bufferEnd = new AtomicLong(capacity);
closedReason = new AtomicReference<>(null);
}
public static <T> Channel<T> newUnlimitedChannel() {
return new Channel<>(UNLIMITED_CAPACITY);
}
private static final int UNLIMITED_CAPACITY = -1;
// *******
// Sending
// *******
/**
* Send a value to the channel.
*
* @param value The value to send. Not {@code null}.
* @throws ChannelClosedException When the channel is closed.
*/
public void send(T value) throws InterruptedException {
var r = sendSafe(value);
if (r instanceof ChannelClosed c) {
throw c.toException();
}
}
/**
* Send a value to the channel. Doesn't throw exceptions when the channel is closed, but returns a value.
*
* @param value The value to send. Not {@code null}.
* @return Either {@code null}, or {@link ChannelClosed}, when the channel is closed.
*/
public Object sendSafe(T value) throws InterruptedException {
return doSend(value, null, null);
}
/**
* @return If {@code select} & {@code selectClause} is {@code null}: {@code null} when the value was sent, or
* {@link ChannelClosed}, when the channel is closed. Otherwise, might also return {@link StoredSelectClause}.
*/
private Object doSend(T value, SelectInstance select, SelectClause<?> selectClause) throws InterruptedException {
if (value == null) {
throw new NullPointerException();
}
while (true) {
// reading the segment before the counter increment - this is needed to find the required segment later
var segment = sendSegment.get();
// reserving the next cell
var scf = sendersAndClosedFlag.getAndIncrement();
if (isClosed(scf)) {
return closedReason.get();
}
var s = getSendersCounter(scf);
// calculating the segment id and the index within the segment
var id = s / Segment.SEGMENT_SIZE;
var i = (int) (s % Segment.SEGMENT_SIZE);
// check if `sendSegment` stores a previous segment, if so move the reference forward
if (segment.getId() != id) { | segment = findAndMoveForward(sendSegment, segment, id); | 1 | 2023-11-08 12:58:16+00:00 | 4k |
mioclient/oyvey-ported | src/main/java/me/alpha432/oyvey/manager/ColorManager.java | [
{
"identifier": "Component",
"path": "src/main/java/me/alpha432/oyvey/features/gui/Component.java",
"snippet": "public class Component\n extends Feature {\n public static int[] counter1 = new int[]{1};\n protected DrawContext context;\n private final List<Item> items = new ArrayList<>();... | import me.alpha432.oyvey.features.gui.Component;
import me.alpha432.oyvey.features.modules.client.ClickGui;
import me.alpha432.oyvey.util.ColorUtil;
import java.awt.*; | 3,289 | package me.alpha432.oyvey.manager;
public class ColorManager {
private float red = 1.0f;
private float green = 1.0f;
private float blue = 1.0f;
private float alpha = 1.0f;
private Color color = new Color(this.red, this.green, this.blue, this.alpha);
public void init() {
ClickGui ui = ClickGui.getInstance();
setColor(ui.red.getValue(), ui.green.getValue(), ui.blue.getValue(), ui.hoverAlpha.getValue());
}
public Color getColor() {
return this.color;
}
public void setColor(Color color) {
this.color = color;
}
public int getColorAsInt() { | package me.alpha432.oyvey.manager;
public class ColorManager {
private float red = 1.0f;
private float green = 1.0f;
private float blue = 1.0f;
private float alpha = 1.0f;
private Color color = new Color(this.red, this.green, this.blue, this.alpha);
public void init() {
ClickGui ui = ClickGui.getInstance();
setColor(ui.red.getValue(), ui.green.getValue(), ui.blue.getValue(), ui.hoverAlpha.getValue());
}
public Color getColor() {
return this.color;
}
public void setColor(Color color) {
this.color = color;
}
public int getColorAsInt() { | return ColorUtil.toRGBA(this.color); | 2 | 2023-11-05 18:10:28+00:00 | 4k |
Jlan45/MCCTF | src/main/java/darkflow/mcctf/MCCTF.java | [
{
"identifier": "BlockFlagCollecter",
"path": "src/main/java/darkflow/mcctf/blocks/BlockFlagCollecter.java",
"snippet": "public class BlockFlagCollecter extends Block {\n public BlockFlagCollecter() {\n super(Settings.of(Material.ICE).hardness(-1f).dropsNothing());\n }\n @Override\n p... | import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.tree.LiteralCommandNode;
import darkflow.mcctf.blocks.BlockFlagCollecter;
import darkflow.mcctf.blocks.BlockFlagGetter;
import darkflow.mcctf.commands.BroadCastCommand;
import darkflow.mcctf.commands.TestCommand;
import darkflow.mcctf.items.ItemFlag;
import darkflow.mcctf.items.ItemFlagCollecter;
import darkflow.mcctf.items.ItemFlagGetter;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.fabricmc.fabric.api.item.v1.FabricItemSettings;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
import net.fabricmc.fabric.api.object.builder.v1.block.entity.FabricBlockEntityTypeBuilder;
import net.minecraft.block.AbstractBlock;
import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraft.block.Material;
import net.minecraft.block.entity.BlockEntityType;
import net.minecraft.item.BlockItem;
import net.minecraft.stat.Stats;
import net.minecraft.util.Identifier;
import net.minecraft.util.Rarity;
import net.minecraft.util.registry.Registry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import static net.minecraft.client.render.entity.feature.TridentRiptideFeatureRenderer.BOX; | 1,694 | package darkflow.mcctf;
public class MCCTF implements ModInitializer {
/**
* Runs the mod initializer.
*/
public static final Logger LOGGER = LoggerFactory.getLogger("mcctf");
public static final ItemFlag FLAG=new ItemFlag();
public static final BlockFlagGetter FLAG_GETTER_BLOCK=new BlockFlagGetter();
public static final BlockFlagCollecter FLAG_COLLECTER_BLOCK=new BlockFlagCollecter();
public static final ItemFlagCollecter FLAG_COLLECTER_ITEM=new ItemFlagCollecter(FLAG_COLLECTER_BLOCK,new FabricItemSettings().maxCount(1));
public static final ItemFlagGetter FLAG_GETTER_ITEM=new ItemFlagGetter(FLAG_GETTER_BLOCK,new FabricItemSettings().maxCount(1));
public static final Identifier PLAYER_CONTEST_SCORE = new Identifier("mcctf", "contest_score");
@Override
public void onInitialize() {
CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> BroadCastCommand.register(dispatcher)); | package darkflow.mcctf;
public class MCCTF implements ModInitializer {
/**
* Runs the mod initializer.
*/
public static final Logger LOGGER = LoggerFactory.getLogger("mcctf");
public static final ItemFlag FLAG=new ItemFlag();
public static final BlockFlagGetter FLAG_GETTER_BLOCK=new BlockFlagGetter();
public static final BlockFlagCollecter FLAG_COLLECTER_BLOCK=new BlockFlagCollecter();
public static final ItemFlagCollecter FLAG_COLLECTER_ITEM=new ItemFlagCollecter(FLAG_COLLECTER_BLOCK,new FabricItemSettings().maxCount(1));
public static final ItemFlagGetter FLAG_GETTER_ITEM=new ItemFlagGetter(FLAG_GETTER_BLOCK,new FabricItemSettings().maxCount(1));
public static final Identifier PLAYER_CONTEST_SCORE = new Identifier("mcctf", "contest_score");
@Override
public void onInitialize() {
CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> BroadCastCommand.register(dispatcher)); | CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> TestCommand.register(dispatcher)); | 2 | 2023-11-01 14:11:07+00:00 | 4k |
EB-wilson/TooManyItems | src/main/java/tmi/recipe/parser/DrillParser.java | [
{
"identifier": "Recipe",
"path": "src/main/java/tmi/recipe/Recipe.java",
"snippet": "public class Recipe {\n private static final EffFunc ONE_BASE = getDefaultEff(1);\n private static final EffFunc ZERO_BASE = getDefaultEff(0);\n\n /**该配方的类型,请参阅{@link RecipeType}*/\n public final RecipeType recipeT... | import arc.math.Mathf;
import arc.struct.ObjectMap;
import arc.struct.ObjectSet;
import arc.struct.Seq;
import arc.util.Strings;
import mindustry.Vars;
import mindustry.core.UI;
import mindustry.type.Item;
import mindustry.world.Block;
import mindustry.world.blocks.environment.Floor;
import mindustry.world.blocks.environment.OreBlock;
import mindustry.world.blocks.production.Drill;
import mindustry.world.consumers.Consume;
import mindustry.world.consumers.ConsumeLiquidBase;
import mindustry.world.meta.StatUnit;
import tmi.recipe.Recipe;
import tmi.recipe.RecipeType;
import static tmi.util.Consts.markerTile; | 3,185 | package tmi.recipe.parser;
public class DrillParser extends ConsumerParser<Drill>{
protected ObjectSet<Floor> itemDrops = new ObjectSet<>();
@Override
public void init() {
for (Block block : Vars.content.blocks()) {
if (block instanceof Floor f && f.itemDrop != null && !f.wallOre) itemDrops.add(f);
}
}
@Override
public boolean isTarget(Block content) {
return content instanceof Drill;
}
@Override | package tmi.recipe.parser;
public class DrillParser extends ConsumerParser<Drill>{
protected ObjectSet<Floor> itemDrops = new ObjectSet<>();
@Override
public void init() {
for (Block block : Vars.content.blocks()) {
if (block instanceof Floor f && f.itemDrop != null && !f.wallOre) itemDrops.add(f);
}
}
@Override
public boolean isTarget(Block content) {
return content instanceof Drill;
}
@Override | public Seq<Recipe> parse(Drill content) { | 0 | 2023-11-05 11:39:21+00:00 | 4k |
dulaiduwang003/DeepSee | microservices/ts-drawing/src/main/java/com/cn/listener/SdTaskListener.java | [
{
"identifier": "PoolCommon",
"path": "microservices/ts-drawing/src/main/java/com/cn/common/PoolCommon.java",
"snippet": "@Component\n@RequiredArgsConstructor\npublic class PoolCommon {\n\n\n private final PoolDefaultConfiguration configuration;\n public static final PoolStructure STRUCTURE = new ... | import com.alibaba.fastjson.JSONObject;
import com.cn.common.PoolCommon;
import com.cn.common.SdCommon;
import com.cn.constant.DrawingConstant;
import com.cn.constant.DrawingStatusConstant;
import com.cn.entity.TsGenerateDrawing;
import com.cn.enums.DrawingTypeEnum;
import com.cn.enums.FileEnum;
import com.cn.mapper.TsGenerateDrawingMapper;
import com.cn.model.SdModel;
import com.cn.structure.TaskStructure;
import com.cn.utils.UploadUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; | 2,289 | package com.cn.listener;
@Slf4j
@Transactional(rollbackFor = Exception.class)
@RequiredArgsConstructor
@SuppressWarnings("all")
@Configuration
public class SdTaskListener {
private final RedisTemplate<String, Object> redisTemplate;
private final WebClient.Builder webClient;
private Semaphore semaphore;
private final ThreadPoolExecutor threadPoolExecutor;
| package com.cn.listener;
@Slf4j
@Transactional(rollbackFor = Exception.class)
@RequiredArgsConstructor
@SuppressWarnings("all")
@Configuration
public class SdTaskListener {
private final RedisTemplate<String, Object> redisTemplate;
private final WebClient.Builder webClient;
private Semaphore semaphore;
private final ThreadPoolExecutor threadPoolExecutor;
| private final UploadUtil uploadUtil; | 10 | 2023-11-05 16:26:39+00:00 | 4k |
ewolff/microservice-spring | microservice-spring-demo/microservice-spring-order/src/test/java/com/ewolff/microservice/order/logic/OrderWebIntegrationTest.java | [
{
"identifier": "OrderApp",
"path": "microservice-spring-demo/microservice-spring-order/src/main/java/com/ewolff/microservice/order/OrderApp.java",
"snippet": "@SpringBootApplication\npublic class OrderApp {\n\t\n\tprivate CustomerTestDataGenerator customerTestDataGenerator;\n\tprivate ItemTestDataGener... | import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.stream.StreamSupport;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import com.ewolff.microservice.order.OrderApp;
import com.ewolff.microservice.order.customer.Customer;
import com.ewolff.microservice.order.customer.CustomerRepository;
import com.ewolff.microservice.order.item.Item;
import com.ewolff.microservice.order.item.ItemRepository; | 2,079 | package com.ewolff.microservice.order.logic;
@SpringBootTest(classes = OrderApp.class, webEnvironment = WebEnvironment.DEFINED_PORT)
@ActiveProfiles("test")
@TestInstance(Lifecycle.PER_CLASS)
class OrderWebIntegrationTest {
private RestTemplate restTemplate = new RestTemplate();
@LocalServerPort
private long serverPort;
@Autowired | package com.ewolff.microservice.order.logic;
@SpringBootTest(classes = OrderApp.class, webEnvironment = WebEnvironment.DEFINED_PORT)
@ActiveProfiles("test")
@TestInstance(Lifecycle.PER_CLASS)
class OrderWebIntegrationTest {
private RestTemplate restTemplate = new RestTemplate();
@LocalServerPort
private long serverPort;
@Autowired | private ItemRepository itemRepository; | 4 | 2023-11-03 17:36:15+00:00 | 4k |
LaughingMuffin/apk-killer-java-mod-menu | app/src/main/java/com/muffin/whale/xposed/XposedBridge.java | [
{
"identifier": "WhaleRuntime",
"path": "app/src/main/java/com/muffin/whale/WhaleRuntime.java",
"snippet": "public class WhaleRuntime {\n private static String getShorty(Member member) {\n return VMHelper.getShorty(member);\n }\n\n public static long[] countInstancesOfClasses(Class[] cla... | import android.util.Log;
import com.muffin.whale.WhaleRuntime;
import com.muffin.whale.xposed.XC_MethodHook.MethodHookParam;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map; | 2,918 | package com.muffin.whale.xposed;
/**
* This class contains most of Xposed's central logic, such as initialization and callbacks used by
* the native side. It also includes methods to add new hooks.
* <p>
* Latest Update 2018/04/20
*/
@SuppressWarnings("WeakerAccess")
public final class XposedBridge {
/**
* The system class loader which can be used to locate Android framework classes.
* Application classes cannot be retrieved from it.
*
* @see ClassLoader#getSystemClassLoader
*/
@SuppressWarnings("unused")
public static final ClassLoader BOOTCLASSLOADER = ClassLoader.getSystemClassLoader();
public static final String TAG = "Whale-Buildin-Xposed";
/*package*/ static boolean disableHooks = false;
private static final Object[] EMPTY_ARRAY = new Object[0];
// built-in handlers
private static final Map<Member, CopyOnWriteSortedSet<XC_MethodHook>> sHookedMethodCallbacks = new HashMap<>();
private static final Map<Member, Long> sHookedMethodSlotMap = new HashMap<>();
/**
* Writes a message to the logcat error log.
*
* @param text The log message.
*/
@SuppressWarnings("unused")
public static void log(final String text) {
Log.i(TAG, text);
}
/**
* Logs a stack trace to the logcat error log.
*
* @param t The Throwable object for the stack trace.
*/
public static void log(final Throwable t) {
Log.e(TAG, Log.getStackTraceString(t));
}
/**
* Hook any method (or constructor) with the specified callback. See below for some wrappers
* that make it easier to find a method/constructor in one step.
*
* @param hookMethod The method to be hooked.
* @param callback The callback to be executed when the hooked method is called.
* @return An object that can be used to remove the hook.
* @see XposedHelpers#findAndHookMethod(String, ClassLoader, String, Object...)
* @see XposedHelpers#findAndHookMethod(Class, String, Object...)
* @see #hookAllMethods
* @see XposedHelpers#findAndHookConstructor(String, ClassLoader, Object...)
* @see XposedHelpers#findAndHookConstructor(Class, Object...)
* @see #hookAllConstructors
*/
public static XC_MethodHook.Unhook hookMethod(final Member hookMethod, final XC_MethodHook callback) {
if (!(hookMethod instanceof Method) && !(hookMethod instanceof Constructor<?>)) {
throw new IllegalArgumentException("Only methods and constructors can be hooked: " + hookMethod.toString());
} else if (hookMethod.getDeclaringClass().isInterface()) {
throw new IllegalArgumentException("Cannot hook interfaces: " + hookMethod.toString());
} else if (Modifier.isAbstract(hookMethod.getModifiers())) {
throw new IllegalArgumentException("Cannot hook abstract methods: " + hookMethod.toString());
}
boolean newMethod = false;
CopyOnWriteSortedSet<XC_MethodHook> callbacks;
synchronized (sHookedMethodCallbacks) {
callbacks = sHookedMethodCallbacks.get(hookMethod);
if (callbacks == null) {
callbacks = new CopyOnWriteSortedSet<>();
sHookedMethodCallbacks.put(hookMethod, callbacks);
newMethod = true;
}
}
callbacks.add(callback);
if (newMethod) {
XposedHelpers.resolveStaticMethod(hookMethod);
AdditionalHookInfo additionalInfo = new AdditionalHookInfo(callbacks);
long slot = WhaleRuntime.hookMethodNative(hookMethod.getDeclaringClass(), hookMethod, additionalInfo);
if (slot <= 0) {
throw new IllegalStateException("Failed to hook method: " + hookMethod);
}
synchronized (sHookedMethodSlotMap) {
sHookedMethodSlotMap.put(hookMethod, slot);
}
}
return callback.new Unhook(hookMethod);
}
/**
* Removes the callback for a hooked method/constructor.
*
* @param hookMethod The method for which the callback should be removed.
* @param callback The reference to the callback as specified in {@link #hookMethod}.
*/
@SuppressWarnings("all")
public static void unhookMethod(final Member hookMethod, final XC_MethodHook callback) {
synchronized (sHookedMethodSlotMap) {
sHookedMethodSlotMap.remove(hookMethod);
}
CopyOnWriteSortedSet<XC_MethodHook> callbacks;
synchronized (sHookedMethodCallbacks) {
callbacks = sHookedMethodCallbacks.get(hookMethod);
if (callbacks == null)
return;
}
callbacks.remove(callback);
}
/**
* Hooks all methods that were declared in the specified class. Inherited
* methods and constructors are not considered. For constructors, use
* {@link #hookAllConstructors} instead.
* <p>
* AndHook extension function.
*
* @param hookClass The class to check for declared methods.
* @param callback The callback to be executed when the hooked methods are called.
* @return A set containing one object for each found method which can be used to unhook it.
*/
@SuppressWarnings("all")
public static HashSet<XC_MethodHook.Unhook> hookAllMethods(final Class<?> hookClass,
final XC_MethodHook callback) {
final HashSet<XC_MethodHook.Unhook> unhooks = new HashSet<>();
for (final Member method : hookClass.getDeclaredMethods())
unhooks.add(hookMethod(method, callback));
return unhooks;
}
/**
* Hooks all methods with a certain name that were declared in the specified class. Inherited
* methods and constructors are not considered. For constructors, use
* {@link #hookAllConstructors} instead.
*
* @param hookClass The class to check for declared methods.
* @param methodName The name of the method(s) to hook.
* @param callback The callback to be executed when the hooked methods are called.
* @return A set containing one object for each found method which can be used to unhook it.
*/
@SuppressWarnings("all")
public static HashSet<XC_MethodHook.Unhook> hookAllMethods(final Class<?> hookClass,
final String methodName,
final XC_MethodHook callback) {
final HashSet<XC_MethodHook.Unhook> unhooks = new HashSet<>();
for (final Member method : hookClass.getDeclaredMethods())
if (method.getName().equals(methodName))
unhooks.add(hookMethod(method, callback));
return unhooks;
}
/**
* Hook all constructors of the specified class.
*
* @param hookClass The class to check for constructors.
* @param callback The callback to be executed when the hooked constructors are called.
* @return A set containing one object for each found constructor which can be used to unhook it.
*/
@SuppressWarnings("all")
public static HashSet<XC_MethodHook.Unhook> hookAllConstructors(final Class<?> hookClass,
final XC_MethodHook callback) {
final HashSet<XC_MethodHook.Unhook> unhooks = new HashSet<>();
for (final Member constructor : hookClass.getDeclaredConstructors())
unhooks.add(hookMethod(constructor, callback));
return unhooks;
}
/**
* This method is called as a replacement for hooked methods.
*/
public static Object handleHookedMethod(Member method, long slot, Object additionalInfoObj,
Object thisObject, Object[] args) throws Throwable {
AdditionalHookInfo additionalInfo = (AdditionalHookInfo) additionalInfoObj;
if (disableHooks) {
try {
return invokeOriginalMethod(slot, thisObject, args);
} catch (InvocationTargetException e) {
throw e.getCause();
}
}
Object[] callbacksSnapshot = additionalInfo.callbacks.getSnapshot();
final int callbacksLength = callbacksSnapshot.length;
if (callbacksLength == 0) {
try {
return invokeOriginalMethod(slot, thisObject, args);
} catch (InvocationTargetException e) {
throw e.getCause();
}
}
| package com.muffin.whale.xposed;
/**
* This class contains most of Xposed's central logic, such as initialization and callbacks used by
* the native side. It also includes methods to add new hooks.
* <p>
* Latest Update 2018/04/20
*/
@SuppressWarnings("WeakerAccess")
public final class XposedBridge {
/**
* The system class loader which can be used to locate Android framework classes.
* Application classes cannot be retrieved from it.
*
* @see ClassLoader#getSystemClassLoader
*/
@SuppressWarnings("unused")
public static final ClassLoader BOOTCLASSLOADER = ClassLoader.getSystemClassLoader();
public static final String TAG = "Whale-Buildin-Xposed";
/*package*/ static boolean disableHooks = false;
private static final Object[] EMPTY_ARRAY = new Object[0];
// built-in handlers
private static final Map<Member, CopyOnWriteSortedSet<XC_MethodHook>> sHookedMethodCallbacks = new HashMap<>();
private static final Map<Member, Long> sHookedMethodSlotMap = new HashMap<>();
/**
* Writes a message to the logcat error log.
*
* @param text The log message.
*/
@SuppressWarnings("unused")
public static void log(final String text) {
Log.i(TAG, text);
}
/**
* Logs a stack trace to the logcat error log.
*
* @param t The Throwable object for the stack trace.
*/
public static void log(final Throwable t) {
Log.e(TAG, Log.getStackTraceString(t));
}
/**
* Hook any method (or constructor) with the specified callback. See below for some wrappers
* that make it easier to find a method/constructor in one step.
*
* @param hookMethod The method to be hooked.
* @param callback The callback to be executed when the hooked method is called.
* @return An object that can be used to remove the hook.
* @see XposedHelpers#findAndHookMethod(String, ClassLoader, String, Object...)
* @see XposedHelpers#findAndHookMethod(Class, String, Object...)
* @see #hookAllMethods
* @see XposedHelpers#findAndHookConstructor(String, ClassLoader, Object...)
* @see XposedHelpers#findAndHookConstructor(Class, Object...)
* @see #hookAllConstructors
*/
public static XC_MethodHook.Unhook hookMethod(final Member hookMethod, final XC_MethodHook callback) {
if (!(hookMethod instanceof Method) && !(hookMethod instanceof Constructor<?>)) {
throw new IllegalArgumentException("Only methods and constructors can be hooked: " + hookMethod.toString());
} else if (hookMethod.getDeclaringClass().isInterface()) {
throw new IllegalArgumentException("Cannot hook interfaces: " + hookMethod.toString());
} else if (Modifier.isAbstract(hookMethod.getModifiers())) {
throw new IllegalArgumentException("Cannot hook abstract methods: " + hookMethod.toString());
}
boolean newMethod = false;
CopyOnWriteSortedSet<XC_MethodHook> callbacks;
synchronized (sHookedMethodCallbacks) {
callbacks = sHookedMethodCallbacks.get(hookMethod);
if (callbacks == null) {
callbacks = new CopyOnWriteSortedSet<>();
sHookedMethodCallbacks.put(hookMethod, callbacks);
newMethod = true;
}
}
callbacks.add(callback);
if (newMethod) {
XposedHelpers.resolveStaticMethod(hookMethod);
AdditionalHookInfo additionalInfo = new AdditionalHookInfo(callbacks);
long slot = WhaleRuntime.hookMethodNative(hookMethod.getDeclaringClass(), hookMethod, additionalInfo);
if (slot <= 0) {
throw new IllegalStateException("Failed to hook method: " + hookMethod);
}
synchronized (sHookedMethodSlotMap) {
sHookedMethodSlotMap.put(hookMethod, slot);
}
}
return callback.new Unhook(hookMethod);
}
/**
* Removes the callback for a hooked method/constructor.
*
* @param hookMethod The method for which the callback should be removed.
* @param callback The reference to the callback as specified in {@link #hookMethod}.
*/
@SuppressWarnings("all")
public static void unhookMethod(final Member hookMethod, final XC_MethodHook callback) {
synchronized (sHookedMethodSlotMap) {
sHookedMethodSlotMap.remove(hookMethod);
}
CopyOnWriteSortedSet<XC_MethodHook> callbacks;
synchronized (sHookedMethodCallbacks) {
callbacks = sHookedMethodCallbacks.get(hookMethod);
if (callbacks == null)
return;
}
callbacks.remove(callback);
}
/**
* Hooks all methods that were declared in the specified class. Inherited
* methods and constructors are not considered. For constructors, use
* {@link #hookAllConstructors} instead.
* <p>
* AndHook extension function.
*
* @param hookClass The class to check for declared methods.
* @param callback The callback to be executed when the hooked methods are called.
* @return A set containing one object for each found method which can be used to unhook it.
*/
@SuppressWarnings("all")
public static HashSet<XC_MethodHook.Unhook> hookAllMethods(final Class<?> hookClass,
final XC_MethodHook callback) {
final HashSet<XC_MethodHook.Unhook> unhooks = new HashSet<>();
for (final Member method : hookClass.getDeclaredMethods())
unhooks.add(hookMethod(method, callback));
return unhooks;
}
/**
* Hooks all methods with a certain name that were declared in the specified class. Inherited
* methods and constructors are not considered. For constructors, use
* {@link #hookAllConstructors} instead.
*
* @param hookClass The class to check for declared methods.
* @param methodName The name of the method(s) to hook.
* @param callback The callback to be executed when the hooked methods are called.
* @return A set containing one object for each found method which can be used to unhook it.
*/
@SuppressWarnings("all")
public static HashSet<XC_MethodHook.Unhook> hookAllMethods(final Class<?> hookClass,
final String methodName,
final XC_MethodHook callback) {
final HashSet<XC_MethodHook.Unhook> unhooks = new HashSet<>();
for (final Member method : hookClass.getDeclaredMethods())
if (method.getName().equals(methodName))
unhooks.add(hookMethod(method, callback));
return unhooks;
}
/**
* Hook all constructors of the specified class.
*
* @param hookClass The class to check for constructors.
* @param callback The callback to be executed when the hooked constructors are called.
* @return A set containing one object for each found constructor which can be used to unhook it.
*/
@SuppressWarnings("all")
public static HashSet<XC_MethodHook.Unhook> hookAllConstructors(final Class<?> hookClass,
final XC_MethodHook callback) {
final HashSet<XC_MethodHook.Unhook> unhooks = new HashSet<>();
for (final Member constructor : hookClass.getDeclaredConstructors())
unhooks.add(hookMethod(constructor, callback));
return unhooks;
}
/**
* This method is called as a replacement for hooked methods.
*/
public static Object handleHookedMethod(Member method, long slot, Object additionalInfoObj,
Object thisObject, Object[] args) throws Throwable {
AdditionalHookInfo additionalInfo = (AdditionalHookInfo) additionalInfoObj;
if (disableHooks) {
try {
return invokeOriginalMethod(slot, thisObject, args);
} catch (InvocationTargetException e) {
throw e.getCause();
}
}
Object[] callbacksSnapshot = additionalInfo.callbacks.getSnapshot();
final int callbacksLength = callbacksSnapshot.length;
if (callbacksLength == 0) {
try {
return invokeOriginalMethod(slot, thisObject, args);
} catch (InvocationTargetException e) {
throw e.getCause();
}
}
| MethodHookParam param = new MethodHookParam(); | 1 | 2023-11-08 09:47:46+00:00 | 4k |
xsreality/spring-modulith-with-ddd | src/test/java/example/borrow/LoanIntegrationTests.java | [
{
"identifier": "Book",
"path": "src/main/java/example/borrow/book/domain/Book.java",
"snippet": "@AggregateRoot\n@Entity\n@Getter\n@NoArgsConstructor\n@Table(name = \"borrow_books\", uniqueConstraints = @UniqueConstraint(columnNames = {\"barcode\"}))\npublic class Book {\n\n @Identity\n @Id\n ... | import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.modulith.test.ApplicationModuleTest;
import org.springframework.modulith.test.Scenario;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.springframework.transaction.annotation.Transactional;
import java.time.Duration;
import example.borrow.book.domain.Book;
import example.borrow.book.domain.BookCollected;
import example.borrow.book.domain.BookPlacedOnHold;
import example.borrow.book.domain.BookRepository;
import example.borrow.book.domain.BookReturned;
import example.borrow.loan.domain.Loan.LoanStatus;
import example.borrow.loan.application.LoanManagement;
import example.catalog.BookAddedToCatalog;
import static org.assertj.core.api.Assertions.assertThat; | 1,614 | package example.borrow;
@Transactional
@ApplicationModuleTest
class LoanIntegrationTests {
@DynamicPropertySource
static void initializeData(DynamicPropertyRegistry registry) {
registry.add("spring.sql.init.data-locations", () -> "classpath:borrow.sql");
}
@Autowired | package example.borrow;
@Transactional
@ApplicationModuleTest
class LoanIntegrationTests {
@DynamicPropertySource
static void initializeData(DynamicPropertyRegistry registry) {
registry.add("spring.sql.init.data-locations", () -> "classpath:borrow.sql");
}
@Autowired | LoanManagement loans; | 3 | 2023-11-03 22:21:01+00:00 | 4k |
daominh-studio/quick-mem | app/src/main/java/com/daominh/quickmem/adapter/group/MyViewClassAdapter.java | [
{
"identifier": "ViewMembersFragment",
"path": "app/src/main/java/com/daominh/quickmem/ui/activities/classes/ViewMembersFragment.java",
"snippet": "public class ViewMembersFragment extends Fragment {\n private FragmentViewMembersBinding binding;\n private UserSharePreferences userSharePreferences;... | import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import com.daominh.quickmem.ui.activities.classes.ViewMembersFragment;
import com.daominh.quickmem.ui.activities.classes.ViewSetsFragment;
import com.daominh.quickmem.ui.fragments.library.FoldersFragment;
import com.daominh.quickmem.ui.fragments.library.MyClassesFragment;
import com.daominh.quickmem.ui.fragments.library.StudySetsFragment; | 3,101 | package com.daominh.quickmem.adapter.group;
public class MyViewClassAdapter extends FragmentStatePagerAdapter {
public MyViewClassAdapter(@NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
}
@NonNull
@Override
public Fragment getItem(int position) {
return switch (position) {
case 1 -> new ViewMembersFragment(); | package com.daominh.quickmem.adapter.group;
public class MyViewClassAdapter extends FragmentStatePagerAdapter {
public MyViewClassAdapter(@NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
}
@NonNull
@Override
public Fragment getItem(int position) {
return switch (position) {
case 1 -> new ViewMembersFragment(); | default -> new ViewSetsFragment(); | 1 | 2023-11-07 16:56:39+00:00 | 4k |
walidbosso/SpringBoot_Football_Matches | src/main/java/spring/tp/controllers/EquipeController.java | [
{
"identifier": "Joueur",
"path": "src/main/java/spring/tp/entities/Joueur.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Entity\npublic class Joueur {\n\t@Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n\tLong id;\n\tString nom;\n\tString poste;\n\n\t@ManyToOne\n\tEqui... | import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
import spring.tp.entities.Joueur;
import spring.tp.entities.Matche;
import spring.tp.entities.Equipe;
import spring.tp.services.EquipeService; | 1,898 | package spring.tp.controllers;
@RestController
public class EquipeController {
@Autowired
EquipeService es;
@PostMapping("equipe")
public Equipe addEquipe(@RequestBody Equipe e) {
return es.addEquipe(e);
}
@GetMapping("equipe")
List<Equipe> getAllEquipes(){
return es.getAllEquipes();
}
@GetMapping("equipe/{id}")
public Equipe getEquipeById(@PathVariable Long id) {
return es.getEquipeById(id);
}
//we'll add player to equipe with id in url
@PostMapping("equipe/{id}/joueur") | package spring.tp.controllers;
@RestController
public class EquipeController {
@Autowired
EquipeService es;
@PostMapping("equipe")
public Equipe addEquipe(@RequestBody Equipe e) {
return es.addEquipe(e);
}
@GetMapping("equipe")
List<Equipe> getAllEquipes(){
return es.getAllEquipes();
}
@GetMapping("equipe/{id}")
public Equipe getEquipeById(@PathVariable Long id) {
return es.getEquipeById(id);
}
//we'll add player to equipe with id in url
@PostMapping("equipe/{id}/joueur") | public Joueur addJoueurToEquipe(@PathVariable Long id, @RequestBody Joueur m) { | 0 | 2023-11-07 21:46:09+00:00 | 4k |
FRCTeam2910/2023CompetitionRobot-Public | src/main/java/org/frcteam2910/c2023/subsystems/arm/ArmIOSim.java | [
{
"identifier": "Robot",
"path": "src/main/java/org/frcteam2910/c2023/Robot.java",
"snippet": "public class Robot extends LoggedRobot {\n private RobotContainer robotContainer;\n\n private final PowerDistribution powerDistribution = new PowerDistribution();\n private final LinearFilter average ... | import edu.wpi.first.math.MathUtil;
import edu.wpi.first.math.Matrix;
import edu.wpi.first.math.VecBuilder;
import edu.wpi.first.math.controller.PIDController;
import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.math.geometry.Translation2d;
import edu.wpi.first.math.numbers.N1;
import edu.wpi.first.math.numbers.N3;
import edu.wpi.first.math.numbers.N6;
import edu.wpi.first.math.system.NumericalIntegration;
import edu.wpi.first.math.system.plant.DCMotor;
import edu.wpi.first.math.util.Units;
import org.frcteam2910.c2023.Robot;
import org.frcteam2910.c2023.util.Interpolation; | 2,412 | package org.frcteam2910.c2023.subsystems.arm;
public class ArmIOSim implements ArmIO {
private static final DCMotor SHOULDER_MOTOR = DCMotor.getFalcon500(4).withReduction(100.0);
private static final DCMotor WRIST_MOTOR = DCMotor.getFalcon500(1).withReduction(1.0);
private static final DCMotor EXTENSION_MOTOR = DCMotor.getFalcon500(2).withReduction(1.0);
private static final double SHOULDER_CURRENT_LIMIT_AMPS = 40.0;
private static final double SHOULDER_MINIMUM_MOMENT_OF_INERTIA = 1.0;
private static final double SHOULDER_MASS_KG = Units.lbsToKilograms(20);
private static final Translation2d SHOULDER_CG_OFFSET = new Translation2d();
private static final double SHOULDER_AXLE_OFFSET = 0;
private static final double EXTENSION_CURRENT_LIMIT_AMPS = 20;
private static final double EXTENSION_PULLEY_RADIUS_METERS = Units.inchesToMeters(3);
private static final double EXTENSION_MINIMUM_MOMENT_OF_INERTIA = 1.0;
private static final double EXTENSION_MAXIMUM_MOMENT_OF_INERTIA = 2.0;
private static final double EXTENSION_MINIMUM_LENGTH_METERS = Units.inchesToMeters(20);
private static final double EXTENSION_MAXIMUM_LENGTH_METERS = Units.inchesToMeters(40);
private static final double EXTENSION_MASS_KG = Units.lbsToKilograms(20);
private static final double EXTENSION_CG_OFFSET = Units.inchesToMeters(5);
private static final Translation2d EXTENSION_MINIMUM_CG = new Translation2d();
private static final Translation2d EXTENSION_MAXIMUM_CG = new Translation2d();
private static final double WRIST_CURRENT_LIMIT_AMPS = 10;
private static final double WRIST_MINIMUM_MOMENT_OF_INERTIA = 1.0;
private static final double WRIST_MASS_KG = Units.lbsToKilograms(5);
private static final Translation2d WRIST_CG_OFFSET = new Translation2d();
private static final Translation2d WRIST_AXLE_OFFSET = new Translation2d();
private final PIDController shoulderFeedback = new PIDController(1, 0, 0);
private final PIDController wristFeedback = new PIDController(1, 0, 0);
private final PIDController extensionFeedback = new PIDController(1, 0, 0);
@Override
public void updateInputs(ArmIOInputs inputs) {
Matrix<N6, N1> systemStates = VecBuilder.fill(
inputs.shoulderAngleRad,
inputs.shoulderAngularVelocityRadPerSec,
inputs.extensionPositionMeters,
inputs.extensionVelocityMetersPerSec,
inputs.wristAngleRad,
inputs.wristAngularVelocityRadPerSec);
Matrix<N3, N1> systemInputs = VecBuilder.fill(
shoulderFeedback.calculate(inputs.shoulderAngleRad),
extensionFeedback.calculate(inputs.extensionPositionMeters),
wristFeedback.calculate(inputs.wristAngleRad));
Matrix<N6, N1> nextState =
NumericalIntegration.rk4(this::calculateSystem, systemStates, systemInputs, Robot.defaultPeriodSecs);
inputs.shoulderAngleRad = nextState.get(0, 0);
inputs.shoulderAngularVelocityRadPerSec = nextState.get(1, 0);
inputs.shoulderAppliedVolts = systemInputs.get(0, 0);
inputs.shoulderCurrentDrawAmps = Math.min(
Math.abs(SHOULDER_MOTOR.getCurrent(
inputs.shoulderAngularVelocityRadPerSec, inputs.shoulderAppliedVolts)),
SHOULDER_CURRENT_LIMIT_AMPS);
inputs.extensionPositionMeters = nextState.get(2, 0);
inputs.extensionVelocityMetersPerSec = nextState.get(3, 0);
inputs.extensionAppliedVolts = systemInputs.get(1, 0);
inputs.extensionCurrentDrawAmps = Math.min(
Math.abs(
EXTENSION_MOTOR.getCurrent(inputs.extensionVelocityMetersPerSec, inputs.extensionAppliedVolts)),
EXTENSION_CURRENT_LIMIT_AMPS);
inputs.wristAngleRad = nextState.get(4, 0);
inputs.wristAngularVelocityRadPerSec = nextState.get(5, 0);
inputs.wristAppliedVolts = systemInputs.get(2, 0);
inputs.wristCurrentDrawAmps = Math.min(
Math.abs(WRIST_MOTOR.getCurrent(inputs.wristAngularVelocityRadPerSec, inputs.wristAppliedVolts)),
WRIST_CURRENT_LIMIT_AMPS);
}
private double calculateShoulderAngularMomentOfInertia(
double shoulderAngle, double extensionLength, double wristAngle) { | package org.frcteam2910.c2023.subsystems.arm;
public class ArmIOSim implements ArmIO {
private static final DCMotor SHOULDER_MOTOR = DCMotor.getFalcon500(4).withReduction(100.0);
private static final DCMotor WRIST_MOTOR = DCMotor.getFalcon500(1).withReduction(1.0);
private static final DCMotor EXTENSION_MOTOR = DCMotor.getFalcon500(2).withReduction(1.0);
private static final double SHOULDER_CURRENT_LIMIT_AMPS = 40.0;
private static final double SHOULDER_MINIMUM_MOMENT_OF_INERTIA = 1.0;
private static final double SHOULDER_MASS_KG = Units.lbsToKilograms(20);
private static final Translation2d SHOULDER_CG_OFFSET = new Translation2d();
private static final double SHOULDER_AXLE_OFFSET = 0;
private static final double EXTENSION_CURRENT_LIMIT_AMPS = 20;
private static final double EXTENSION_PULLEY_RADIUS_METERS = Units.inchesToMeters(3);
private static final double EXTENSION_MINIMUM_MOMENT_OF_INERTIA = 1.0;
private static final double EXTENSION_MAXIMUM_MOMENT_OF_INERTIA = 2.0;
private static final double EXTENSION_MINIMUM_LENGTH_METERS = Units.inchesToMeters(20);
private static final double EXTENSION_MAXIMUM_LENGTH_METERS = Units.inchesToMeters(40);
private static final double EXTENSION_MASS_KG = Units.lbsToKilograms(20);
private static final double EXTENSION_CG_OFFSET = Units.inchesToMeters(5);
private static final Translation2d EXTENSION_MINIMUM_CG = new Translation2d();
private static final Translation2d EXTENSION_MAXIMUM_CG = new Translation2d();
private static final double WRIST_CURRENT_LIMIT_AMPS = 10;
private static final double WRIST_MINIMUM_MOMENT_OF_INERTIA = 1.0;
private static final double WRIST_MASS_KG = Units.lbsToKilograms(5);
private static final Translation2d WRIST_CG_OFFSET = new Translation2d();
private static final Translation2d WRIST_AXLE_OFFSET = new Translation2d();
private final PIDController shoulderFeedback = new PIDController(1, 0, 0);
private final PIDController wristFeedback = new PIDController(1, 0, 0);
private final PIDController extensionFeedback = new PIDController(1, 0, 0);
@Override
public void updateInputs(ArmIOInputs inputs) {
Matrix<N6, N1> systemStates = VecBuilder.fill(
inputs.shoulderAngleRad,
inputs.shoulderAngularVelocityRadPerSec,
inputs.extensionPositionMeters,
inputs.extensionVelocityMetersPerSec,
inputs.wristAngleRad,
inputs.wristAngularVelocityRadPerSec);
Matrix<N3, N1> systemInputs = VecBuilder.fill(
shoulderFeedback.calculate(inputs.shoulderAngleRad),
extensionFeedback.calculate(inputs.extensionPositionMeters),
wristFeedback.calculate(inputs.wristAngleRad));
Matrix<N6, N1> nextState =
NumericalIntegration.rk4(this::calculateSystem, systemStates, systemInputs, Robot.defaultPeriodSecs);
inputs.shoulderAngleRad = nextState.get(0, 0);
inputs.shoulderAngularVelocityRadPerSec = nextState.get(1, 0);
inputs.shoulderAppliedVolts = systemInputs.get(0, 0);
inputs.shoulderCurrentDrawAmps = Math.min(
Math.abs(SHOULDER_MOTOR.getCurrent(
inputs.shoulderAngularVelocityRadPerSec, inputs.shoulderAppliedVolts)),
SHOULDER_CURRENT_LIMIT_AMPS);
inputs.extensionPositionMeters = nextState.get(2, 0);
inputs.extensionVelocityMetersPerSec = nextState.get(3, 0);
inputs.extensionAppliedVolts = systemInputs.get(1, 0);
inputs.extensionCurrentDrawAmps = Math.min(
Math.abs(
EXTENSION_MOTOR.getCurrent(inputs.extensionVelocityMetersPerSec, inputs.extensionAppliedVolts)),
EXTENSION_CURRENT_LIMIT_AMPS);
inputs.wristAngleRad = nextState.get(4, 0);
inputs.wristAngularVelocityRadPerSec = nextState.get(5, 0);
inputs.wristAppliedVolts = systemInputs.get(2, 0);
inputs.wristCurrentDrawAmps = Math.min(
Math.abs(WRIST_MOTOR.getCurrent(inputs.wristAngularVelocityRadPerSec, inputs.wristAppliedVolts)),
WRIST_CURRENT_LIMIT_AMPS);
}
private double calculateShoulderAngularMomentOfInertia(
double shoulderAngle, double extensionLength, double wristAngle) { | double t = Interpolation.inverseInterpolate( | 1 | 2023-11-03 02:12:12+00:00 | 4k |
YunaBraska/type-map | src/main/java/berlin/yuna/typemap/logic/JsonEncoder.java | [
{
"identifier": "arrayOf",
"path": "src/main/java/berlin/yuna/typemap/logic/TypeConverter.java",
"snippet": "public static <E> E[] arrayOf(final Object object, final E[] typeIndicator, final Class<E> componentType) {\n ArrayList<E> result = collectionOf(object, ArrayList::new, componentType);\n re... | import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.function.IntFunction;
import java.util.stream.Collectors;
import static berlin.yuna.typemap.logic.TypeConverter.arrayOf;
import static berlin.yuna.typemap.logic.TypeConverter.convertObj; | 1,715 | package berlin.yuna.typemap.logic;
public class JsonEncoder {
@SuppressWarnings({"java:S2386"})
public static final Map<Character, String> JSON_ESCAPE_SEQUENCES = new HashMap<>();
@SuppressWarnings({"java:S2386"})
public static final Map<String, String> JSON_UNESCAPE_SEQUENCES = new HashMap<>();
static {
JSON_ESCAPE_SEQUENCES.put('"', "\\\"");
JSON_ESCAPE_SEQUENCES.put('\\', "\\\\");
JSON_ESCAPE_SEQUENCES.put('\b', "\\b");
JSON_ESCAPE_SEQUENCES.put('\f', "\\f");
JSON_ESCAPE_SEQUENCES.put('\n', "\\n");
JSON_ESCAPE_SEQUENCES.put('\r', "\\r");
JSON_ESCAPE_SEQUENCES.put('\t', "\\t");
JSON_ESCAPE_SEQUENCES.forEach((key, value) -> JSON_UNESCAPE_SEQUENCES.put(value, key.toString()));
}
/**
* Converts any object to its JSON representation.
* This method dispatches the conversion task based on the type of the object.
* It handles Maps, Collections, Arrays (both primitive and object types),
* and other objects. If the object is null, it returns an empty JSON object ({}).
* Standalone objects are converted to JSON strings and wrapped in curly braces,
* making them single-property JSON objects.
*
* @param object The object to be converted to JSON.
* @return A JSON representation of the object as a String.
* If the object is null, returns "{}".
*/
public static String toJson(final Object object) {
if (object == null) {
return "{}";
} else if (object instanceof Map) {
return jsonOf((Map<?, ?>) object);
} else if (object instanceof Collection) {
return jsonOf((Collection<?>) object);
} else if (object.getClass().isArray()) {
return jsonOfArray(object, Object[]::new, Object.class);
} else {
return "{" + jsonify(object) + "}";
}
}
/**
* Escapes a String for JSON.
* This method replaces special characters in a String with their corresponding JSON escape sequences.
*
* @param str The string to be escaped for JSON.
* @return The escaped JSON string.
*/
public static String escapeJsonValue(final String str) {
return str == null ? null : str.chars()
.mapToObj(c -> escapeJson((char) c))
.collect(Collectors.joining());
}
/**
* Escapes a character for JSON.
* This method returns the JSON escape sequence for a given character, if necessary.
*
* @param c The character to be escaped for JSON.
* @return The escaped JSON character as a String.
*/
public static String escapeJson(final char c) {
return JSON_ESCAPE_SEQUENCES.getOrDefault(c, (c < 32 || c >= 127) ? String.format("\\u%04x", (int) c) : String.valueOf(c));
}
/**
* Unescapes a JSON string by replacing JSON escape sequences with their corresponding characters.
* <p>
* This method iterates through a predefined set of JSON escape sequences (like \" for double quotes,
* \\ for backslash, \n for newline, etc.) and replaces them in the input string with the actual characters
* they represent. The method is designed to process a JSON-encoded string and return a version with
* standard characters, making it suitable for further processing or display.
* <p>
* Note: This method assumes that the input string is a valid JSON string with correct escape sequences.
* It does not perform JSON validation.
*
* @param str The JSON string with escape sequences to be unescaped.
* @return The unescaped version of the JSON string.
*/
public static String unescapeJson(final String str) {
String result = str;
for (final Map.Entry<String, String> entry : JSON_UNESCAPE_SEQUENCES.entrySet()) {
result = result.replace(entry.getKey(), entry.getValue());
}
return result;
}
private static String jsonOf(final Map<?, ?> map) {
return map.entrySet().stream()
.map(entry -> jsonify(entry.getKey()) + ":" + jsonify(entry.getValue()))
.collect(Collectors.joining(",", "{", "}"));
}
private static String jsonOf(final Collection<?> collection) {
return collection.stream()
.map(JsonEncoder::jsonify)
.collect(Collectors.joining(",", "[", "]"));
}
@SuppressWarnings("SameParameterValue")
private static <E> String jsonOfArray(final Object object, final IntFunction<E[]> generator, final Class<E> componentType) {
return object.getClass().isArray() ? Arrays.stream(arrayOf(object, generator, componentType))
.map(JsonEncoder::jsonify)
.collect(Collectors.joining(",", "[", "]")) : "null";
}
private static String jsonify(final Object obj) {
if (obj == null) {
return "null";
} else if (obj instanceof String) {
return "\"" + escapeJsonValue((String) obj) + "\"";
} else if (obj instanceof Number || obj instanceof Boolean) {
return obj.toString();
} else if (obj instanceof Map) {
return jsonOf((Map<?, ?>) obj);
} else if (obj instanceof Collection) {
return jsonOf((Collection<?>) obj);
} else if (obj.getClass().isArray()) {
return jsonOfArray(obj, Object[]::new, Object.class);
} else { | package berlin.yuna.typemap.logic;
public class JsonEncoder {
@SuppressWarnings({"java:S2386"})
public static final Map<Character, String> JSON_ESCAPE_SEQUENCES = new HashMap<>();
@SuppressWarnings({"java:S2386"})
public static final Map<String, String> JSON_UNESCAPE_SEQUENCES = new HashMap<>();
static {
JSON_ESCAPE_SEQUENCES.put('"', "\\\"");
JSON_ESCAPE_SEQUENCES.put('\\', "\\\\");
JSON_ESCAPE_SEQUENCES.put('\b', "\\b");
JSON_ESCAPE_SEQUENCES.put('\f', "\\f");
JSON_ESCAPE_SEQUENCES.put('\n', "\\n");
JSON_ESCAPE_SEQUENCES.put('\r', "\\r");
JSON_ESCAPE_SEQUENCES.put('\t', "\\t");
JSON_ESCAPE_SEQUENCES.forEach((key, value) -> JSON_UNESCAPE_SEQUENCES.put(value, key.toString()));
}
/**
* Converts any object to its JSON representation.
* This method dispatches the conversion task based on the type of the object.
* It handles Maps, Collections, Arrays (both primitive and object types),
* and other objects. If the object is null, it returns an empty JSON object ({}).
* Standalone objects are converted to JSON strings and wrapped in curly braces,
* making them single-property JSON objects.
*
* @param object The object to be converted to JSON.
* @return A JSON representation of the object as a String.
* If the object is null, returns "{}".
*/
public static String toJson(final Object object) {
if (object == null) {
return "{}";
} else if (object instanceof Map) {
return jsonOf((Map<?, ?>) object);
} else if (object instanceof Collection) {
return jsonOf((Collection<?>) object);
} else if (object.getClass().isArray()) {
return jsonOfArray(object, Object[]::new, Object.class);
} else {
return "{" + jsonify(object) + "}";
}
}
/**
* Escapes a String for JSON.
* This method replaces special characters in a String with their corresponding JSON escape sequences.
*
* @param str The string to be escaped for JSON.
* @return The escaped JSON string.
*/
public static String escapeJsonValue(final String str) {
return str == null ? null : str.chars()
.mapToObj(c -> escapeJson((char) c))
.collect(Collectors.joining());
}
/**
* Escapes a character for JSON.
* This method returns the JSON escape sequence for a given character, if necessary.
*
* @param c The character to be escaped for JSON.
* @return The escaped JSON character as a String.
*/
public static String escapeJson(final char c) {
return JSON_ESCAPE_SEQUENCES.getOrDefault(c, (c < 32 || c >= 127) ? String.format("\\u%04x", (int) c) : String.valueOf(c));
}
/**
* Unescapes a JSON string by replacing JSON escape sequences with their corresponding characters.
* <p>
* This method iterates through a predefined set of JSON escape sequences (like \" for double quotes,
* \\ for backslash, \n for newline, etc.) and replaces them in the input string with the actual characters
* they represent. The method is designed to process a JSON-encoded string and return a version with
* standard characters, making it suitable for further processing or display.
* <p>
* Note: This method assumes that the input string is a valid JSON string with correct escape sequences.
* It does not perform JSON validation.
*
* @param str The JSON string with escape sequences to be unescaped.
* @return The unescaped version of the JSON string.
*/
public static String unescapeJson(final String str) {
String result = str;
for (final Map.Entry<String, String> entry : JSON_UNESCAPE_SEQUENCES.entrySet()) {
result = result.replace(entry.getKey(), entry.getValue());
}
return result;
}
private static String jsonOf(final Map<?, ?> map) {
return map.entrySet().stream()
.map(entry -> jsonify(entry.getKey()) + ":" + jsonify(entry.getValue()))
.collect(Collectors.joining(",", "{", "}"));
}
private static String jsonOf(final Collection<?> collection) {
return collection.stream()
.map(JsonEncoder::jsonify)
.collect(Collectors.joining(",", "[", "]"));
}
@SuppressWarnings("SameParameterValue")
private static <E> String jsonOfArray(final Object object, final IntFunction<E[]> generator, final Class<E> componentType) {
return object.getClass().isArray() ? Arrays.stream(arrayOf(object, generator, componentType))
.map(JsonEncoder::jsonify)
.collect(Collectors.joining(",", "[", "]")) : "null";
}
private static String jsonify(final Object obj) {
if (obj == null) {
return "null";
} else if (obj instanceof String) {
return "\"" + escapeJsonValue((String) obj) + "\"";
} else if (obj instanceof Number || obj instanceof Boolean) {
return obj.toString();
} else if (obj instanceof Map) {
return jsonOf((Map<?, ?>) obj);
} else if (obj instanceof Collection) {
return jsonOf((Collection<?>) obj);
} else if (obj.getClass().isArray()) {
return jsonOfArray(obj, Object[]::new, Object.class);
} else { | final String str = convertObj(obj, String.class); | 1 | 2023-11-09 14:40:13+00:00 | 4k |
estkme-group/InfiLPA | app/src/main/java/com/infineon/esim/lpa/euicc/usbreader/identive/IdentiveUSBReaderInterface.java | [
{
"identifier": "EuiccConnection",
"path": "app/src/main/java/com/infineon/esim/lpa/euicc/base/EuiccConnection.java",
"snippet": "@SuppressWarnings(\"unused\")\npublic interface EuiccConnection extends EuiccChannel {\n\n void updateEuiccConnectionSettings(EuiccConnectionSettings euiccConnectionSettin... | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.content.Context;
import com.infineon.esim.lpa.euicc.base.EuiccConnection;
import com.infineon.esim.lpa.euicc.base.EuiccInterfaceStatusChangeHandler;
import com.infineon.esim.lpa.euicc.usbreader.USBReaderConnectionBroadcastReceiver;
import com.infineon.esim.lpa.euicc.usbreader.USBReaderInterface;
import com.infineon.esim.util.Log; | 2,034 | /*
* THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON
* TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR,
* STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
* SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
*
* THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES
* RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER
* REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR
* THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME.
*
* INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR
* CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR
* ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR
* PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE
* DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION
* WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR
* PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON
* WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE.
*
* (C)Copyright INFINEON TECHNOLOGIES All rights reserved
*/
package com.infineon.esim.lpa.euicc.usbreader.identive;
final public class IdentiveUSBReaderInterface implements USBReaderInterface {
private static final String TAG = IdentiveUSBReaderInterface.class.getName();
public static final List<String> READER_NAMES = new ArrayList<>(Arrays.asList(
"SCR3500 A Contact Reader",
"Identive CLOUD 4700 F Dual Interface Reader",
"Identiv uTrust 4701 F Dual Interface Reader",
"CLOUD 2700 R Smart Card Reader"
));
private final IdentiveService identiveService;
private final List<String> euiccNames;
| /*
* THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON
* TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR,
* STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
* SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
*
* THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES
* RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER
* REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR
* THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME.
*
* INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR
* CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR
* ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR
* PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE
* DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION
* WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR
* PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON
* WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE.
*
* (C)Copyright INFINEON TECHNOLOGIES All rights reserved
*/
package com.infineon.esim.lpa.euicc.usbreader.identive;
final public class IdentiveUSBReaderInterface implements USBReaderInterface {
private static final String TAG = IdentiveUSBReaderInterface.class.getName();
public static final List<String> READER_NAMES = new ArrayList<>(Arrays.asList(
"SCR3500 A Contact Reader",
"Identive CLOUD 4700 F Dual Interface Reader",
"Identiv uTrust 4701 F Dual Interface Reader",
"CLOUD 2700 R Smart Card Reader"
));
private final IdentiveService identiveService;
private final List<String> euiccNames;
| private EuiccConnection euiccConnection; | 0 | 2023-11-06 02:41:13+00:00 | 4k |
Teleight/TeleightBots | demo/src/main/java/org/teleight/teleightbots/demo/MainDemo.java | [
{
"identifier": "TeleightBots",
"path": "src/main/java/org/teleight/teleightbots/TeleightBots.java",
"snippet": "public final class TeleightBots {\n\n private static TeleightBotsProcess teleightBotsProcess;\n\n public static @NotNull TeleightBots init() {\n updateProcess();\n return ... | import org.teleight.teleightbots.TeleightBots;
import org.teleight.teleightbots.api.methods.SendMessage;
import org.teleight.teleightbots.api.utils.ParseMode;
import org.teleight.teleightbots.bot.BotSettings;
import org.teleight.teleightbots.demo.command.Test2Command;
import org.teleight.teleightbots.demo.command.TestCommand;
import org.teleight.teleightbots.event.EventListener;
import org.teleight.teleightbots.event.bot.UpdateReceivedEvent;
import org.teleight.teleightbots.menu.Menu;
import org.teleight.teleightbots.menu.MenuButton;
import java.util.concurrent.TimeUnit; | 2,283 | package org.teleight.teleightbots.demo;
public class MainDemo {
public static void main(String[] args) {
final TeleightBots teleightBots = TeleightBots.init();
teleightBots.start();
final String botToken = System.getenv("bot.token") != null ? System.getenv("bot.token") : "--INSERT-TOKEN-HERE--";
final String botUsername = System.getenv("bot.username") != null ? System.getenv("bot.username") : "--INSERT-USERNAME--HERE";
final String chatId = System.getenv("bot.default_chatid") != null ? System.getenv("bot.default_chatid") : "--INSERT-CHATID--HERE";
final EventListener<UpdateReceivedEvent> updateEvent = EventListener.builder(UpdateReceivedEvent.class)
.handler(event -> System.out.println("UpdateReceivedEvent: " + event.bot().getBotUsername() + " -> " + event))
.build();
TeleightBots.getBotManager().registerLongPolling(botToken, botUsername, BotSettings.DEFAULT, bot -> {
System.out.println("Bot registered: " + bot.getBotUsername());
//Listener
bot.getEventManager().addListener(updateEvent);
//Commands
bot.getCommandManager().registerCommand(new TestCommand());
Menu menu = bot.createMenu((context, rootMenu) -> {
Menu subMenu2 = context.createMenu("subMenu2");
Menu subMenu3 = context.createMenu("subMenu3");
rootMenu.setText("Root menu");
subMenu2.setText("SubMenu 2");
subMenu3.setText("SubMenu 3");
MenuButton button1_1 = MenuButton.builder().text("menu 1 - button 1").destinationMenu(subMenu2).build();
MenuButton button2_1 = MenuButton.builder().text("menu 2 - button 1").build();
MenuButton button2_2 = MenuButton.builder().text("menu 2 - button 2").destinationMenu(rootMenu).build();
MenuButton button2_3 = MenuButton.builder().text("menu 2 - button 3").destinationMenu(subMenu3).build();
MenuButton button3_1 = MenuButton.builder().text("menu 3 - button 4").destinationMenu(subMenu2).build();
rootMenu.addRow(button1_1);
subMenu2.addRow(button2_1, button2_2)
.addRow(button2_3);
subMenu3.addRow(button3_1);
});
SendMessage sendMessage = SendMessage.builder()
.text("<b>Test message</b>")
.chatId(chatId)
.replyMarkup(menu.getKeyboard()) | package org.teleight.teleightbots.demo;
public class MainDemo {
public static void main(String[] args) {
final TeleightBots teleightBots = TeleightBots.init();
teleightBots.start();
final String botToken = System.getenv("bot.token") != null ? System.getenv("bot.token") : "--INSERT-TOKEN-HERE--";
final String botUsername = System.getenv("bot.username") != null ? System.getenv("bot.username") : "--INSERT-USERNAME--HERE";
final String chatId = System.getenv("bot.default_chatid") != null ? System.getenv("bot.default_chatid") : "--INSERT-CHATID--HERE";
final EventListener<UpdateReceivedEvent> updateEvent = EventListener.builder(UpdateReceivedEvent.class)
.handler(event -> System.out.println("UpdateReceivedEvent: " + event.bot().getBotUsername() + " -> " + event))
.build();
TeleightBots.getBotManager().registerLongPolling(botToken, botUsername, BotSettings.DEFAULT, bot -> {
System.out.println("Bot registered: " + bot.getBotUsername());
//Listener
bot.getEventManager().addListener(updateEvent);
//Commands
bot.getCommandManager().registerCommand(new TestCommand());
Menu menu = bot.createMenu((context, rootMenu) -> {
Menu subMenu2 = context.createMenu("subMenu2");
Menu subMenu3 = context.createMenu("subMenu3");
rootMenu.setText("Root menu");
subMenu2.setText("SubMenu 2");
subMenu3.setText("SubMenu 3");
MenuButton button1_1 = MenuButton.builder().text("menu 1 - button 1").destinationMenu(subMenu2).build();
MenuButton button2_1 = MenuButton.builder().text("menu 2 - button 1").build();
MenuButton button2_2 = MenuButton.builder().text("menu 2 - button 2").destinationMenu(rootMenu).build();
MenuButton button2_3 = MenuButton.builder().text("menu 2 - button 3").destinationMenu(subMenu3).build();
MenuButton button3_1 = MenuButton.builder().text("menu 3 - button 4").destinationMenu(subMenu2).build();
rootMenu.addRow(button1_1);
subMenu2.addRow(button2_1, button2_2)
.addRow(button2_3);
subMenu3.addRow(button3_1);
});
SendMessage sendMessage = SendMessage.builder()
.text("<b>Test message</b>")
.chatId(chatId)
.replyMarkup(menu.getKeyboard()) | .parseMode(ParseMode.HTML) | 1 | 2023-11-04 16:55:27+00:00 | 4k |
DJ-Raven/swing-glasspane-popup | src/test/java/test/TestSampleMessage.java | [
{
"identifier": "Drawer",
"path": "src/main/java/raven/drawer/Drawer.java",
"snippet": "public class Drawer {\n\n private static Drawer instance;\n private DrawerPanel drawerPanel;\n private DrawerOption option;\n\n public static Drawer getInstance() {\n if (instance == null) {\n ... | import com.formdev.flatlaf.FlatClientProperties;
import com.formdev.flatlaf.FlatLaf;
import com.formdev.flatlaf.fonts.roboto.FlatRobotoFont;
import com.formdev.flatlaf.themes.FlatMacDarkLaf;
import net.miginfocom.swing.MigLayout;
import raven.drawer.Drawer;
import raven.popup.GlassPanePopup;
import raven.popup.component.SimplePopupBorder;
import raven.popup.component.SimplePopupBorderOption;
import javax.swing.*;
import java.awt.*; | 3,416 | package test;
public class TestSampleMessage extends JFrame {
public TestSampleMessage() { | package test;
public class TestSampleMessage extends JFrame {
public TestSampleMessage() { | GlassPanePopup.install(this); | 1 | 2023-11-08 14:06:16+00:00 | 4k |
CxyJerry/pilipala | src/main/java/com/jerry/pilipala/domain/user/service/impl/FansServiceImpl.java | [
{
"identifier": "UserVO",
"path": "src/main/java/com/jerry/pilipala/application/vo/user/UserVO.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\n@Accessors(chain = true)\npublic class UserVO extends PreviewUserVO {\n private int fansCount = 0;\n private int followCount = 0;\n}"
},
... | import cn.dev33.satoken.stp.StpUtil;
import com.jerry.pilipala.application.vo.user.UserVO;
import com.jerry.pilipala.domain.user.entity.neo4j.UserEntity;
import com.jerry.pilipala.domain.user.repository.UserEntityRepository;
import com.jerry.pilipala.domain.user.service.FansService;
import com.jerry.pilipala.domain.user.service.UserService;
import com.jerry.pilipala.infrastructure.common.errors.BusinessException;
import com.jerry.pilipala.infrastructure.common.response.StandardResponse;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors; | 1,630 | package com.jerry.pilipala.domain.user.service.impl;
@Service
public class FansServiceImpl implements FansService {
private final UserService userService;
private final UserEntityRepository userEntityRepository;
public FansServiceImpl(UserService userService,
UserEntityRepository userEntityRepository) {
this.userService = userService;
this.userEntityRepository = userEntityRepository;
}
@Override
public UserVO put(String upUid) {
String myUid = (String) StpUtil.getLoginId();
if (upUid.equals(myUid)) { | package com.jerry.pilipala.domain.user.service.impl;
@Service
public class FansServiceImpl implements FansService {
private final UserService userService;
private final UserEntityRepository userEntityRepository;
public FansServiceImpl(UserService userService,
UserEntityRepository userEntityRepository) {
this.userService = userService;
this.userEntityRepository = userEntityRepository;
}
@Override
public UserVO put(String upUid) {
String myUid = (String) StpUtil.getLoginId();
if (upUid.equals(myUid)) { | throw new BusinessException("无须关注自己", StandardResponse.ERROR); | 6 | 2023-11-03 10:05:02+00:00 | 4k |
viego1999/xuecheng-plus-project | xuecheng-plus-learning/xuecheng-plus-learning-service/src/main/java/com/xuecheng/learning/service/impl/LearningServiceImpl.java | [
{
"identifier": "XueChengPlusException",
"path": "xuecheng-plus-base/src/main/java/com/xuecheng/base/exception/XueChengPlusException.java",
"snippet": "public class XueChengPlusException extends RuntimeException {\n private static final long serialVersionUID = 5565760508056698922L;\n private Strin... | import com.alibaba.fastjson.JSON;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.RestResponse;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.learning.feignclient.ContentServiceClient;
import com.xuecheng.learning.feignclient.MediaServiceClient;
import com.xuecheng.learning.model.dto.XcCourseTablesDto;
import com.xuecheng.learning.service.LearningService;
import com.xuecheng.learning.service.MyCourseTablesService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List; | 3,476 | package com.xuecheng.learning.service.impl;
/**
* 学习课程管理 service 接口实现类
*
* @author Wuxy
* @version 1.0
* @ClassName LearningServiceImpl
* @since 2023/2/3 12:32
*/
@Service
public class LearningServiceImpl implements LearningService {
@Autowired
private ContentServiceClient contentServiceClient;
@Autowired
private MediaServiceClient mediaServiceClient;
@Autowired
private MyCourseTablesService myCourseTablesService;
@Override
public RestResponse<String> getVideo(String userId, Long courseId, Long teachplanId, String mediaId) {
// 查询课程信息
CoursePublish coursePublish = contentServiceClient.getCoursePublish(courseId);
if (coursePublish == null) { | package com.xuecheng.learning.service.impl;
/**
* 学习课程管理 service 接口实现类
*
* @author Wuxy
* @version 1.0
* @ClassName LearningServiceImpl
* @since 2023/2/3 12:32
*/
@Service
public class LearningServiceImpl implements LearningService {
@Autowired
private ContentServiceClient contentServiceClient;
@Autowired
private MediaServiceClient mediaServiceClient;
@Autowired
private MyCourseTablesService myCourseTablesService;
@Override
public RestResponse<String> getVideo(String userId, Long courseId, Long teachplanId, String mediaId) {
// 查询课程信息
CoursePublish coursePublish = contentServiceClient.getCoursePublish(courseId);
if (coursePublish == null) { | XueChengPlusException.cast("课程信息不存在"); | 0 | 2023-11-04 07:15:26+00:00 | 4k |
snicoll/cds-log-parser | src/main/java/org/springframework/experiment/cds/Runner.java | [
{
"identifier": "CdsArchiveLogParser",
"path": "src/main/java/org/springframework/experiment/cds/parser/CdsArchiveLogParser.java",
"snippet": "public class CdsArchiveLogParser {\n\n\tprivate static final Log logger = LogFactory.getLog(CdsArchiveLogParser.class);\n\n\tpublic CdsArchiveReport parse(Resour... | import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Locale;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.io.FileSystemResource;
import org.springframework.experiment.cds.parser.CdsArchiveLogParser;
import org.springframework.experiment.cds.parser.CdsArchiveReport;
import org.springframework.experiment.cds.parser.ClassLoadingLogParser;
import org.springframework.experiment.cds.parser.ClassLoadingReport;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils; | 3,149 | package org.springframework.experiment.cds;
/**
* {@link ApplicationRunner} implementation that parses and print a class loading report.
*
* @author Stephane Nicoll
*/
@Component
class Runner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
String target = getValue(args, "target", System.getProperty("user.dir"));
Path workingDirectory = Paths.get(target);
Mode mode = Mode.from(args);
switch (mode) {
case PARSE -> parseJvmLogs(args, workingDirectory);
case CREATE -> createCdsArchive(args, workingDirectory);
}
}
private void createCdsArchive(ApplicationArguments args, Path workingDirectory) throws Exception {
List<String> applicationArguments = detectApplication(args, workingDirectory);
if (applicationArguments == null) {
throw new IllegalStateException("No application detected in " + workingDirectory);
}
AppRunner appRunner = new AppRunner();
System.out.println("Creating the CDS archive ...");
System.out.println();
System.out.println("Using java version:");
System.out.println(appRunner.getJavaVersion());
System.out.println("Starting application using command: java " + String.join(" ", applicationArguments));
Path cdsArchive = appRunner.createCdsArchive(workingDirectory, applicationArguments);
CdsArchiveReport report = new CdsArchiveLogParser().parse(new FileSystemResource(cdsArchive));
new CdsArchiveReportPrinter().print(report, System.out);
System.out.println(
"To use the archive and collect class loading logs for this application, add the following flags:");
System.out.println();
System.out.println("\t-XX:SharedArchiveFile=application.jsa -Xlog:class+load:file=cds.log");
}
private List<String> detectApplication(ApplicationArguments args, Path workingDirectory) {
String jarFile = getValue(args, "jar", null);
if (jarFile != null) {
if (!Files.exists(workingDirectory.resolve(jarFile))) {
throw new IllegalArgumentException(
"Specified jar file does not exist: " + workingDirectory.resolve(jarFile));
}
return List.of("-jar", jarFile);
}
else if (Files.exists(workingDirectory.resolve("BOOT-INF"))) {
return List.of("org.springframework.boot.loader.launch.JarLauncher");
}
else if (Files.exists(workingDirectory.resolve("run-app.jar"))) {
return List.of("-jar", "run-app.jar");
}
return null;
}
private void parseJvmLogs(ApplicationArguments args, Path workingDirectory) throws IOException {
String fileName = getValue(args, "logFile", "cds.log");
Path logFile = workingDirectory.resolve(fileName);
if (!Files.exists(logFile)) {
throw new IllegalArgumentException(
"JVM log file does not exist: '" + logFile.toAbsolutePath() + "' Set --target or --logFile");
}
ClassLoadingLogParser parser = new ClassLoadingLogParser(workingDirectory); | package org.springframework.experiment.cds;
/**
* {@link ApplicationRunner} implementation that parses and print a class loading report.
*
* @author Stephane Nicoll
*/
@Component
class Runner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
String target = getValue(args, "target", System.getProperty("user.dir"));
Path workingDirectory = Paths.get(target);
Mode mode = Mode.from(args);
switch (mode) {
case PARSE -> parseJvmLogs(args, workingDirectory);
case CREATE -> createCdsArchive(args, workingDirectory);
}
}
private void createCdsArchive(ApplicationArguments args, Path workingDirectory) throws Exception {
List<String> applicationArguments = detectApplication(args, workingDirectory);
if (applicationArguments == null) {
throw new IllegalStateException("No application detected in " + workingDirectory);
}
AppRunner appRunner = new AppRunner();
System.out.println("Creating the CDS archive ...");
System.out.println();
System.out.println("Using java version:");
System.out.println(appRunner.getJavaVersion());
System.out.println("Starting application using command: java " + String.join(" ", applicationArguments));
Path cdsArchive = appRunner.createCdsArchive(workingDirectory, applicationArguments);
CdsArchiveReport report = new CdsArchiveLogParser().parse(new FileSystemResource(cdsArchive));
new CdsArchiveReportPrinter().print(report, System.out);
System.out.println(
"To use the archive and collect class loading logs for this application, add the following flags:");
System.out.println();
System.out.println("\t-XX:SharedArchiveFile=application.jsa -Xlog:class+load:file=cds.log");
}
private List<String> detectApplication(ApplicationArguments args, Path workingDirectory) {
String jarFile = getValue(args, "jar", null);
if (jarFile != null) {
if (!Files.exists(workingDirectory.resolve(jarFile))) {
throw new IllegalArgumentException(
"Specified jar file does not exist: " + workingDirectory.resolve(jarFile));
}
return List.of("-jar", jarFile);
}
else if (Files.exists(workingDirectory.resolve("BOOT-INF"))) {
return List.of("org.springframework.boot.loader.launch.JarLauncher");
}
else if (Files.exists(workingDirectory.resolve("run-app.jar"))) {
return List.of("-jar", "run-app.jar");
}
return null;
}
private void parseJvmLogs(ApplicationArguments args, Path workingDirectory) throws IOException {
String fileName = getValue(args, "logFile", "cds.log");
Path logFile = workingDirectory.resolve(fileName);
if (!Files.exists(logFile)) {
throw new IllegalArgumentException(
"JVM log file does not exist: '" + logFile.toAbsolutePath() + "' Set --target or --logFile");
}
ClassLoadingLogParser parser = new ClassLoadingLogParser(workingDirectory); | ClassLoadingReport report = parser.parser(new FileSystemResource(logFile)); | 3 | 2023-11-06 08:24:32+00:00 | 4k |
SAHONGPAK/JWT-Example | jwt-springboot/src/main/java/com/example/jwt/controller/UserController.java | [
{
"identifier": "AuthDto",
"path": "jwt-springboot/src/main/java/com/example/jwt/model/dto/AuthDto.java",
"snippet": "public class AuthDto {\n\tprivate String userId;\n\tprivate String refreshToken;\n\t\n\tpublic AuthDto(String userId, String refreshToken) {\n\t\tthis.userId = userId;\n\t\tthis.refreshT... | import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.beans.factory.annotation.Value;
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.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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.jwt.annotation.AuthRequired;
import com.example.jwt.model.dto.AuthDto;
import com.example.jwt.model.dto.UserDto;
import com.example.jwt.model.service.AuthService;
import com.example.jwt.model.service.UserService;
import com.example.jwt.util.JWTUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses; | 1,601 | package com.example.jwt.controller;
@RestController
@RequestMapping("/api/v1/user")
public class UserController {
@Value("${jwt.refreshtoken.expiretime}")
private Integer refreshTokenExpireTime;
private final UserService userService; | package com.example.jwt.controller;
@RestController
@RequestMapping("/api/v1/user")
public class UserController {
@Value("${jwt.refreshtoken.expiretime}")
private Integer refreshTokenExpireTime;
private final UserService userService; | private final JWTUtil jwtUtil; | 4 | 2023-11-09 13:14:13+00:00 | 4k |
Verusins/CMS-Android-Simulation | app/src/main/java/example/com/cmsandroidsimulation/EventStudentFragment.java | [
{
"identifier": "EventComment",
"path": "app/src/main/java/example/com/cmsandroidsimulation/datastructures/EventComment.java",
"snippet": "public class EventComment extends UserPost {\n private final int rating;\n private final Date date;\n public EventComment(String author, String details, int... | import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.DocumentSnapshot;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;
import example.com.cmsandroidsimulation.databinding.FragmentEventStudentBinding;
import example.com.cmsandroidsimulation.datastructures.EventComment;
import example.com.cmsandroidsimulation.datastructures.EventInfo;
import example.com.cmsandroidsimulation.apiwrapper.Student; | 2,351 | package example.com.cmsandroidsimulation;
public class EventStudentFragment extends Fragment {
FragmentEventStudentBinding binding;
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState
) {
binding = FragmentEventStudentBinding.inflate(inflater, container, false);
return binding.getRoot();
}
@SuppressLint("MissingInflatedId")
@Override
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Load Content from db
int eventIndex = getArguments().getInt("selectedEventIndex");
| package example.com.cmsandroidsimulation;
public class EventStudentFragment extends Fragment {
FragmentEventStudentBinding binding;
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState
) {
binding = FragmentEventStudentBinding.inflate(inflater, container, false);
return binding.getRoot();
}
@SuppressLint("MissingInflatedId")
@Override
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Load Content from db
int eventIndex = getArguments().getInt("selectedEventIndex");
| Student.getInstance().getEvents().thenAccept((ArrayList<EventInfo> events) -> { | 2 | 2023-11-07 16:52:01+00:00 | 4k |
ProjectBIGWHALE/bigwhale-api | src/test/java/com/whale/web/documents/DocumentsTest.java | [
{
"identifier": "CertificateTypeEnum",
"path": "src/main/java/com/whale/web/documents/certificategenerator/model/enums/CertificateTypeEnum.java",
"snippet": "@Getter\n@ToString\npublic enum CertificateTypeEnum {\n PARTICIPATION(\"Participante\"), SPEAKER(\"Palestrante\"), COURCE(\"Curso\");\n\n pr... | import com.fasterxml.jackson.databind.ObjectMapper;
import com.whale.web.documents.certificategenerator.dto.CertificateRecordDto;
import com.whale.web.documents.certificategenerator.model.enums.CertificateTypeEnum;
import com.whale.web.documents.compressedfileconverter.CompactConverterService;
import com.whale.web.documents.zipfilegenerator.ZipFileCompressorService;
import com.whale.web.documents.qrcodegenerator.dto.QRCodeEmailRecordDto;
import com.whale.web.documents.qrcodegenerator.dto.QRCodeLinkRecordDto;
import com.whale.web.documents.qrcodegenerator.dto.QRCodeWhatsappRecordDto;
import com.whale.web.documents.textextract.TextExtractService;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; | 2,867 | "test-image." + inputFormat,
"image/" + inputFormat,
baos.toByteArray()
);
}
MockMultipartFile createTestImageWhithName(String inputFormat, String name) throws IOException {
BufferedImage bufferedImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = bufferedImage.createGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, 100, 100);
graphics.dispose();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, inputFormat, baos);
baos.toByteArray();
return new MockMultipartFile(
name,
"test-image." + inputFormat,
"image/" + inputFormat,
baos.toByteArray()
);
}
@Test
void testCompactConverterForOneArchive() throws Exception {
MockMultipartFile file = createTestZipFile();
String outputFormat = "tar";
mockMvc.perform(MockMvcRequestBuilders.multipart("/api/v1/documents/compactconverter")
.file(file)
.param("outputFormat", outputFormat))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.header().string("Content-Disposition", "attachment; filename=zip-test." + outputFormat))
.andExpect(MockMvcResultMatchers.header().string("Content-Type", "application/octet-stream"))
.andReturn();
}
@Test
void testCompactConverterForTwoArchives() throws Exception {
MockMultipartFile file1 = createTestZipFile();
MockMultipartFile file2 = createTestZipFile();
String outputFormat = "7z";
mockMvc.perform(MockMvcRequestBuilders.multipart("/api/v1/documents/compactconverter")
.file(file1)
.file(file2)
.param("outputFormat", outputFormat))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.header().string("Content-Disposition", "attachment; filename=zip-test." + outputFormat))
.andExpect(MockMvcResultMatchers.header().string("Content-Type", "application/octet-stream"))
.andReturn();
}
@Test
void compressFileShouldReturnTheFileZip() throws Exception {
MockMultipartFile multipartFile = new MockMultipartFile(
"file",
"test-file.txt",
"text/plain",
"Test file content".getBytes()
);
var multipartFile2 = createTestImage("jpeg", "file");
when(compressorService.compressFiles(any())).thenReturn(multipartFile.getBytes());
mockMvc.perform(MockMvcRequestBuilders.multipart("/api/v1/documents/filecompressor")
.file(multipartFile)
.file(multipartFile2))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType("application/octet-stream"))
.andExpect(MockMvcResultMatchers.header().string("Content-Disposition", "attachment; filename=compressedFile.zip"));
verify(compressorService, times(1)).compressFiles(any());
}
/* @Test
void shouldReturnTheCertificatesStatusCode200() throws Exception {
String csvContent = "col1,col2,col3\nvalue1,value2,value3";
MockMultipartFile csvFileDto = new MockMultipartFile(
"csvFileDto",
"worksheet.csv",
MediaType.TEXT_PLAIN_VALUE,
csvContent.getBytes());
var certificateRecordDto = new CertificateRecordDto(
CertificateTypeEnum.COURCE,
"ABC dos DEVS",
"Ronnyscley",
"CTO",
"20",
"2023-09-12",
"São Paulo",
1L
);
mockMvc.perform(MockMvcRequestBuilders.multipart("/api/v1/documents/certificategenerator")
.file(csvFileDto)
.flashAttr("certificateRecordDto", certificateRecordDto)
.contentType(MediaType.MULTIPART_FORM_DATA))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_OCTET_STREAM_VALUE))
.andExpect(MockMvcResultMatchers.header().string("Content-Disposition", Matchers.containsString("attachment")));
}*/
@Test
void shouldReturnARedirectionStatusCode500() throws Exception {
String csvContent = "col1,col2,col3\nvalue1,value2,value3";
MockMultipartFile csvFileDto = new MockMultipartFile(
"csvFileDto",
"worksheet.csv",
MediaType.TEXT_PLAIN_VALUE,
csvContent.getBytes());
var certificateDto = new CertificateRecordDto( | package com.whale.web.documents;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@AutoConfigureMockMvc
@SpringBootTest
class DocumentsTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@MockBean
private TextExtractService textExtractService;
@MockBean
private ZipFileCompressorService compressorService;
@MockBean
private CompactConverterService compactConverterService;
MockMultipartFile createTestZipFile() throws IOException {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zipOut = new ZipOutputStream(baos)) {
ZipEntry entry = new ZipEntry("test.txt");
zipOut.putNextEntry(entry);
byte[] fileContent = "This is a test file content.".getBytes();
zipOut.write(fileContent, 0, fileContent.length);
zipOut.closeEntry();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
return new MockMultipartFile("files", "zip-test.zip", "application/zip", bais);
}
}
MockMultipartFile createTestTarFile() throws IOException {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
TarArchiveOutputStream tarOut = new TarArchiveOutputStream(baos)) {
TarArchiveEntry entry = new TarArchiveEntry("test.txt");
tarOut.putArchiveEntry(entry);
byte[] fileContent = "This is a test file content.".getBytes();
tarOut.write(fileContent, 0, fileContent.length);
tarOut.closeArchiveEntry();
tarOut.finish();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
return new MockMultipartFile("files", "tar-test.tar", "application/tar", bais);
}
}
MockMultipartFile createTestImage(String inputFormat, String name) throws IOException {
BufferedImage bufferedImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = bufferedImage.createGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, 100, 100);
graphics.dispose();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, inputFormat, baos);
baos.toByteArray();
return new MockMultipartFile(
name,
"test-image." + inputFormat,
"image/" + inputFormat,
baos.toByteArray()
);
}
MockMultipartFile createTestImageWhithName(String inputFormat, String name) throws IOException {
BufferedImage bufferedImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = bufferedImage.createGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, 100, 100);
graphics.dispose();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, inputFormat, baos);
baos.toByteArray();
return new MockMultipartFile(
name,
"test-image." + inputFormat,
"image/" + inputFormat,
baos.toByteArray()
);
}
@Test
void testCompactConverterForOneArchive() throws Exception {
MockMultipartFile file = createTestZipFile();
String outputFormat = "tar";
mockMvc.perform(MockMvcRequestBuilders.multipart("/api/v1/documents/compactconverter")
.file(file)
.param("outputFormat", outputFormat))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.header().string("Content-Disposition", "attachment; filename=zip-test." + outputFormat))
.andExpect(MockMvcResultMatchers.header().string("Content-Type", "application/octet-stream"))
.andReturn();
}
@Test
void testCompactConverterForTwoArchives() throws Exception {
MockMultipartFile file1 = createTestZipFile();
MockMultipartFile file2 = createTestZipFile();
String outputFormat = "7z";
mockMvc.perform(MockMvcRequestBuilders.multipart("/api/v1/documents/compactconverter")
.file(file1)
.file(file2)
.param("outputFormat", outputFormat))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.header().string("Content-Disposition", "attachment; filename=zip-test." + outputFormat))
.andExpect(MockMvcResultMatchers.header().string("Content-Type", "application/octet-stream"))
.andReturn();
}
@Test
void compressFileShouldReturnTheFileZip() throws Exception {
MockMultipartFile multipartFile = new MockMultipartFile(
"file",
"test-file.txt",
"text/plain",
"Test file content".getBytes()
);
var multipartFile2 = createTestImage("jpeg", "file");
when(compressorService.compressFiles(any())).thenReturn(multipartFile.getBytes());
mockMvc.perform(MockMvcRequestBuilders.multipart("/api/v1/documents/filecompressor")
.file(multipartFile)
.file(multipartFile2))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType("application/octet-stream"))
.andExpect(MockMvcResultMatchers.header().string("Content-Disposition", "attachment; filename=compressedFile.zip"));
verify(compressorService, times(1)).compressFiles(any());
}
/* @Test
void shouldReturnTheCertificatesStatusCode200() throws Exception {
String csvContent = "col1,col2,col3\nvalue1,value2,value3";
MockMultipartFile csvFileDto = new MockMultipartFile(
"csvFileDto",
"worksheet.csv",
MediaType.TEXT_PLAIN_VALUE,
csvContent.getBytes());
var certificateRecordDto = new CertificateRecordDto(
CertificateTypeEnum.COURCE,
"ABC dos DEVS",
"Ronnyscley",
"CTO",
"20",
"2023-09-12",
"São Paulo",
1L
);
mockMvc.perform(MockMvcRequestBuilders.multipart("/api/v1/documents/certificategenerator")
.file(csvFileDto)
.flashAttr("certificateRecordDto", certificateRecordDto)
.contentType(MediaType.MULTIPART_FORM_DATA))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_OCTET_STREAM_VALUE))
.andExpect(MockMvcResultMatchers.header().string("Content-Disposition", Matchers.containsString("attachment")));
}*/
@Test
void shouldReturnARedirectionStatusCode500() throws Exception {
String csvContent = "col1,col2,col3\nvalue1,value2,value3";
MockMultipartFile csvFileDto = new MockMultipartFile(
"csvFileDto",
"worksheet.csv",
MediaType.TEXT_PLAIN_VALUE,
csvContent.getBytes());
var certificateDto = new CertificateRecordDto( | CertificateTypeEnum.COURCE, | 0 | 2023-11-08 22:41:22+00:00 | 4k |
ballerina-platform/module-ballerina-data-xmldata | native/src/main/java/io/ballerina/stdlib/data/xmldata/FromString.java | [
{
"identifier": "DiagnosticErrorCode",
"path": "native/src/main/java/io/ballerina/stdlib/data/xmldata/utils/DiagnosticErrorCode.java",
"snippet": "public enum DiagnosticErrorCode {\n\n INVALID_TYPE(\"BDE_0001\", \"invalid.type\"),\n XML_ROOT_MISSING(\"BDE_0002\", \"xml.root.missing\"),\n INVALI... | import java.util.Comparator;
import java.util.List;
import io.ballerina.runtime.api.PredefinedTypes;
import io.ballerina.runtime.api.TypeTags;
import io.ballerina.runtime.api.creators.ValueCreator;
import io.ballerina.runtime.api.types.ReferenceType;
import io.ballerina.runtime.api.types.Type;
import io.ballerina.runtime.api.types.UnionType;
import io.ballerina.runtime.api.values.BDecimal;
import io.ballerina.runtime.api.values.BError;
import io.ballerina.runtime.api.values.BString;
import io.ballerina.runtime.api.values.BTypedesc;
import io.ballerina.stdlib.data.xmldata.utils.DiagnosticErrorCode;
import io.ballerina.stdlib.data.xmldata.utils.DiagnosticLog; | 1,760 | /*
* Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com).
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.ballerina.stdlib.data.xmldata;
/**
* Native implementation of data:fromStringWithType(string).
*
* @since 0.1.0
*/
public class FromString {
public static Object fromStringWithType(BString string, BTypedesc typed) {
Type expType = typed.getDescribingType();
try {
return fromStringWithType(string, expType);
} catch (NumberFormatException e) {
return returnError(string.getValue(), expType.toString());
}
}
public static Object fromStringWithTypeInternal(BString string, Type expType) {
return fromStringWithType(string, expType);
}
private static Object fromStringWithType(BString string, Type expType) {
String value = string.getValue();
try {
switch (expType.getTag()) {
case TypeTags.INT_TAG:
return stringToInt(value);
case TypeTags.FLOAT_TAG:
return stringToFloat(value);
case TypeTags.DECIMAL_TAG:
return stringToDecimal(value);
case TypeTags.STRING_TAG:
return string;
case TypeTags.BOOLEAN_TAG:
return stringToBoolean(value);
case TypeTags.NULL_TAG:
return stringToNull(value);
case TypeTags.UNION_TAG:
return stringToUnion(string, (UnionType) expType);
case TypeTags.TYPE_REFERENCED_TYPE_TAG:
return fromStringWithType(string, ((ReferenceType) expType).getReferredType());
default:
return returnError(value, expType.toString());
}
} catch (NumberFormatException e) {
return returnError(value, expType.toString());
}
}
private static Long stringToInt(String value) throws NumberFormatException {
return Long.parseLong(value);
}
private static Double stringToFloat(String value) throws NumberFormatException {
if (hasFloatOrDecimalLiteralSuffix(value)) {
throw new NumberFormatException();
}
return Double.parseDouble(value);
}
private static BDecimal stringToDecimal(String value) throws NumberFormatException {
return ValueCreator.createDecimalValue(value);
}
private static Object stringToBoolean(String value) throws NumberFormatException {
if ("true".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value)) {
return true;
}
if ("false".equalsIgnoreCase(value) || "0".equalsIgnoreCase(value)) {
return false;
}
return returnError(value, "boolean");
}
private static Object stringToNull(String value) throws NumberFormatException {
if ("null".equalsIgnoreCase(value) || "()".equalsIgnoreCase(value)) {
return null;
}
return returnError(value, "()");
}
private static Object stringToUnion(BString string, UnionType expType) throws NumberFormatException {
List<Type> memberTypes = expType.getMemberTypes();
memberTypes.sort(Comparator.comparingInt(t -> t.getTag()));
boolean isStringExpType = false;
for (Type memberType : memberTypes) {
try {
Object result = fromStringWithType(string, memberType);
if (result instanceof BString) {
isStringExpType = true;
continue;
} else if (result instanceof BError) {
continue;
}
return result;
} catch (Exception e) {
// Skip
}
}
if (isStringExpType) {
return string;
}
return returnError(string.getValue(), expType.toString());
}
private static boolean hasFloatOrDecimalLiteralSuffix(String value) {
int length = value.length();
if (length == 0) {
return false;
}
switch (value.charAt(length - 1)) {
case 'F':
case 'f':
case 'D':
case 'd':
return true;
default:
return false;
}
}
private static BError returnError(String string, String expType) { | /*
* Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com).
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.ballerina.stdlib.data.xmldata;
/**
* Native implementation of data:fromStringWithType(string).
*
* @since 0.1.0
*/
public class FromString {
public static Object fromStringWithType(BString string, BTypedesc typed) {
Type expType = typed.getDescribingType();
try {
return fromStringWithType(string, expType);
} catch (NumberFormatException e) {
return returnError(string.getValue(), expType.toString());
}
}
public static Object fromStringWithTypeInternal(BString string, Type expType) {
return fromStringWithType(string, expType);
}
private static Object fromStringWithType(BString string, Type expType) {
String value = string.getValue();
try {
switch (expType.getTag()) {
case TypeTags.INT_TAG:
return stringToInt(value);
case TypeTags.FLOAT_TAG:
return stringToFloat(value);
case TypeTags.DECIMAL_TAG:
return stringToDecimal(value);
case TypeTags.STRING_TAG:
return string;
case TypeTags.BOOLEAN_TAG:
return stringToBoolean(value);
case TypeTags.NULL_TAG:
return stringToNull(value);
case TypeTags.UNION_TAG:
return stringToUnion(string, (UnionType) expType);
case TypeTags.TYPE_REFERENCED_TYPE_TAG:
return fromStringWithType(string, ((ReferenceType) expType).getReferredType());
default:
return returnError(value, expType.toString());
}
} catch (NumberFormatException e) {
return returnError(value, expType.toString());
}
}
private static Long stringToInt(String value) throws NumberFormatException {
return Long.parseLong(value);
}
private static Double stringToFloat(String value) throws NumberFormatException {
if (hasFloatOrDecimalLiteralSuffix(value)) {
throw new NumberFormatException();
}
return Double.parseDouble(value);
}
private static BDecimal stringToDecimal(String value) throws NumberFormatException {
return ValueCreator.createDecimalValue(value);
}
private static Object stringToBoolean(String value) throws NumberFormatException {
if ("true".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value)) {
return true;
}
if ("false".equalsIgnoreCase(value) || "0".equalsIgnoreCase(value)) {
return false;
}
return returnError(value, "boolean");
}
private static Object stringToNull(String value) throws NumberFormatException {
if ("null".equalsIgnoreCase(value) || "()".equalsIgnoreCase(value)) {
return null;
}
return returnError(value, "()");
}
private static Object stringToUnion(BString string, UnionType expType) throws NumberFormatException {
List<Type> memberTypes = expType.getMemberTypes();
memberTypes.sort(Comparator.comparingInt(t -> t.getTag()));
boolean isStringExpType = false;
for (Type memberType : memberTypes) {
try {
Object result = fromStringWithType(string, memberType);
if (result instanceof BString) {
isStringExpType = true;
continue;
} else if (result instanceof BError) {
continue;
}
return result;
} catch (Exception e) {
// Skip
}
}
if (isStringExpType) {
return string;
}
return returnError(string.getValue(), expType.toString());
}
private static boolean hasFloatOrDecimalLiteralSuffix(String value) {
int length = value.length();
if (length == 0) {
return false;
}
switch (value.charAt(length - 1)) {
case 'F':
case 'f':
case 'D':
case 'd':
return true;
default:
return false;
}
}
private static BError returnError(String string, String expType) { | return DiagnosticLog.error(DiagnosticErrorCode.CANNOT_CONVERT_TO_EXPECTED_TYPE, | 1 | 2023-11-08 04:13:52+00:00 | 4k |
Mau38/SparePartsFTC | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/ParkFarBlue.java | [
{
"identifier": "SampleMecanumDrive",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/drive/SampleMecanumDrive.java",
"snippet": "@Config\npublic class SampleMecanumDrive extends MecanumDrive {\n public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(0, 0, 0);... | import com.acmerobotics.roadrunner.geometry.Pose2d;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import org.firstinspires.ftc.teamcode.roadRunner.drive.SampleMecanumDrive;
import org.firstinspires.ftc.teamcode.roadRunner.trajectorysequence.TrajectorySequence; | 2,865 | package org.firstinspires.ftc.teamcode;
@Autonomous(name = "ParkFarBlue", group = "CompAutos")
public class ParkFarBlue extends LinearOpMode {
public static double STRAFE_DIST = 30;
public static double FORWARD_DIST = 160;
@Override
public void runOpMode() throws InterruptedException { | package org.firstinspires.ftc.teamcode;
@Autonomous(name = "ParkFarBlue", group = "CompAutos")
public class ParkFarBlue extends LinearOpMode {
public static double STRAFE_DIST = 30;
public static double FORWARD_DIST = 160;
@Override
public void runOpMode() throws InterruptedException { | SampleMecanumDrive drive = new SampleMecanumDrive(hardwareMap); | 0 | 2023-11-06 21:25:54+00:00 | 4k |
RoshanAdi/GPTonDemand-Api | src/main/java/com/gpt/gptplus1/Controller/UserController.java | [
{
"identifier": "ResponseMessage",
"path": "src/main/java/com/gpt/gptplus1/Entity/ResponseMessage.java",
"snippet": "public class ResponseMessage {\n private String message;\n\n public ResponseMessage(String message) {\n this.message = message;\n }\n\n public String getMessage() {\n ... | import com.gpt.gptplus1.Entity.ResponseMessage;
import com.gpt.gptplus1.Entity.User;
import com.gpt.gptplus1.Service.Email.SendEmail;
import com.gpt.gptplus1.Service.WebSecurity.AuthToken;
import com.gpt.gptplus1.Service.WebSecurity.TokenProvider;
import com.gpt.gptplus1.Service.WebSecurity.UserDetailsServiceImpl;
import com.gpt.gptplus1.Service.WebSecurity.UserService;
import jakarta.mail.MessagingException;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.repository.query.Param;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;
import java.io.UnsupportedEncodingException;
import java.util.Objects; | 3,153 | package com.gpt.gptplus1.Controller;
@RestController
@RequestMapping("/")
public class UserController {
@Value("${frontEnd.URL}")
private String clientURL;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private TokenProvider jwtTokenUtil;
@Autowired
private UserService userService;
@Autowired
private SendEmail sendEmail;
@Autowired
private UserDetailsServiceImpl userDetailsService;
@PostMapping(value="/api1/register" )
public ResponseMessage saveUser(@RequestBody User user, HttpServletRequest request) {
String message="";
if (userService.getUserByEmail(user.getEmail())!=null) {
message = user.getEmail()+" is already registered!. May be you haven't verify your email address. if so, please check your mailbox ";
return new ResponseMessage(message);
} else {
String siteURL = request.getRequestURL().toString();
userService.saveUser(user,siteURL.replace(request.getServletPath(),""));
message = "Please confirm your email address. We have sent an confirmation link to "+user.getEmail();
return new ResponseMessage(message);
}
}
@PostMapping(value = "/api1/login")
public ResponseEntity<?> generateToken(@RequestBody User loginUser) throws AuthenticationException {
try {
final Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
loginUser.getEmail(),
loginUser.getPassword()
)
);
if (!userDetailsService.isUserEnabled(loginUser.getEmail())) {
return ResponseEntity.status(399)
.body("User is not enabled. Please verify your email.");
}
SecurityContextHolder.getContext().setAuthentication(authentication);
final String token = jwtTokenUtil.generateToken(authentication);
| package com.gpt.gptplus1.Controller;
@RestController
@RequestMapping("/")
public class UserController {
@Value("${frontEnd.URL}")
private String clientURL;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private TokenProvider jwtTokenUtil;
@Autowired
private UserService userService;
@Autowired
private SendEmail sendEmail;
@Autowired
private UserDetailsServiceImpl userDetailsService;
@PostMapping(value="/api1/register" )
public ResponseMessage saveUser(@RequestBody User user, HttpServletRequest request) {
String message="";
if (userService.getUserByEmail(user.getEmail())!=null) {
message = user.getEmail()+" is already registered!. May be you haven't verify your email address. if so, please check your mailbox ";
return new ResponseMessage(message);
} else {
String siteURL = request.getRequestURL().toString();
userService.saveUser(user,siteURL.replace(request.getServletPath(),""));
message = "Please confirm your email address. We have sent an confirmation link to "+user.getEmail();
return new ResponseMessage(message);
}
}
@PostMapping(value = "/api1/login")
public ResponseEntity<?> generateToken(@RequestBody User loginUser) throws AuthenticationException {
try {
final Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
loginUser.getEmail(),
loginUser.getPassword()
)
);
if (!userDetailsService.isUserEnabled(loginUser.getEmail())) {
return ResponseEntity.status(399)
.body("User is not enabled. Please verify your email.");
}
SecurityContextHolder.getContext().setAuthentication(authentication);
final String token = jwtTokenUtil.generateToken(authentication);
| return ResponseEntity.ok(new AuthToken(token)); | 3 | 2023-11-07 11:52:13+00:00 | 4k |
project-BarryBarry/coffeeport | src/main/java/com/barrybarry/coffeeport/router/VeraportRouter.java | [
{
"identifier": "VeraDataConverter",
"path": "src/main/java/com/barrybarry/coffeeport/converter/VeraDataConverter.java",
"snippet": "public class VeraDataConverter implements ResponseConverterFunction {\n // 正直、この方法は良くないと思う\n private static final String callbackFormat = \"try {%s(%s);} catch(e){}\... | import com.barrybarry.coffeeport.converter.VeraDataConverter;
import com.barrybarry.coffeeport.data.*;
import com.barrybarry.coffeeport.data.task.TaskData;
import com.barrybarry.coffeeport.data.task.VeraData;
import com.barrybarry.coffeeport.data.xml.Data;
import com.barrybarry.coffeeport.data.xml.VeraTaskData;
import com.barrybarry.coffeeport.handler.CommandHandler;
import com.barrybarry.coffeeport.sigleton.TaskListManager;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.linecorp.armeria.common.HttpRequest;
import com.linecorp.armeria.server.ServiceRequestContext;
import com.linecorp.armeria.server.annotation.Get;
import com.linecorp.armeria.server.annotation.Param;
import com.linecorp.armeria.server.annotation.Post;
import com.linecorp.armeria.server.annotation.ResponseConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | 2,299 | package com.barrybarry.coffeeport.router;
public class VeraportRouter {
private static final Logger logger = LoggerFactory.getLogger(VeraportRouter.class);
| package com.barrybarry.coffeeport.router;
public class VeraportRouter {
private static final Logger logger = LoggerFactory.getLogger(VeraportRouter.class);
| @ResponseConverter(VeraDataConverter.class) | 0 | 2023-11-08 01:22:24+00:00 | 4k |
celedev97/asa-server-manager | src/main/java/dev/cele/asa_sm/services/UpdateService.java | [
{
"identifier": "Const",
"path": "src/main/java/dev/cele/asa_sm/Const.java",
"snippet": "public final class Const {\n public final static String ASA_STEAM_GAME_NUMBER = \"2430930\";\n\n public final static Path DATA_DIR = Path.of(\"data\");\n public final static Path PROFILES_DIR = DATA_DIR.res... | import dev.cele.asa_sm.Const;
import dev.cele.asa_sm.dto.github.Release;
import dev.cele.asa_sm.feign.GithubClient;
import dev.cele.asa_sm.ui.frames.ProgressFrame;
import jakarta.annotation.PostConstruct;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
import org.springframework.web.client.RestTemplate;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.regex.Pattern; | 1,760 | package dev.cele.asa_sm.services;
@Service
@RequiredArgsConstructor
@Slf4j
public class UpdateService {
private final GithubClient githubClient;
@Getter
@Value("${application.version}")
private String currentVersion;
private String ignoredVersion = "";
{
try {
var ignoredVersionFile = Const.DATA_DIR.resolve("ignoredVersion.txt");
if(ignoredVersionFile.toFile().exists() && ignoredVersionFile.toFile().isFile()){
ignoredVersion = new String(Files.readAllBytes(ignoredVersionFile));
}
}catch (IOException e){
JOptionPane.showMessageDialog(null, "Error while reading ignoredVersion.txt: " + e.getMessage());
log.error("Error while reading ignoredVersion.txt: ", e);
}
}
public void checkForUpdates() {
Release latestRelease = null;
if(currentVersion.contains("-SNAPSHOT")){
//don't check update if this is a snapshot
log.info("This is a snapshot version, skipping update check");
return;
}
log.info("Checking for updates...");
try {
latestRelease = githubClient.getLatestRelease("celedev97", "asa-server-manager");
}catch (Exception e){
JOptionPane.showMessageDialog(null, "Error while checking for updates: " + e.getMessage());
log.error("Error while checking for updates: ", e);
}
assert latestRelease != null;
var newVersion = latestRelease.getTag_name();
if(ignoredVersion.equals(newVersion)){
return;
}
//regex for version number with optional starting v and with optional snapshot version, one capturing group for major, one for minor, one for patch
var versionRegex = Pattern.compile("v?(\\d+)\\.(\\d+)\\.(\\d+)");
var currentVersionMatcher = versionRegex.matcher(currentVersion);
var newVersionMatcher = versionRegex.matcher(newVersion);
//extract version numbers from version strings
currentVersionMatcher.find();
newVersionMatcher.find();
var currentMajor = Integer.parseInt(currentVersionMatcher.group(1));
var currentMinor = Integer.parseInt(currentVersionMatcher.group(2));
var currentPatch = Integer.parseInt(currentVersionMatcher.group(3));
var newMajor = Integer.parseInt(newVersionMatcher.group(1));
var newMinor = Integer.parseInt(newVersionMatcher.group(2));
var newPatch = Integer.parseInt(newVersionMatcher.group(3));
//check if new version is newer than current version
if(newMajor > currentMajor || newMinor > currentMinor || newPatch > currentPatch){
String[] options = new String[] {"Yes", "Ask me Later", "Ignore this version"};
int response = JOptionPane.showOptionDialog(
null,
"A new version of ASA Server Manager is available: " + newVersion + "\nDo you want to download it?",
"New Version Available",
JOptionPane.DEFAULT_OPTION,
JOptionPane.INFORMATION_MESSAGE,
null,
options,
options[0]
);
if(response == 0){
try {
downloadUpdate(latestRelease);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error while opening download link: " + e.getMessage());
log.error("Error while opening download link: ", e);
}
System.exit(0);
}else if(response == 2){
try {
Files.writeString(Const.DATA_DIR.resolve("ignoredVersion.txt"), newVersion);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Error while writing ignoredVersion.txt: " + e.getMessage());
log.error("Error while writing ignoredVersion.txt: ", e);
}
}
}
}
@SneakyThrows
private void downloadUpdate(Release latestRelease) {
if(SystemUtils.IS_OS_WINDOWS){
var asset = Arrays.stream(latestRelease.getAssets())
.filter(a -> a.getName().endsWith(".exe"))
.findFirst()
.orElseThrow(() -> new RuntimeException("No exe asset found"));
log.info("Downloading update...");
InputStream input = new URL(asset.getBrowser_download_url()).openStream();
var tempFile = File.createTempFile("asa_sm_update", ".exe");
//file copy from input to tempFile with progress bar
FileOutputStream output = new FileOutputStream(tempFile);
| package dev.cele.asa_sm.services;
@Service
@RequiredArgsConstructor
@Slf4j
public class UpdateService {
private final GithubClient githubClient;
@Getter
@Value("${application.version}")
private String currentVersion;
private String ignoredVersion = "";
{
try {
var ignoredVersionFile = Const.DATA_DIR.resolve("ignoredVersion.txt");
if(ignoredVersionFile.toFile().exists() && ignoredVersionFile.toFile().isFile()){
ignoredVersion = new String(Files.readAllBytes(ignoredVersionFile));
}
}catch (IOException e){
JOptionPane.showMessageDialog(null, "Error while reading ignoredVersion.txt: " + e.getMessage());
log.error("Error while reading ignoredVersion.txt: ", e);
}
}
public void checkForUpdates() {
Release latestRelease = null;
if(currentVersion.contains("-SNAPSHOT")){
//don't check update if this is a snapshot
log.info("This is a snapshot version, skipping update check");
return;
}
log.info("Checking for updates...");
try {
latestRelease = githubClient.getLatestRelease("celedev97", "asa-server-manager");
}catch (Exception e){
JOptionPane.showMessageDialog(null, "Error while checking for updates: " + e.getMessage());
log.error("Error while checking for updates: ", e);
}
assert latestRelease != null;
var newVersion = latestRelease.getTag_name();
if(ignoredVersion.equals(newVersion)){
return;
}
//regex for version number with optional starting v and with optional snapshot version, one capturing group for major, one for minor, one for patch
var versionRegex = Pattern.compile("v?(\\d+)\\.(\\d+)\\.(\\d+)");
var currentVersionMatcher = versionRegex.matcher(currentVersion);
var newVersionMatcher = versionRegex.matcher(newVersion);
//extract version numbers from version strings
currentVersionMatcher.find();
newVersionMatcher.find();
var currentMajor = Integer.parseInt(currentVersionMatcher.group(1));
var currentMinor = Integer.parseInt(currentVersionMatcher.group(2));
var currentPatch = Integer.parseInt(currentVersionMatcher.group(3));
var newMajor = Integer.parseInt(newVersionMatcher.group(1));
var newMinor = Integer.parseInt(newVersionMatcher.group(2));
var newPatch = Integer.parseInt(newVersionMatcher.group(3));
//check if new version is newer than current version
if(newMajor > currentMajor || newMinor > currentMinor || newPatch > currentPatch){
String[] options = new String[] {"Yes", "Ask me Later", "Ignore this version"};
int response = JOptionPane.showOptionDialog(
null,
"A new version of ASA Server Manager is available: " + newVersion + "\nDo you want to download it?",
"New Version Available",
JOptionPane.DEFAULT_OPTION,
JOptionPane.INFORMATION_MESSAGE,
null,
options,
options[0]
);
if(response == 0){
try {
downloadUpdate(latestRelease);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error while opening download link: " + e.getMessage());
log.error("Error while opening download link: ", e);
}
System.exit(0);
}else if(response == 2){
try {
Files.writeString(Const.DATA_DIR.resolve("ignoredVersion.txt"), newVersion);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Error while writing ignoredVersion.txt: " + e.getMessage());
log.error("Error while writing ignoredVersion.txt: ", e);
}
}
}
}
@SneakyThrows
private void downloadUpdate(Release latestRelease) {
if(SystemUtils.IS_OS_WINDOWS){
var asset = Arrays.stream(latestRelease.getAssets())
.filter(a -> a.getName().endsWith(".exe"))
.findFirst()
.orElseThrow(() -> new RuntimeException("No exe asset found"));
log.info("Downloading update...");
InputStream input = new URL(asset.getBrowser_download_url()).openStream();
var tempFile = File.createTempFile("asa_sm_update", ".exe");
//file copy from input to tempFile with progress bar
FileOutputStream output = new FileOutputStream(tempFile);
| var progressFrame = new ProgressFrame(null, "Downloading Update", "Downloading update...", false); | 3 | 2023-11-07 19:36:49+00:00 | 4k |
fredpena/barcamp2023 | src/main/java/dev/fredpena/barcamp/views/person/FormView.java | [
{
"identifier": "ConfirmationDialog",
"path": "src/main/java/dev/fredpena/barcamp/componect/ConfirmationDialog.java",
"snippet": "public class ConfirmationDialog extends Dialog {\n\n private H2 title;\n private Paragraph question;\n private final transient Consumer<Dialog> listener;\n\n publ... | import com.vaadin.flow.component.ClickEvent;
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.HtmlContainer;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.checkbox.Checkbox;
import com.vaadin.flow.component.combobox.ComboBox;
import com.vaadin.flow.component.datepicker.DatePicker;
import com.vaadin.flow.component.dialog.Dialog;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.html.Hr;
import com.vaadin.flow.component.orderedlayout.FlexComponent;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.textfield.EmailField;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.BeanValidationBinder;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.data.binder.ValidationException;
import com.vaadin.flow.theme.lumo.LumoUtility;
import dev.fredpena.barcamp.componect.ConfirmationDialog;
import dev.fredpena.barcamp.componect.CustomNotification;
import dev.fredpena.barcamp.data.tenant.entity.Person;
import dev.fredpena.barcamp.data.tenant.service.PersonService;
import jakarta.persistence.Column;
import jakarta.validation.constraints.NotNull;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional; | 2,227 | package dev.fredpena.barcamp.views.person;
public class FormView {
private final TextField firstName = new TextField("First Name");
private final TextField lastName = new TextField("Last Name");
private final EmailField email = new EmailField("Email");
private final TextField phone = new TextField("Phone Number");
private final DatePicker dateOfBirth = new DatePicker("Birthday");
private final TextField occupation = new TextField("Occupation");
private final ComboBox<String> fieldRole = new ComboBox<>("Role");
private final Checkbox important = new Checkbox("Is important?");
private final Button delete = new Button("Delete");
private final Button cancel = new Button("Cancel");
private final Button save = new Button("Save");
private final HtmlContainer parent;
private final PersonService personService;
private final CustomNotification notification; | package dev.fredpena.barcamp.views.person;
public class FormView {
private final TextField firstName = new TextField("First Name");
private final TextField lastName = new TextField("Last Name");
private final EmailField email = new EmailField("Email");
private final TextField phone = new TextField("Phone Number");
private final DatePicker dateOfBirth = new DatePicker("Birthday");
private final TextField occupation = new TextField("Occupation");
private final ComboBox<String> fieldRole = new ComboBox<>("Role");
private final Checkbox important = new Checkbox("Is important?");
private final Button delete = new Button("Delete");
private final Button cancel = new Button("Cancel");
private final Button save = new Button("Save");
private final HtmlContainer parent;
private final PersonService personService;
private final CustomNotification notification; | private Person element; | 2 | 2023-11-08 18:12:12+00:00 | 4k |
HexHive/Crystallizer | src/dynamic/SeriFuzz.java | [
{
"identifier": "GadgetVertexSerializable",
"path": "src/static/src/main/java/analysis/GadgetVertexSerializable.java",
"snippet": "public class GadgetVertexSerializable implements Serializable {\n final GadgetMethodSerializable node;\n\n public GadgetVertexSerializable(GadgetMethodSerializable nod... | import com.code_intelligence.jazzer.api.FuzzedDataProvider;
import com.code_intelligence.jazzer.autofuzz.*;
import analysis.GadgetVertexSerializable;
import analysis.GadgetMethodSerializable;
import org.jgrapht.*;
import org.jgrapht.graph.*;
import org.jgrapht.traverse.*;
import org.jgrapht.alg.shortestpath.*;
import java.io.*;
import java.lang.reflect.Constructor;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator; | 1,908 | package com.example;
// import clojure.*;
// import org.apache.logging.log4j.Logger;
public class SeriFuzz {
// private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final Logger LOGGER = Logger.getLogger(SeriFuzz.class);
private static String logProperties = "/root/SeriFuzz/src/dynamic/log4j.properties";
// This sinkID is used to identify is sink gadget is triggered
public static List<String> sinkIDs = new ArrayList<String>();
// This flag identifies if we are running the fuzzer in the dynamic sink identification mode
public static boolean isSinkIDMode = false;
// This flag identifiers if we are running the fuzzer in the crash triage mode
public static boolean isCrashTriageMode = false;
// This flag identifies if we are running the fuzzer to find DoS bugs
public static boolean isDosMode = false;
// This flag identifies if we are running the fuzzer to enumerate all candidate paths
public static boolean isPathEnumerationMode = false;
// This flag identifies if we are running the fuzzer without the aid of the gadget graph
public static boolean isNoGGMode = false;
// Specify the threshold time we put in to get new cov before we deem that the campaign has stalled
public static long thresholdTime = 3600;
// Specifies the maximum length of the chains that are to be found
public static int maxPathLength = 5;
public static boolean sinkTriggered;
// In case CrashTriage mode is enabled, we use this variable to keep track
// of which path is being triaged
public static int triagePathID;
public static void readMode() {
// This control string identifies which mode the dynamic analysis component should be run in.
// Available modes: SinkID, CrashTriage, Dos, PathEnumeration, NoGG, Fuzz
// This string is read from a file named `_crystallizer_mode` created in the
// directory pointed by TrackStatistics.storeDir
String crystallizerMode = null;
try {
BufferedReader br = new BufferedReader(new FileReader(TrackStatistics.storeDir + "_crystallizer_mode"));
crystallizerMode = br.readLine();
if (crystallizerMode.equals("SinkID")) {
LOGGER.info("Turning on sink ID mode");
// Read in the library being analyzed
BufferedReader br1 = new BufferedReader(new FileReader(TrackStatistics.storeDir + "_libname"));
DynamicSinkID.targetLibrary = br1.readLine();
isSinkIDMode = true;
} else if (crystallizerMode.equals("CrashTriage")) {
LOGGER.info("Turning on crash triage mode");
Scanner scanner = new Scanner(new File(TrackStatistics.storeDir + "_pathID"));
GadgetDB.currentPathID = scanner.nextInt();
LOGGER.info("Path ID to be triaged:" + GadgetDB.currentPathID);
// Read in the path ID that is to be triaged
isCrashTriageMode = true;
} else if (crystallizerMode.equals("Dos")) {
LOGGER.info("Turning on DOS mode");
isDosMode = true;
} else if (crystallizerMode.equals("PathEnumeration")) {
LOGGER.info("Turning on path enumeration mode");
isPathEnumerationMode = true;
} else if (crystallizerMode.equals("NoGG")) {
LOGGER.info("Turning on nogg mode");
isNoGGMode = true;
} else if (crystallizerMode.equals("Fuzz")) {
LOGGER.info("No specialized modes turned on, performing regular fuzzing");
} else {
LOGGER.info(String.format("Unknown mode found %s...exiting", crystallizerMode));
System.exit(1);
}
} catch (IOException e) {
LOGGER.info("Could not read crystallizer mode initiailizer..exiting");
System.exit(1);
}
}
public static void fuzzerInitialize(String[] args) {
PropertyConfigurator.configure(logProperties);
// Read in the mode in which Crystallizer is to be run
SeriFuzz.readMode();
LogCrash.makeCrashDir();
LogCrash.initJDKCrashedPaths();
TrackStatistics.logInitTimeStamp();
// ObjectFactory.populateClassCache();
if (isSinkIDMode) {
Meta.isSinkIDMode = true;
LOGGER.debug("Reinitializing vulnerable sinks found");
LogCrash.reinitVulnerableSinks();
// We do this to force init the class so that reachable classes are
// computed before the fuzz timeout is enforced
LOGGER.debug(String.format("Number of unique classes:%d", DynamicSinkID.uniqueClasses.length));
return;
}
if (isCrashTriageMode) {
LOGGER.debug("Running the fuzzer in crash triage mode");
Meta.isCrashTriageMode = true;
}
LogCrash.initCrashID();
GadgetDB.tagSourcesAndSinks();
// GadgetDB.findAllPaths();
if (! isSinkIDMode) {
GadgetDB.findAllPaths();
}
if (! isDosMode) {
TrackStatistics.initProgressCounters();
}
}
public static void fuzzerTestOneInput(FuzzedDataProvider data) {
if (Meta.isCrashTriageMode) {
Meta.constructionSteps.clear();
}
if (isPathEnumerationMode) {
// GadgetDB.showVertices();
GadgetDB.printAllPaths();
System.exit(1);
}
// Operating in the dynamic sink ID mode
if (isSinkIDMode) {
boolean didTest = DynamicSinkID.testPotentialSinks(data);
return;
}
// Operating in DoS bug discovery mode
if (isDosMode) {
DosChain.runAnalysis(data);
return;
}
// makeHookActive = false;
sinkTriggered = false;
Meta.localCache.clear(); | package com.example;
// import clojure.*;
// import org.apache.logging.log4j.Logger;
public class SeriFuzz {
// private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final Logger LOGGER = Logger.getLogger(SeriFuzz.class);
private static String logProperties = "/root/SeriFuzz/src/dynamic/log4j.properties";
// This sinkID is used to identify is sink gadget is triggered
public static List<String> sinkIDs = new ArrayList<String>();
// This flag identifies if we are running the fuzzer in the dynamic sink identification mode
public static boolean isSinkIDMode = false;
// This flag identifiers if we are running the fuzzer in the crash triage mode
public static boolean isCrashTriageMode = false;
// This flag identifies if we are running the fuzzer to find DoS bugs
public static boolean isDosMode = false;
// This flag identifies if we are running the fuzzer to enumerate all candidate paths
public static boolean isPathEnumerationMode = false;
// This flag identifies if we are running the fuzzer without the aid of the gadget graph
public static boolean isNoGGMode = false;
// Specify the threshold time we put in to get new cov before we deem that the campaign has stalled
public static long thresholdTime = 3600;
// Specifies the maximum length of the chains that are to be found
public static int maxPathLength = 5;
public static boolean sinkTriggered;
// In case CrashTriage mode is enabled, we use this variable to keep track
// of which path is being triaged
public static int triagePathID;
public static void readMode() {
// This control string identifies which mode the dynamic analysis component should be run in.
// Available modes: SinkID, CrashTriage, Dos, PathEnumeration, NoGG, Fuzz
// This string is read from a file named `_crystallizer_mode` created in the
// directory pointed by TrackStatistics.storeDir
String crystallizerMode = null;
try {
BufferedReader br = new BufferedReader(new FileReader(TrackStatistics.storeDir + "_crystallizer_mode"));
crystallizerMode = br.readLine();
if (crystallizerMode.equals("SinkID")) {
LOGGER.info("Turning on sink ID mode");
// Read in the library being analyzed
BufferedReader br1 = new BufferedReader(new FileReader(TrackStatistics.storeDir + "_libname"));
DynamicSinkID.targetLibrary = br1.readLine();
isSinkIDMode = true;
} else if (crystallizerMode.equals("CrashTriage")) {
LOGGER.info("Turning on crash triage mode");
Scanner scanner = new Scanner(new File(TrackStatistics.storeDir + "_pathID"));
GadgetDB.currentPathID = scanner.nextInt();
LOGGER.info("Path ID to be triaged:" + GadgetDB.currentPathID);
// Read in the path ID that is to be triaged
isCrashTriageMode = true;
} else if (crystallizerMode.equals("Dos")) {
LOGGER.info("Turning on DOS mode");
isDosMode = true;
} else if (crystallizerMode.equals("PathEnumeration")) {
LOGGER.info("Turning on path enumeration mode");
isPathEnumerationMode = true;
} else if (crystallizerMode.equals("NoGG")) {
LOGGER.info("Turning on nogg mode");
isNoGGMode = true;
} else if (crystallizerMode.equals("Fuzz")) {
LOGGER.info("No specialized modes turned on, performing regular fuzzing");
} else {
LOGGER.info(String.format("Unknown mode found %s...exiting", crystallizerMode));
System.exit(1);
}
} catch (IOException e) {
LOGGER.info("Could not read crystallizer mode initiailizer..exiting");
System.exit(1);
}
}
public static void fuzzerInitialize(String[] args) {
PropertyConfigurator.configure(logProperties);
// Read in the mode in which Crystallizer is to be run
SeriFuzz.readMode();
LogCrash.makeCrashDir();
LogCrash.initJDKCrashedPaths();
TrackStatistics.logInitTimeStamp();
// ObjectFactory.populateClassCache();
if (isSinkIDMode) {
Meta.isSinkIDMode = true;
LOGGER.debug("Reinitializing vulnerable sinks found");
LogCrash.reinitVulnerableSinks();
// We do this to force init the class so that reachable classes are
// computed before the fuzz timeout is enforced
LOGGER.debug(String.format("Number of unique classes:%d", DynamicSinkID.uniqueClasses.length));
return;
}
if (isCrashTriageMode) {
LOGGER.debug("Running the fuzzer in crash triage mode");
Meta.isCrashTriageMode = true;
}
LogCrash.initCrashID();
GadgetDB.tagSourcesAndSinks();
// GadgetDB.findAllPaths();
if (! isSinkIDMode) {
GadgetDB.findAllPaths();
}
if (! isDosMode) {
TrackStatistics.initProgressCounters();
}
}
public static void fuzzerTestOneInput(FuzzedDataProvider data) {
if (Meta.isCrashTriageMode) {
Meta.constructionSteps.clear();
}
if (isPathEnumerationMode) {
// GadgetDB.showVertices();
GadgetDB.printAllPaths();
System.exit(1);
}
// Operating in the dynamic sink ID mode
if (isSinkIDMode) {
boolean didTest = DynamicSinkID.testPotentialSinks(data);
return;
}
// Operating in DoS bug discovery mode
if (isDosMode) {
DosChain.runAnalysis(data);
return;
}
// makeHookActive = false;
sinkTriggered = false;
Meta.localCache.clear(); | GraphPath<GadgetVertexSerializable, DefaultEdge> candidate = null; | 0 | 2023-11-07 22:03:19+00:00 | 4k |
wuyu-wy/mgzm_volunteer | volunteer/src/main/java/com/blbd/volunteer/service/impl/ChatFriendListServiceImpl.java | [
{
"identifier": "ChatFriendListEntity",
"path": "volunteer/src/main/java/com/blbd/volunteer/dao/entity/ChatFriendListEntity.java",
"snippet": "@Data\npublic class ChatFriendListEntity implements Serializable {\n /**\n * 聊天列表主键\n */\n private Integer listId;\n\n /**\n * 聊天主表id\n ... | import com.blbd.volunteer.dao.entity.ChatFriendListEntity;
import com.blbd.volunteer.service.ChatFriendListService;
import com.blbd.volunteer.dao.ChatFriendListEntityMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List; | 1,662 | package com.blbd.volunteer.service.impl;
/**
* @author 1185911254@qq.com
* @description 针对表【chat_friend_list】的数据库操作Service实现
* @createDate 2023-11-05 15:51:06
*/
@Service
public class ChatFriendListServiceImpl implements ChatFriendListService {
@Autowired
ChatFriendListEntityMapper chatFriendListEntityMapper;
// 添加至好友列表(双向添加) | package com.blbd.volunteer.service.impl;
/**
* @author 1185911254@qq.com
* @description 针对表【chat_friend_list】的数据库操作Service实现
* @createDate 2023-11-05 15:51:06
*/
@Service
public class ChatFriendListServiceImpl implements ChatFriendListService {
@Autowired
ChatFriendListEntityMapper chatFriendListEntityMapper;
// 添加至好友列表(双向添加) | public int addFriendList(ChatFriendListEntity chatFriendListEntity){ | 0 | 2023-11-02 05:55:45+00:00 | 4k |
baguchan/BetterWithAquatic | src/main/java/baguchan/better_with_aquatic/mixin/client/EntityPlayerSPMixin.java | [
{
"identifier": "BetterWithAquatic",
"path": "src/main/java/baguchan/better_with_aquatic/BetterWithAquatic.java",
"snippet": "public class BetterWithAquatic implements GameStartEntrypoint, ModInitializer {\n\n\tpublic static final String MOD_ID = \"better_with_aquatic\";\n\tprivate static final boolean ... | import baguchan.better_with_aquatic.BetterWithAquatic;
import baguchan.better_with_aquatic.api.ISwiming;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.player.EntityPlayerSP;
import net.minecraft.core.block.material.Material;
import net.minecraft.core.entity.player.EntityPlayer;
import net.minecraft.core.util.helper.MathHelper;
import net.minecraft.core.world.World;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
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; | 1,849 | package baguchan.better_with_aquatic.mixin.client;
@Mixin(value = EntityPlayerSP.class, remap = false)
public abstract class EntityPlayerSPMixin extends EntityPlayer implements ISwiming {
@Shadow
protected Minecraft mc;
@Unique
private boolean pressedSprint = false;
public EntityPlayerSPMixin(World world) {
super(world);
}
@Shadow
private boolean isBlockTranslucent(int i, int j, int k) {
return false;
}
@Inject(method = "checkInTile", at = @At(value = "HEAD"), cancellable = true)
protected void checkInTile(double d, double d1, double d2, CallbackInfoReturnable<Boolean> cir) {
if (!this.noPhysics && this.isSwimming()) {
int i = MathHelper.floor_double(d);
int j = MathHelper.floor_double(d1);
int k = MathHelper.floor_double(d2);
double d3 = d - (double) i;
double d4 = d2 - (double) k;
if (this.isBlockTranslucent(i, j, k)) {
boolean flag = !this.isBlockTranslucent(i - 1, j, k);
boolean flag1 = !this.isBlockTranslucent(i + 1, j, k);
boolean flag2 = !this.isBlockTranslucent(i, j, k - 1);
boolean flag3 = !this.isBlockTranslucent(i, j, k + 1);
int byte0 = -1;
double d5 = 9999.0;
if (flag && d3 < d5) {
d5 = d3;
byte0 = 0;
}
if (flag1 && 1.0 - d3 < d5) {
d5 = 1.0 - d3;
byte0 = 1;
}
if (flag2 && d4 < d5) {
d5 = d4;
byte0 = 4;
}
if (flag3 && 1.0 - d4 < d5) {
double d6 = 1.0 - d4;
byte0 = 5;
}
float f = 0.1f;
if (byte0 == 0) {
this.xd = -f;
}
if (byte0 == 1) {
this.xd = f;
}
if (byte0 == 4) {
this.zd = -f;
}
if (byte0 == 5) {
this.zd = f;
}
}
cir.setReturnValue(false);
}
}
@Inject(method = "onLivingUpdate", at = @At(value = "TAIL"))
public void onLivingUpdateSwiming(CallbackInfo ci) {
if (this.isUnderLiquid(Material.water) && !this.isSneaking()) { | package baguchan.better_with_aquatic.mixin.client;
@Mixin(value = EntityPlayerSP.class, remap = false)
public abstract class EntityPlayerSPMixin extends EntityPlayer implements ISwiming {
@Shadow
protected Minecraft mc;
@Unique
private boolean pressedSprint = false;
public EntityPlayerSPMixin(World world) {
super(world);
}
@Shadow
private boolean isBlockTranslucent(int i, int j, int k) {
return false;
}
@Inject(method = "checkInTile", at = @At(value = "HEAD"), cancellable = true)
protected void checkInTile(double d, double d1, double d2, CallbackInfoReturnable<Boolean> cir) {
if (!this.noPhysics && this.isSwimming()) {
int i = MathHelper.floor_double(d);
int j = MathHelper.floor_double(d1);
int k = MathHelper.floor_double(d2);
double d3 = d - (double) i;
double d4 = d2 - (double) k;
if (this.isBlockTranslucent(i, j, k)) {
boolean flag = !this.isBlockTranslucent(i - 1, j, k);
boolean flag1 = !this.isBlockTranslucent(i + 1, j, k);
boolean flag2 = !this.isBlockTranslucent(i, j, k - 1);
boolean flag3 = !this.isBlockTranslucent(i, j, k + 1);
int byte0 = -1;
double d5 = 9999.0;
if (flag && d3 < d5) {
d5 = d3;
byte0 = 0;
}
if (flag1 && 1.0 - d3 < d5) {
d5 = 1.0 - d3;
byte0 = 1;
}
if (flag2 && d4 < d5) {
d5 = d4;
byte0 = 4;
}
if (flag3 && 1.0 - d4 < d5) {
double d6 = 1.0 - d4;
byte0 = 5;
}
float f = 0.1f;
if (byte0 == 0) {
this.xd = -f;
}
if (byte0 == 1) {
this.xd = f;
}
if (byte0 == 4) {
this.zd = -f;
}
if (byte0 == 5) {
this.zd = f;
}
}
cir.setReturnValue(false);
}
}
@Inject(method = "onLivingUpdate", at = @At(value = "TAIL"))
public void onLivingUpdateSwiming(CallbackInfo ci) {
if (this.isUnderLiquid(Material.water) && !this.isSneaking()) { | if (BetterWithAquatic.isEnableSwim() && mc.gameSettings.keySprint.isPressed()) { | 0 | 2023-11-08 23:02:14+00:00 | 4k |
Suff99/ExtraShells | common/src/main/java/mc/craig/software/extra_shells/client/models/ShellEntryRegistry.java | [
{
"identifier": "ESModelRegistry",
"path": "common/src/main/java/mc/craig/software/extra_shells/ESModelRegistry.java",
"snippet": "public class ESModelRegistry {\n\n public static SeaBlueShellModel TOMMY_EXT_MODEL;\n public static EngineersShellModel ENGINEERS_EXT_MODEL;\n public static EllenSh... | import mc.craig.software.extra_shells.ESModelRegistry;
import mc.craig.software.extra_shells.ESShellRegistry;
import whocraft.tardis_refined.client.model.blockentity.shell.ShellModelCollection;
import whocraft.tardis_refined.common.tardis.themes.ShellTheme; | 2,714 | package mc.craig.software.extra_shells.client.models;
public class ShellEntryRegistry {
public static void init(){ | package mc.craig.software.extra_shells.client.models;
public class ShellEntryRegistry {
public static void init(){ | ShellModelCollection.registerShellEntry(ESShellRegistry.ENGINEERS.get(), ESModelRegistry.ENGINEERS_EXT_MODEL, ESModelRegistry.ENGINEERS_INT_MODEL); | 0 | 2023-11-04 22:53:31+00:00 | 4k |
Sorenon/GitCraft | src/main/java/com/example/mc/RepoBlockEntity.java | [
{
"identifier": "ExampleMod",
"path": "src/main/java/com/example/ExampleMod.java",
"snippet": "public class ExampleMod implements ModInitializer {\n public static final ResourceLocation OPEN_SCREEN = new ResourceLocation(\"gitcraft\", \"open_screen\");\n\n public static final RepoBlock REPO_BLOCK ... | import com.example.ExampleMod;
import com.example.GCBlocks;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.levelgen.structure.BoundingBox;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.revwalk.RevCommit;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Stack; | 2,728 | package com.example.mc;
public class RepoBlockEntity extends BlockEntity {
public BoundingBox boundingBox;
public String name;
public Git git;
public boolean powered;
public int cooldown = 0;
public Stack<RevCommit> replayingCommits = null;
public RepoBlockEntity(BlockPos blockPos, BlockState blockState) {
super(ExampleMod.REPO_BLOCK_ENTITY, blockPos, blockState);
}
@Override
public void load(CompoundTag compoundTag) {
if (compoundTag.contains("name")) {
boundingBox = new BoundingBox(
compoundTag.getInt("x1"),
compoundTag.getInt("y1"),
compoundTag.getInt("z1"),
compoundTag.getInt("x2"),
compoundTag.getInt("y2"),
compoundTag.getInt("z2")
);
name = compoundTag.getString("name");
}
powered = compoundTag.getBoolean("powered");
this.setLevel(level);
}
@Override
public void setLevel(Level level) {
super.setLevel(level);
if (level instanceof ServerLevel && this.name != null) {
if (this.boundingBox.isInside(this.getBlockPos().getX(), this.getBlockPos().getY(), this.getBlockPos().getZ())) {
level.setBlock(this.getBlockPos(), Blocks.AIR.defaultBlockState(), 2);
((ServerLevel) level).getServer().sendSystemMessage(Component.literal("Cannot place repo within boundaries"));
return;
}
if (git == null) {
try {
git = Git.open(this.getPath().toFile());
} catch (IOException e) {
System.err.println(e);
}
System.out.println(git);
}
}
}
public Path getPath() {
return ExampleMod.repoDir((ServerLevel) this.level, this.name);
}
@Override
protected void saveAdditional(CompoundTag tag) {
if (this.boundingBox != null) {
tag.putInt("x1", boundingBox.minX());
tag.putInt("x2", boundingBox.maxX());
tag.putInt("y1", boundingBox.minY());
tag.putInt("y2", boundingBox.maxY());
tag.putInt("z1", boundingBox.minZ());
tag.putInt("z2", boundingBox.maxZ());
tag.putString("name", name);
}
tag.putBoolean("powered", powered);
}
public void onUse(ServerPlayer serverPlayer, InteractionHand interactionHand) {
if (this.git == null) return;
var stack = serverPlayer.getItemInHand(interactionHand);
if (stack.getItem() == ExampleMod.RESET) {
try { | package com.example.mc;
public class RepoBlockEntity extends BlockEntity {
public BoundingBox boundingBox;
public String name;
public Git git;
public boolean powered;
public int cooldown = 0;
public Stack<RevCommit> replayingCommits = null;
public RepoBlockEntity(BlockPos blockPos, BlockState blockState) {
super(ExampleMod.REPO_BLOCK_ENTITY, blockPos, blockState);
}
@Override
public void load(CompoundTag compoundTag) {
if (compoundTag.contains("name")) {
boundingBox = new BoundingBox(
compoundTag.getInt("x1"),
compoundTag.getInt("y1"),
compoundTag.getInt("z1"),
compoundTag.getInt("x2"),
compoundTag.getInt("y2"),
compoundTag.getInt("z2")
);
name = compoundTag.getString("name");
}
powered = compoundTag.getBoolean("powered");
this.setLevel(level);
}
@Override
public void setLevel(Level level) {
super.setLevel(level);
if (level instanceof ServerLevel && this.name != null) {
if (this.boundingBox.isInside(this.getBlockPos().getX(), this.getBlockPos().getY(), this.getBlockPos().getZ())) {
level.setBlock(this.getBlockPos(), Blocks.AIR.defaultBlockState(), 2);
((ServerLevel) level).getServer().sendSystemMessage(Component.literal("Cannot place repo within boundaries"));
return;
}
if (git == null) {
try {
git = Git.open(this.getPath().toFile());
} catch (IOException e) {
System.err.println(e);
}
System.out.println(git);
}
}
}
public Path getPath() {
return ExampleMod.repoDir((ServerLevel) this.level, this.name);
}
@Override
protected void saveAdditional(CompoundTag tag) {
if (this.boundingBox != null) {
tag.putInt("x1", boundingBox.minX());
tag.putInt("x2", boundingBox.maxX());
tag.putInt("y1", boundingBox.minY());
tag.putInt("y2", boundingBox.maxY());
tag.putInt("z1", boundingBox.minZ());
tag.putInt("z2", boundingBox.maxZ());
tag.putString("name", name);
}
tag.putBoolean("powered", powered);
}
public void onUse(ServerPlayer serverPlayer, InteractionHand interactionHand) {
if (this.git == null) return;
var stack = serverPlayer.getItemInHand(interactionHand);
if (stack.getItem() == ExampleMod.RESET) {
try { | GCBlocks.load(level, this.boundingBox, this.getPath().resolve("blocks.gc")); | 1 | 2023-11-05 03:18:32+00:00 | 4k |
Svydovets-Bobocode-Java-Ultimate-3-0/Bring | src/test/java/com/bobocode/svydovets/ioc/util/NameResolverTest.java | [
{
"identifier": "resolveBeanName",
"path": "src/main/java/svydovets/util/NameResolver.java",
"snippet": "public static String resolveBeanName(Class<?> beanClass) {\n log.trace(\"Call resolveBeanName({}) for class base bean\", beanClass);\n if (beanClass.isAnnotationPresent(RestController.class)) {... | import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static svydovets.util.NameResolver.resolveBeanName;
import static svydovets.util.NameResolver.resolveRequestParameterName;
import java.util.Arrays;
import com.bobocode.svydovets.source.base.CommonService;
import com.bobocode.svydovets.source.base.MessageService;
import com.bobocode.svydovets.source.config.BasePackageBeansConfig;
import com.bobocode.svydovets.source.config.BasePackageWithAdditionalBeansConfig;
import com.bobocode.svydovets.source.interfaces.NonInterfaceConfiguration;
import com.bobocode.svydovets.source.web.AllMethodRestController;
import com.bobocode.svydovets.source.web.SimpleRestController;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import svydovets.core.annotation.Bean;
import svydovets.core.annotation.Component;
import svydovets.core.annotation.Configuration;
import svydovets.web.annotation.PathVariable;
import svydovets.web.annotation.RequestParam;
import svydovets.web.annotation.RestController; | 1,673 | package com.bobocode.svydovets.ioc.util;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class NameResolverTest {
@Test
@Order(1)
public void shouldReturnComponentAnnotationValueIfNameIsSpecifiedExplicitly() {
String beanName = MessageService.class.getAnnotation(Component.class).value();
assertThat(beanName).isEqualTo(resolveBeanName(MessageService.class));
}
@Test
@Order(2)
public void shouldReturnSimpleClassNameIfComponentAnnotationValueIsNotSpecifiedExplicitly() {
String beanName = "commonService";
assertThat(beanName).isEqualTo(resolveBeanName(CommonService.class));
}
@Test
@Order(3)
public void shouldReturnConfigurationAnnotationValueIfNameIsSpecifiedExplicitly() {
String beanName = NonInterfaceConfiguration.class.getAnnotation(Configuration.class).value();
assertThat(beanName).isEqualTo(resolveBeanName(NonInterfaceConfiguration.class));
}
@Test
@Order(4)
public void shouldReturnSimpleClassNameIfConfigurationAnnotationValueIsNotSpecifiedExplicitly() {
String beanName = "basePackageBeansConfig"; | package com.bobocode.svydovets.ioc.util;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class NameResolverTest {
@Test
@Order(1)
public void shouldReturnComponentAnnotationValueIfNameIsSpecifiedExplicitly() {
String beanName = MessageService.class.getAnnotation(Component.class).value();
assertThat(beanName).isEqualTo(resolveBeanName(MessageService.class));
}
@Test
@Order(2)
public void shouldReturnSimpleClassNameIfComponentAnnotationValueIsNotSpecifiedExplicitly() {
String beanName = "commonService";
assertThat(beanName).isEqualTo(resolveBeanName(CommonService.class));
}
@Test
@Order(3)
public void shouldReturnConfigurationAnnotationValueIfNameIsSpecifiedExplicitly() {
String beanName = NonInterfaceConfiguration.class.getAnnotation(Configuration.class).value();
assertThat(beanName).isEqualTo(resolveBeanName(NonInterfaceConfiguration.class));
}
@Test
@Order(4)
public void shouldReturnSimpleClassNameIfConfigurationAnnotationValueIsNotSpecifiedExplicitly() {
String beanName = "basePackageBeansConfig"; | assertThat(beanName).isEqualTo(resolveBeanName(BasePackageBeansConfig.class)); | 4 | 2023-11-07 06:36:50+00:00 | 4k |
oneqxz/RiseLoader | src/main/java/me/oneqxz/riseloader/fxml/components/impl/controllers/UpdatingController.java | [
{
"identifier": "RiseLoaderMain",
"path": "src/main/java/me/oneqxz/riseloader/RiseLoaderMain.java",
"snippet": "public class RiseLoaderMain {\n\n private static final Logger log = LogManager.getLogger(\"RiseLoader\");\n\n public static void main(String[] args) {\n log.info(\"Starting RiseLo... | import javafx.application.Platform;
import javafx.scene.control.ProgressBar;
import me.oneqxz.riseloader.RiseLoaderMain;
import me.oneqxz.riseloader.RiseUI;
import me.oneqxz.riseloader.fxml.components.impl.ErrorBox;
import me.oneqxz.riseloader.fxml.controllers.Controller;
import me.oneqxz.riseloader.utils.OSUtils;
import me.oneqxz.riseloader.utils.requests.Requests;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Random; | 2,798 | package me.oneqxz.riseloader.fxml.components.impl.controllers;
public class UpdatingController extends Controller {
ProgressBar mainProgress;
@Override
protected void init() {
this.mainProgress = (ProgressBar) root.lookup("#mainProgress");
new Thread(() ->
{
try {
String currentFilePath = this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
String tempFilePath = "update" + new Random().nextInt(10000) + ".temp_jar";
| package me.oneqxz.riseloader.fxml.components.impl.controllers;
public class UpdatingController extends Controller {
ProgressBar mainProgress;
@Override
protected void init() {
this.mainProgress = (ProgressBar) root.lookup("#mainProgress");
new Thread(() ->
{
try {
String currentFilePath = this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
String tempFilePath = "update" + new Random().nextInt(10000) + ".temp_jar";
| downloadUpdate(RiseUI.serverIp + "/file/loader.jar", tempFilePath); | 1 | 2023-11-01 01:40:52+00:00 | 4k |
YufiriaMazenta/CrypticLib | nms/v1_18_R1/src/main/java/crypticlib/nms/tile/v1_18_R1/V1_18_R1NbtTileEntity.java | [
{
"identifier": "V1_18_R1NbtTagCompound",
"path": "nms/v1_18_R1/src/main/java/crypticlib/nms/nbt/v1_18_R1/V1_18_R1NbtTagCompound.java",
"snippet": "public class V1_18_R1NbtTagCompound extends NbtTagCompound {\n\n public V1_18_R1NbtTagCompound() {\n super(V1_18_R1NbtTranslator.INSTANCE);\n }... | import crypticlib.nms.nbt.v1_18_R1.V1_18_R1NbtTagCompound;
import crypticlib.nms.tile.NbtTileEntity;
import crypticlib.util.ReflectUtil;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.level.block.entity.TileEntity;
import org.bukkit.block.BlockState;
import org.bukkit.craftbukkit.v1_18_R1.block.CraftBlockEntityState;
import java.lang.reflect.Method; | 1,920 | package crypticlib.nms.tile.v1_18_R1;
public class V1_18_R1NbtTileEntity extends NbtTileEntity {
public V1_18_R1NbtTileEntity(BlockState bukkit) {
super(bukkit);
}
@Override
public void saveNbtToTileEntity() {
CraftBlockEntityState<?> craftTileEntity = ((CraftBlockEntityState<?>) bukkit); | package crypticlib.nms.tile.v1_18_R1;
public class V1_18_R1NbtTileEntity extends NbtTileEntity {
public V1_18_R1NbtTileEntity(BlockState bukkit) {
super(bukkit);
}
@Override
public void saveNbtToTileEntity() {
CraftBlockEntityState<?> craftTileEntity = ((CraftBlockEntityState<?>) bukkit); | Method getSnapshotMethod = ReflectUtil.getDeclaredMethod(CraftBlockEntityState.class, "getSnapshot"); | 2 | 2023-11-07 12:39:20+00:00 | 4k |
Traben-0/resource_explorer | common/src/main/java/traben/resource_explorer/explorer/REResourceFile.java | [
{
"identifier": "SpriteAtlasTextureAccessor",
"path": "common/src/main/java/traben/resource_explorer/mixin/SpriteAtlasTextureAccessor.java",
"snippet": "@Mixin(SpriteAtlasTexture.class)\npublic interface SpriteAtlasTextureAccessor {\n @Accessor\n int getWidth();\n\n @Accessor\n int getHeight... | import net.minecraft.client.MinecraftClient;
import net.minecraft.client.font.MultilineText;
import net.minecraft.client.texture.AbstractTexture;
import net.minecraft.client.texture.NativeImage;
import net.minecraft.client.texture.NativeImageBackedTexture;
import net.minecraft.client.texture.SpriteAtlasTexture;
import net.minecraft.resource.Resource;
import net.minecraft.resource.metadata.ResourceMetadata;
import net.minecraft.text.OrderedText;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import org.jetbrains.annotations.Nullable;
import traben.resource_explorer.mixin.SpriteAtlasTextureAccessor;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import static traben.resource_explorer.explorer.REExplorer.outputResourceToPackInternal; | 2,250 | }
@Override
public int hashCode() {
return Objects.hash(identifier);
}
@Override
boolean canExport() {
return resource != null;
}
@Override
public String toString() {
return toString(0);
}
@Override
public String toString(int indent) {
return " ".repeat(Math.max(0, indent)) + "\\ " +
displayName + "\n";
}
@Override
public String getDisplayName() {
return displayName;
}
@Override
OrderedText getDisplayText() {
return displayText;
}
@Override
List<Text> getExtraText(boolean smallMode) {
ArrayList<Text> lines = new ArrayList<>();
lines.add(trimmedTextToWidth(" " + translated("resource_explorer.detail.type") + ": " + fileType.toString() +
(hasMetaData ? " + " + translated("resource_explorer.detail.metadata") : "")));
if (resource != null) {
lines.add(trimmedTextToWidth(" " + translated("resource_explorer.detail.pack") + ": " + resource.getResourcePackName().replace("file/", "")));
} else {
lines.add(trimmedTextToWidth("§8§o " + translated("resource_explorer.detail.built_msg")));
}
if (smallMode) return lines;
switch (fileType) {
case PNG -> {
lines.add(trimmedTextToWidth(" " + translated("resource_explorer.detail.height") + ": " + height));
lines.add(trimmedTextToWidth(" " + translated("resource_explorer.detail.width") + ": " + width));
if (hasMetaData && height > width && height % width == 0) {
lines.add(trimmedTextToWidth(" " + translated("resource_explorer.detail.frame_count") + ": " + (height / width)));
}
}
case TXT, PROPERTIES, JSON -> {
if (readTextByLineBreaks != null) {
lines.add(trimmedTextToWidth(" " + translated("resource_explorer.detail.lines") + ": " + height));
lines.add(trimmedTextToWidth(" " + translated("resource_explorer.detail.character_count") + ": " + width));
}
}
default -> {
}//lines.add(trimmedTextToWidth(" //todo "));//todo
}
return lines;
}
MultilineText getTextLines() {
if (!fileType.isRawTextType())
return MultilineText.EMPTY;
if (readTextByLineBreaks == null) {
if (resource != null) {
try {
InputStream in = resource.getInputStream();
try {
ArrayList<Text> text = new ArrayList<>();
String readString = new String(in.readAllBytes(), StandardCharsets.UTF_8);
in.close();
//make tabs smaller
String reducedTabs = readString.replaceAll("(\t| {4})", " ");
String[] splitByLines = reducedTabs.split("\n");
width = readString.length();
height = splitByLines.length;
//trim lines to width now
for (int i = 0; i < splitByLines.length; i++) {
splitByLines[i] = trimmedStringToWidth(splitByLines[i], 178);
}
int lineCount = 0;
for (String line :
splitByLines) {
lineCount++;
if (lineCount > 512) {//todo set limit in config
text.add(Text.of("§l§4-- TEXT LONGER THAN " + 512 + " LINES --"));
text.add(Text.of("§r§o " + (height - lineCount) + " lines skipped."));
text.add(Text.of("§l§4-- END --"));
break;
}
text.add(Text.of(line));
}
readTextByLineBreaks = MultilineText.createFromTexts(MinecraftClient.getInstance().textRenderer, text);
} catch (Exception e) {
//resource.close();
in.close();
readTextByLineBreaks = MultilineText.EMPTY;
}
} catch (Exception ignored) {
readTextByLineBreaks = MultilineText.EMPTY;
}
} else {
readTextByLineBreaks = MultilineText.create(MinecraftClient.getInstance().textRenderer, Text.of(" ERROR: no file info could be read"));
}
}
return readTextByLineBreaks;
}
public void exportToOutputPack(REExplorer.REExportContext context) { | package traben.resource_explorer.explorer;
public class REResourceFile extends REResourceEntry {
public static final REResourceFile FAILED_FILE = new REResourceFile();
public final Identifier identifier;
@Nullable
public final Resource resource;
public final FileType fileType;
public final LinkedList<String> folderStructureList;
final AbstractTexture abstractTexture;
private final String displayName;
private final OrderedText displayText;
public MultilineText readTextByLineBreaks = null;
public int height = 1;
public int width = 1;
boolean imageDone = false;
Boolean hasMetaData = null;
private REResourceFile() {
//failed file
this.identifier = new Identifier("search_failed:fail");
this.resource = null;
this.abstractTexture = null;
this.fileType = FileType.OTHER;
displayName = "search_failed";
folderStructureList = new LinkedList<>();
this.displayText = Text.of("search_failed").asOrderedText();
}
public REResourceFile(Identifier identifier, AbstractTexture texture) {
this.identifier = identifier;
this.resource = null;
this.abstractTexture = texture;
//try to capture some sizes
if (abstractTexture instanceof SpriteAtlasTexture atlasTexture) {
width = ((SpriteAtlasTextureAccessor) atlasTexture).getWidth();
height = ((SpriteAtlasTextureAccessor) atlasTexture).getHeight();
} else if (abstractTexture instanceof NativeImageBackedTexture nativeImageBackedTexture) {
NativeImage image = nativeImageBackedTexture.getImage();
if (image != null) {
width = image.getWidth();
height = image.getHeight();
}
}
this.fileType = FileType.getType(this.identifier);
//split out folder hierarchy
String[] splitDirectories = this.identifier.getPath().split("/");
LinkedList<String> directories = new LinkedList<>(List.of(splitDirectories));
//final entry is display file name
displayName = directories.getLast();
directories.removeLast();
//remainder is folder hierarchy, which can be empty
folderStructureList = directories;
this.displayText = trimmedTextToWidth(displayName).asOrderedText();
}
public REResourceFile(Identifier identifier, @Nullable Resource resource) {
this.identifier = identifier;
this.resource = resource;
this.abstractTexture = null;
this.fileType = FileType.getType(this.identifier);
//split out folder hierarchy
String[] splitDirectories = this.identifier.getPath().split("/");
LinkedList<String> directories = new LinkedList<>(List.of(splitDirectories));
//final entry is display file name
displayName = directories.getLast();
directories.removeLast();
//remainder is folder hierarchy, which can be empty
folderStructureList = directories;
this.displayText = trimmedTextToWidth(displayName).asOrderedText();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
REResourceFile that = (REResourceFile) o;
return identifier.equals(that.identifier);
}
@Override
public int hashCode() {
return Objects.hash(identifier);
}
@Override
boolean canExport() {
return resource != null;
}
@Override
public String toString() {
return toString(0);
}
@Override
public String toString(int indent) {
return " ".repeat(Math.max(0, indent)) + "\\ " +
displayName + "\n";
}
@Override
public String getDisplayName() {
return displayName;
}
@Override
OrderedText getDisplayText() {
return displayText;
}
@Override
List<Text> getExtraText(boolean smallMode) {
ArrayList<Text> lines = new ArrayList<>();
lines.add(trimmedTextToWidth(" " + translated("resource_explorer.detail.type") + ": " + fileType.toString() +
(hasMetaData ? " + " + translated("resource_explorer.detail.metadata") : "")));
if (resource != null) {
lines.add(trimmedTextToWidth(" " + translated("resource_explorer.detail.pack") + ": " + resource.getResourcePackName().replace("file/", "")));
} else {
lines.add(trimmedTextToWidth("§8§o " + translated("resource_explorer.detail.built_msg")));
}
if (smallMode) return lines;
switch (fileType) {
case PNG -> {
lines.add(trimmedTextToWidth(" " + translated("resource_explorer.detail.height") + ": " + height));
lines.add(trimmedTextToWidth(" " + translated("resource_explorer.detail.width") + ": " + width));
if (hasMetaData && height > width && height % width == 0) {
lines.add(trimmedTextToWidth(" " + translated("resource_explorer.detail.frame_count") + ": " + (height / width)));
}
}
case TXT, PROPERTIES, JSON -> {
if (readTextByLineBreaks != null) {
lines.add(trimmedTextToWidth(" " + translated("resource_explorer.detail.lines") + ": " + height));
lines.add(trimmedTextToWidth(" " + translated("resource_explorer.detail.character_count") + ": " + width));
}
}
default -> {
}//lines.add(trimmedTextToWidth(" //todo "));//todo
}
return lines;
}
MultilineText getTextLines() {
if (!fileType.isRawTextType())
return MultilineText.EMPTY;
if (readTextByLineBreaks == null) {
if (resource != null) {
try {
InputStream in = resource.getInputStream();
try {
ArrayList<Text> text = new ArrayList<>();
String readString = new String(in.readAllBytes(), StandardCharsets.UTF_8);
in.close();
//make tabs smaller
String reducedTabs = readString.replaceAll("(\t| {4})", " ");
String[] splitByLines = reducedTabs.split("\n");
width = readString.length();
height = splitByLines.length;
//trim lines to width now
for (int i = 0; i < splitByLines.length; i++) {
splitByLines[i] = trimmedStringToWidth(splitByLines[i], 178);
}
int lineCount = 0;
for (String line :
splitByLines) {
lineCount++;
if (lineCount > 512) {//todo set limit in config
text.add(Text.of("§l§4-- TEXT LONGER THAN " + 512 + " LINES --"));
text.add(Text.of("§r§o " + (height - lineCount) + " lines skipped."));
text.add(Text.of("§l§4-- END --"));
break;
}
text.add(Text.of(line));
}
readTextByLineBreaks = MultilineText.createFromTexts(MinecraftClient.getInstance().textRenderer, text);
} catch (Exception e) {
//resource.close();
in.close();
readTextByLineBreaks = MultilineText.EMPTY;
}
} catch (Exception ignored) {
readTextByLineBreaks = MultilineText.EMPTY;
}
} else {
readTextByLineBreaks = MultilineText.create(MinecraftClient.getInstance().textRenderer, Text.of(" ERROR: no file info could be read"));
}
}
return readTextByLineBreaks;
}
public void exportToOutputPack(REExplorer.REExportContext context) { | boolean exported = outputResourceToPackInternal(this); | 1 | 2023-11-05 17:35:39+00:00 | 4k |
cypcodestudio/rbacspring | rbacspring/src/main/java/com/cypcode/rbacspring/service/WUserService.java | [
{
"identifier": "Role",
"path": "rbacspring/src/main/java/com/cypcode/rbacspring/entity/Role.java",
"snippet": "@Entity\n@Table(name = \"Role\")\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class Role implements Serializable{\n\n\tprivate static final long serialVersionUID = 5926468583005150707L... | import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import com.cypcode.rbacspring.entity.Role;
import com.cypcode.rbacspring.entity.User;
import com.cypcode.rbacspring.entity.UserRole;
import com.cypcode.rbacspring.entity.dto.UserRegisterRequestDTO;
import com.cypcode.rbacspring.repository.IUserRepository;
import com.cypcode.rbacspring.repository.IUserRoleRepository;
import com.cypcode.rbacspring.security.SecurityPrincipal;
import jakarta.transaction.Transactional; | 2,904 | package com.cypcode.rbacspring.service;
@Service
@Transactional
public class WUserService implements UserDetailsService {
private static final Logger LOG = LoggerFactory.getLogger(WUserService.class);
@Autowired
private IUserRepository userRepository;
@Autowired
private IUserRoleRepository userRoleRepository;
@Autowired
WRoleService roleService;
@Override
public UserDetails loadUserByUsername(String username) { | package com.cypcode.rbacspring.service;
@Service
@Transactional
public class WUserService implements UserDetailsService {
private static final Logger LOG = LoggerFactory.getLogger(WUserService.class);
@Autowired
private IUserRepository userRepository;
@Autowired
private IUserRoleRepository userRoleRepository;
@Autowired
WRoleService roleService;
@Override
public UserDetails loadUserByUsername(String username) { | User user = userRepository.findByUsername(username); | 1 | 2023-11-05 05:38:31+00:00 | 4k |
txline0420/nacos-dm | core/src/main/java/com/alibaba/nacos/core/control/remote/RemoteTpsCheckRequestParser.java | [
{
"identifier": "Request",
"path": "api/src/main/java/com/alibaba/nacos/api/remote/request/Request.java",
"snippet": "@SuppressWarnings(\"PMD.AbstractClassShouldStartWithAbstractNamingRule\")\npublic abstract class Request implements Payload {\n \n private final Map<String, String> headers = new T... | import com.alibaba.nacos.api.remote.request.Request;
import com.alibaba.nacos.api.remote.request.RequestMeta;
import com.alibaba.nacos.plugin.control.tps.request.TpsCheckRequest; | 1,934 | /*
*
* Copyright 1999-2021 Alibaba Group Holding 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 com.alibaba.nacos.core.control.remote;
/**
* remote tps check request parser.
*
* @author shiyiyue
*/
@SuppressWarnings("PMD.AbstractClassShouldStartWithAbstractNamingRule")
public abstract class RemoteTpsCheckRequestParser {
public RemoteTpsCheckRequestParser() {
RemoteTpsCheckRequestParserRegistry.register(this);
}
/**
* parse tps check request.
*
* @param request request.
* @param meta meta.
* @return
*/ | /*
*
* Copyright 1999-2021 Alibaba Group Holding 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 com.alibaba.nacos.core.control.remote;
/**
* remote tps check request parser.
*
* @author shiyiyue
*/
@SuppressWarnings("PMD.AbstractClassShouldStartWithAbstractNamingRule")
public abstract class RemoteTpsCheckRequestParser {
public RemoteTpsCheckRequestParser() {
RemoteTpsCheckRequestParserRegistry.register(this);
}
/**
* parse tps check request.
*
* @param request request.
* @param meta meta.
* @return
*/ | public abstract TpsCheckRequest parse(Request request, RequestMeta meta); | 2 | 2023-11-02 01:34:09+00:00 | 4k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.