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 |
|---|---|---|---|---|---|---|---|---|---|---|
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; | 917 | 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) { | 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(); | 0 | 2023-11-05 17:35:39+00:00 | 2k |
cypcodestudio/rbacspring | rbacspring/src/main/java/com/cypcode/rbacspring/security/SecurityPrincipal.java | [
{
"identifier": "User",
"path": "rbacspring/src/main/java/com/cypcode/rbacspring/entity/User.java",
"snippet": "@Entity\n@Table(name = \"WUser\")\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class User implements Serializable, UserDetails{\n\n\tprivate static final long serialVersionUID = 592646... | import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import com.cypcode.rbacspring.entity.User;
import com.cypcode.rbacspring.service.WUserService; | 1,570 | /**
*
*/
package com.cypcode.rbacspring.security;
@Service
public class SecurityPrincipal {
private static SecurityPrincipal securityPrincipal = null;
private Authentication principal = SecurityContextHolder.getContext().getAuthentication();
| /**
*
*/
package com.cypcode.rbacspring.security;
@Service
public class SecurityPrincipal {
private static SecurityPrincipal securityPrincipal = null;
private Authentication principal = SecurityContextHolder.getContext().getAuthentication();
| private static WUserService userService; | 1 | 2023-11-05 05:38:31+00:00 | 2k |
txline0420/nacos-dm | plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/dm/TenantInfoMapperByDm.java | [
{
"identifier": "DataSourceConstant",
"path": "plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/constants/DataSourceConstant.java",
"snippet": "public class DataSourceConstant {\n public static final String MYSQL = \"mysql\";\n public static final String DM = \"dm\";\n public... | import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant;
import com.alibaba.nacos.plugin.datasource.mapper.AbstractMapper;
import com.alibaba.nacos.plugin.datasource.mapper.TenantInfoMapper; | 1,426 | /*
* Copyright 1999-2022 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.plugin.datasource.impl.dm;
/**
* The DM implementation of TenantInfoMapper.
*
* @author TXLINE
**/
public class TenantInfoMapperByDm extends AbstractMapper implements TenantInfoMapper {
@Override
public String getDataSource() { | /*
* Copyright 1999-2022 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.plugin.datasource.impl.dm;
/**
* The DM implementation of TenantInfoMapper.
*
* @author TXLINE
**/
public class TenantInfoMapperByDm extends AbstractMapper implements TenantInfoMapper {
@Override
public String getDataSource() { | return DataSourceConstant.DM; | 0 | 2023-11-02 01:34:09+00:00 | 2k |
Kinyarasam/RideShareX | RideShareX/src/main/java/com/ridesharex/controller/UserController.java | [
{
"identifier": "User",
"path": "RideShareX/src/main/java/com/ridesharex/model/User.java",
"snippet": "@Entity\n@Table(name = \"users\")\npublic class User {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(name = \"username\", unique = true)\n pr... | import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.ridesharex.model.User;
import com.ridesharex.service.UserService; | 759 | package com.ridesharex.controller;
@RestController
@RequestMapping("/users")
public class UserController {
private final UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping | package com.ridesharex.controller;
@RestController
@RequestMapping("/users")
public class UserController {
private final UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping | public List<User> getAllUsers() { | 0 | 2023-11-07 06:52:56+00:00 | 2k |
MCMDEV/chatchannels | src/main/java/dev/gamemode/chatchannels/config/ConfigReader.java | [
{
"identifier": "Channel",
"path": "src/main/java/dev/gamemode/chatchannels/model/channel/Channel.java",
"snippet": "public interface Channel {\n\n boolean canSee(Audience audience);\n\n String getName();\n\n Component getDisplayName();\n\n Collection<Audience> getViewers();\n\n ChannelRenderer get... | import com.electronwill.nightconfig.core.Config;
import com.electronwill.nightconfig.core.file.FileConfig;
import com.electronwill.nightconfig.core.file.FileNotFoundAction;
import dev.gamemode.chatchannels.model.channel.Channel;
import dev.gamemode.chatchannels.model.channel.SetCollectionChannel;
import dev.gamemode.chatchannels.model.provider.ChannelProvider;
import dev.gamemode.chatchannels.model.provider.MapChannelProvider;
import dev.gamemode.chatchannels.renderer.ChannelRenderer;
import dev.gamemode.chatchannels.renderer.ConfiguredRenderer;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.stream.Collectors;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage; | 1,161 | package dev.gamemode.chatchannels.config;
public class ConfigReader {
private FileConfig fileConfig;
public void load(File dataFolder) {
if (!dataFolder.exists()) {
dataFolder.mkdirs();
}
File filePath = new File(dataFolder, "config.yml");
this.fileConfig = FileConfig.builder(filePath)
.onFileNotFound(
FileNotFoundAction.copyData(ConfigReader.class.getResourceAsStream("/config.yml")))
.charset(StandardCharsets.UTF_8)
.build();
this.fileConfig.load();
}
| package dev.gamemode.chatchannels.config;
public class ConfigReader {
private FileConfig fileConfig;
public void load(File dataFolder) {
if (!dataFolder.exists()) {
dataFolder.mkdirs();
}
File filePath = new File(dataFolder, "config.yml");
this.fileConfig = FileConfig.builder(filePath)
.onFileNotFound(
FileNotFoundAction.copyData(ConfigReader.class.getResourceAsStream("/config.yml")))
.charset(StandardCharsets.UTF_8)
.build();
this.fileConfig.load();
}
| public ChannelProvider configureProvider() { | 2 | 2023-11-07 20:33:27+00:00 | 2k |
data-harness-cloud/data_harness-be | common/common-quartz/src/main/java/supie/common/quartz/utils/QuaryzUtil.java | [
{
"identifier": "JobFieldType",
"path": "common/common-quartz/src/main/java/supie/common/quartz/object/JobFieldType.java",
"snippet": "public enum JobFieldType {\n\n JOB_NAME(\"任务名称\"),\n JOB_GROUP(\"任务分组\"),\n DESCRIPTION(\"任务描述\"),\n JOB_CLASS_NAME(\"作业执行类\"),\n CRON_EXPRESSION(\"Cron表达... | import cn.hutool.core.util.ReflectUtil;
import cn.hutool.json.JSONUtil;
import supie.common.quartz.object.JobField;
import supie.common.quartz.object.JobFieldType;
import supie.common.quartz.object.QuartzJobData;
import supie.common.quartz.object.QuartzJobParam;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.Map; | 782 | package supie.common.quartz.utils;
/**
* 描述:
*
* @author 王立宏
* @date 2023/10/24 10:53
* @path SDT-supie.common.quartz.utils-QuaryzUtil
*/
public class QuaryzUtil {
public static <MDto> QuartzJobParam modelDtoToJobParam(MDto model) {
QuartzJobParam quartzJobParam = new QuartzJobParam();
Class<?> modelClass = model.getClass();
Field[] fields = ReflectUtil.getFields(modelClass);
for (Field field : fields) {
Object fieldValue = ReflectUtil.getFieldValue(model, field);
if (fieldValue == null) continue;
if (field.isAnnotationPresent(JobField.class)) {
JobField jobField = field.getAnnotation(JobField.class); | package supie.common.quartz.utils;
/**
* 描述:
*
* @author 王立宏
* @date 2023/10/24 10:53
* @path SDT-supie.common.quartz.utils-QuaryzUtil
*/
public class QuaryzUtil {
public static <MDto> QuartzJobParam modelDtoToJobParam(MDto model) {
QuartzJobParam quartzJobParam = new QuartzJobParam();
Class<?> modelClass = model.getClass();
Field[] fields = ReflectUtil.getFields(modelClass);
for (Field field : fields) {
Object fieldValue = ReflectUtil.getFieldValue(model, field);
if (fieldValue == null) continue;
if (field.isAnnotationPresent(JobField.class)) {
JobField jobField = field.getAnnotation(JobField.class); | JobFieldType jobFieldType = jobField.value(); | 0 | 2023-11-04 12:36:44+00:00 | 2k |
FTC-ORBIT/14872-2024-CenterStage | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Sensors/OrbitGyro.java | [
{
"identifier": "PID",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/OrbitUtils/PID.java",
"snippet": "public class PID {\n private static final ElapsedTime timer = new ElapsedTime();\n public double kP = 0;\n public double kI = 0;\n public double kD = 0;\n public double ... | import com.acmerobotics.dashboard.config.Config;
import com.qualcomm.hardware.bosch.BNO055IMU;
import com.qualcomm.hardware.bosch.JustLoggingAccelerationIntegrator;
import com.qualcomm.robotcore.hardware.HardwareMap;
import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit;
import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder;
import org.firstinspires.ftc.robotcore.external.navigation.AxesReference;
import org.firstinspires.ftc.teamcode.OrbitUtils.PID;
import org.firstinspires.ftc.teamcode.robotData.GlobalData; | 774 |
package org.firstinspires.ftc.teamcode.Sensors;
@Config
public class OrbitGyro {
public static BNO055IMU imu;
public static double lastAngle = 0;
static double currentAngle = 0;
public static double kP = 0;
public static double kI = 0;
public static double kD = 0; |
package org.firstinspires.ftc.teamcode.Sensors;
@Config
public class OrbitGyro {
public static BNO055IMU imu;
public static double lastAngle = 0;
static double currentAngle = 0;
public static double kP = 0;
public static double kI = 0;
public static double kD = 0; | static PID anglePID = new PID(kP, kI, kD, 0, 0); | 0 | 2023-11-03 13:32:48+00:00 | 2k |
beminder/BeautyMinder | java/src/test/java/app/beautyminder/controller/vision/VisionApiControllerTest.java | [
{
"identifier": "VisionController",
"path": "java/src/main/java/app/beautyminder/controller/ocr/VisionController.java",
"snippet": "@RestController\n@RequestMapping(\"/vision\")\n@RequiredArgsConstructor\npublic class VisionController {\n private final VisionService visionService;\n\n @PostMapping... | import app.beautyminder.controller.ocr.VisionController;
import app.beautyminder.service.vision.VisionService;
import lombok.extern.slf4j.Slf4j;
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.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.io.IOException;
import java.util.Optional;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; | 1,104 | package app.beautyminder.controller.vision;
@Slf4j
@ActiveProfiles({"awsBasic", "test"})
public class VisionApiControllerTest {
private MockMvc mockMvc;
@Mock
private VisionService visionService;
@InjectMocks | package app.beautyminder.controller.vision;
@Slf4j
@ActiveProfiles({"awsBasic", "test"})
public class VisionApiControllerTest {
private MockMvc mockMvc;
@Mock
private VisionService visionService;
@InjectMocks | private VisionController visionController; | 0 | 2023-11-01 12:37:16+00:00 | 2k |
hacks1ash/keycloak-spring-boot-adapter | src/main/java/io/github/hacks1ash/keycloak/adapter/utils/SecurityContextHelper.java | [
{
"identifier": "KeycloakAuthentication",
"path": "src/main/java/io/github/hacks1ash/keycloak/adapter/KeycloakAuthentication.java",
"snippet": "@Getter\n@Transient\n@EqualsAndHashCode(callSuper = true)\npublic class KeycloakAuthentication<T extends DefaultKeycloakUser> extends JwtAuthenticationToken {\n... | import io.github.hacks1ash.keycloak.adapter.KeycloakAuthentication;
import io.github.hacks1ash.keycloak.adapter.model.DefaultKeycloakUser;
import org.springframework.security.core.context.SecurityContextHolder; | 654 | package io.github.hacks1ash.keycloak.adapter.utils;
/**
* Helper class for accessing the security context of the current user. Provides utility methods
* related to the security context, particularly for Keycloak users.
*/
public class SecurityContextHelper {
private SecurityContextHelper() {
throw new IllegalStateException("SecurityContextHelper class");
}
/**
* Retrieves the current authenticated user from the security context. This method casts the
* current authentication object to a KeycloakAuthentication and returns the associated
* authenticated user.
*
* @param <T> The type parameter extending AbstractKeycloakUser.
* @return The current authenticated user of type T.
* @throws ClassCastException if the current authentication object is not of type
* KeycloakAuthentication.
*/
@SuppressWarnings("unchecked")
public static <T extends DefaultKeycloakUser> T getCurrentUser() { | package io.github.hacks1ash.keycloak.adapter.utils;
/**
* Helper class for accessing the security context of the current user. Provides utility methods
* related to the security context, particularly for Keycloak users.
*/
public class SecurityContextHelper {
private SecurityContextHelper() {
throw new IllegalStateException("SecurityContextHelper class");
}
/**
* Retrieves the current authenticated user from the security context. This method casts the
* current authentication object to a KeycloakAuthentication and returns the associated
* authenticated user.
*
* @param <T> The type parameter extending AbstractKeycloakUser.
* @return The current authenticated user of type T.
* @throws ClassCastException if the current authentication object is not of type
* KeycloakAuthentication.
*/
@SuppressWarnings("unchecked")
public static <T extends DefaultKeycloakUser> T getCurrentUser() { | return ((KeycloakAuthentication<T>) SecurityContextHolder.getContext().getAuthentication()) | 0 | 2023-11-09 09:18:02+00:00 | 2k |
Xrayya/java-cli-pbpu | src/main/java/com/CashierAppUtil/Auth.java | [
{
"identifier": "Cashier",
"path": "src/main/java/com/Model/Cashier.java",
"snippet": "public class Cashier extends Employee {\n public Cashier(UUID employeeID, String name, String username, String password) {\n super(employeeID, name, username, password);\n }\n\n public Cashier(Employee... | import java.util.List;
import com.Model.Cashier;
import com.Model.Employee;
import com.Model.Manager;
import com.RecordUtil.Record; | 659 | package com.CashierAppUtil;
/**
* Auth
*/
public class Auth {
public static Employee authenticate(String username, String password) { | package com.CashierAppUtil;
/**
* Auth
*/
public class Auth {
public static Employee authenticate(String username, String password) { | List<Manager> managers = new Record<Manager>("managers", Manager[].class).readRecordFile(); | 3 | 2023-11-09 05:26:20+00:00 | 2k |
FallenDeity/GameEngine2DJava | src/main/java/engine/observers/EventSystem.java | [
{
"identifier": "GameObject",
"path": "src/main/java/engine/components/GameObject.java",
"snippet": "public class GameObject {\n\tprivate static int ID_COUNTER = 0;\n\tprivate final List<Component> components = new ArrayList<>();\n\tpublic transient Transform transform;\n\tprivate String name;\n\tprivat... | import engine.components.GameObject;
import engine.observers.events.Event;
import java.util.ArrayList;
import java.util.List; | 1,085 | package engine.observers;
public class EventSystem {
private static EventSystem instance = null;
private final List<Observer> observers;
private EventSystem() {
observers = new ArrayList<>();
}
public static EventSystem getInstance() {
if (instance == null) {
instance = new EventSystem();
}
return instance;
}
public void addObserver(Observer observer) {
observers.add(observer);
}
public void removeObserver(Observer observer) {
observers.remove(observer);
}
| package engine.observers;
public class EventSystem {
private static EventSystem instance = null;
private final List<Observer> observers;
private EventSystem() {
observers = new ArrayList<>();
}
public static EventSystem getInstance() {
if (instance == null) {
instance = new EventSystem();
}
return instance;
}
public void addObserver(Observer observer) {
observers.add(observer);
}
public void removeObserver(Observer observer) {
observers.remove(observer);
}
| public void notify(GameObject gameObject, Event event) { | 1 | 2023-11-04 13:19:21+00:00 | 2k |
RezaGooner/University-food-ordering | Frames/Admin/ProfileManagment/LogHistory.java | [
{
"identifier": "icon",
"path": "Classes/Pathes/FilesPath.java",
"snippet": "public static ImageIcon icon = new ImageIcon(\"Source/icon.png\");\r"
},
{
"identifier": "errorSound",
"path": "Classes/Theme/SoundEffect.java",
"snippet": "public static void errorSound() throws IOException, Un... | import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import static Classes.Pathes.FilesPath.icon;
import static Classes.Theme.SoundEffect.errorSound;
import static Classes.Pathes.FilesPath.LogPath;
import javax.sound.sampled.LineUnavailableException;
| 1,493 | package Frames.Admin.ProfileManagment;
/*
این کد یک پنجره جدول برای نمایش تاریخچه ورود کاربران به سیستم ایجاد میکند.
در این پنجره، دادههای مربوط به فایل log.txt خوانده شده و در جدول نمایش داده میشوند.
همچنین، امکان جستجو در دادههای جدول با استفاده از یک JTextField نیز فراهم شده است.
در متد سازنده، یک DefaultTableModel ایجاد و ستونهای مربوط به شناسه، زمان و وضعیت ورود به آن اضافه میشوند.
سپس، با استفاده از FileInputStream و BufferedReader، دادههای مربوط به فایل log.txt خوانده شده
و به صورت ردیف به جدول اضافه میشوند.
در پایان، جستجو به پنجره اضافه شده و با استفاده از TableRowSorter، توانایی مرتبسازی ردیفها به صورت صعودی و نزولی فراهم شده است.
سپس، جدول به پنجره اضافه شده و پنجره نمایش داده میشود.
`````````````````````````````````````````````````````
This code is a Java class named `LogHistory` that extends the `JFrame` class. It represents a GUI application for displaying and searching log history.
Here is a breakdown of the code:
1. The code imports various classes from different packages, including `javax.sound.sampled` for handling audio-related exceptions, `javax.swing` for GUI components, `javax.swing.table` for table-related components, `java.awt.event` for event-related classes, and `java.io` for file-related operations.
2. The `LogHistory` class is defined, which extends the `JFrame` class.
3. The constructor of the `LogHistory` class is defined. It sets up the main frame by setting the title.
4. A `DefaultTableModel` named `tableModel` is created to hold the data for the table. Columns with the headers "شناسه" (ID), "زمان" (Time), and "وضعیت ورود" (Login Status) are added to the table model.
5. The log data is read from a file specified by the `LogPath` and added to the table model. Each line of the file represents a row in the table.
6. A `JTable` named `table` is created using the table model.
7. A search panel (`JPanel`) is created to hold the search field. The search field (`JTextField`) allows users to search for specific entries in the table. When the Enter key is pressed in the search field, an action listener is triggered to filter the table rows based on the entered text.
8. The search panel is added to the north (top) of the frame.
9. A `TableRowSorter` named `sorter` is created using the table model. It allows sorting and filtering of the table rows.
10. The sorter is set on the table using the `setRowSorter()` method.
11. The table is wrapped inside a scroll pane (`JScrollPane`) and added to the frame.
12. A menu bar (`JMenuBar`) is created and added to the frame.
13. A menu (`JMenu`) named "بیشتر" (More) is created and added to the menu bar.
14. A menu item (`JMenuItem`) named "تازه سازی" (Refresh) is created. It adds an action listener to refresh the log history by disposing the current frame and creating a new instance of `LogHistory`.
15. The menu item is added to the menu.
16. The icon image is set for the frame using the `setIconImage()` method.
17. The default close operation is set to dispose the frame when it is closed.
18. The frame is positioned at the center of the screen using the `setLocationRelativeTo()` method.
19. The frame is packed to adjust its size based on the components.
20. The frame is set to be visible.
Overall, this code provides a GUI application for displaying log history in a table format. It allows users to search for specific entries and refresh the log history.
*/
public class LogHistory extends JFrame {
private JTable table;
private TableRowSorter<DefaultTableModel> sorter;
public LogHistory() throws UnsupportedAudioFileException, LineUnavailableException, IOException {
super("سابقه ورود");
DefaultTableModel tableModel = new DefaultTableModel();
tableModel.addColumn("شناسه");
tableModel.addColumn("زمان");
tableModel.addColumn("وضعیت ورود");
try (BufferedReader br = new BufferedReader(new FileReader(new File(LogPath)))) {
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split(" , ");
tableModel.addRow(parts);
}
} catch (Exception e) {
| package Frames.Admin.ProfileManagment;
/*
این کد یک پنجره جدول برای نمایش تاریخچه ورود کاربران به سیستم ایجاد میکند.
در این پنجره، دادههای مربوط به فایل log.txt خوانده شده و در جدول نمایش داده میشوند.
همچنین، امکان جستجو در دادههای جدول با استفاده از یک JTextField نیز فراهم شده است.
در متد سازنده، یک DefaultTableModel ایجاد و ستونهای مربوط به شناسه، زمان و وضعیت ورود به آن اضافه میشوند.
سپس، با استفاده از FileInputStream و BufferedReader، دادههای مربوط به فایل log.txt خوانده شده
و به صورت ردیف به جدول اضافه میشوند.
در پایان، جستجو به پنجره اضافه شده و با استفاده از TableRowSorter، توانایی مرتبسازی ردیفها به صورت صعودی و نزولی فراهم شده است.
سپس، جدول به پنجره اضافه شده و پنجره نمایش داده میشود.
`````````````````````````````````````````````````````
This code is a Java class named `LogHistory` that extends the `JFrame` class. It represents a GUI application for displaying and searching log history.
Here is a breakdown of the code:
1. The code imports various classes from different packages, including `javax.sound.sampled` for handling audio-related exceptions, `javax.swing` for GUI components, `javax.swing.table` for table-related components, `java.awt.event` for event-related classes, and `java.io` for file-related operations.
2. The `LogHistory` class is defined, which extends the `JFrame` class.
3. The constructor of the `LogHistory` class is defined. It sets up the main frame by setting the title.
4. A `DefaultTableModel` named `tableModel` is created to hold the data for the table. Columns with the headers "شناسه" (ID), "زمان" (Time), and "وضعیت ورود" (Login Status) are added to the table model.
5. The log data is read from a file specified by the `LogPath` and added to the table model. Each line of the file represents a row in the table.
6. A `JTable` named `table` is created using the table model.
7. A search panel (`JPanel`) is created to hold the search field. The search field (`JTextField`) allows users to search for specific entries in the table. When the Enter key is pressed in the search field, an action listener is triggered to filter the table rows based on the entered text.
8. The search panel is added to the north (top) of the frame.
9. A `TableRowSorter` named `sorter` is created using the table model. It allows sorting and filtering of the table rows.
10. The sorter is set on the table using the `setRowSorter()` method.
11. The table is wrapped inside a scroll pane (`JScrollPane`) and added to the frame.
12. A menu bar (`JMenuBar`) is created and added to the frame.
13. A menu (`JMenu`) named "بیشتر" (More) is created and added to the menu bar.
14. A menu item (`JMenuItem`) named "تازه سازی" (Refresh) is created. It adds an action listener to refresh the log history by disposing the current frame and creating a new instance of `LogHistory`.
15. The menu item is added to the menu.
16. The icon image is set for the frame using the `setIconImage()` method.
17. The default close operation is set to dispose the frame when it is closed.
18. The frame is positioned at the center of the screen using the `setLocationRelativeTo()` method.
19. The frame is packed to adjust its size based on the components.
20. The frame is set to be visible.
Overall, this code provides a GUI application for displaying log history in a table format. It allows users to search for specific entries and refresh the log history.
*/
public class LogHistory extends JFrame {
private JTable table;
private TableRowSorter<DefaultTableModel> sorter;
public LogHistory() throws UnsupportedAudioFileException, LineUnavailableException, IOException {
super("سابقه ورود");
DefaultTableModel tableModel = new DefaultTableModel();
tableModel.addColumn("شناسه");
tableModel.addColumn("زمان");
tableModel.addColumn("وضعیت ورود");
try (BufferedReader br = new BufferedReader(new FileReader(new File(LogPath)))) {
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split(" , ");
tableModel.addRow(parts);
}
} catch (Exception e) {
| errorSound();
| 1 | 2023-11-03 08:35:22+00:00 | 2k |
Celant/PlaytimeSchedule | src/main/java/uk/co/celant/playtimeschedule/Events.java | [
{
"identifier": "IPlaytimeCapability",
"path": "src/main/java/uk/co/celant/playtimeschedule/capabilities/IPlaytimeCapability.java",
"snippet": "public interface IPlaytimeCapability extends INBTSerializable<CompoundTag> {\r\n int getPlaytime();\r\n int getPlaytimeLeft();\r\n String getPlaytimeLe... | import net.minecraft.ChatFormatting;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.common.capabilities.RegisterCapabilitiesEvent;
import net.minecraftforge.event.AttachCapabilitiesEvent;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.server.permission.PermissionAPI;
import uk.co.celant.playtimeschedule.capabilities.IPlaytimeCapability;
import uk.co.celant.playtimeschedule.capabilities.PlaytimeCapability;
import uk.co.celant.playtimeschedule.capabilities.PlaytimeCapabilityProvider;
import java.text.DecimalFormat;
import java.time.Duration;
import java.util.Calendar;
import java.util.List;
| 1,495 | package uk.co.celant.playtimeschedule;
@Mod.EventBusSubscriber(modid = PlaytimeSchedule.MODID, bus = Mod.EventBusSubscriber.Bus.FORGE)
public class Events {
private int tick;
@SubscribeEvent
public void registerCapabilities(RegisterCapabilitiesEvent event) {
event.register(IPlaytimeCapability.class);
}
@SubscribeEvent
public void attachCapability(AttachCapabilitiesEvent<Entity> event) {
if (!(event.getObject() instanceof Player)) return;
event.addCapability(PlaytimeCapabilityProvider.IDENTIFIER, new PlaytimeCapabilityProvider());
}
@SubscribeEvent
public void onPlayerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) {
Player player = event.getEntity();
| package uk.co.celant.playtimeschedule;
@Mod.EventBusSubscriber(modid = PlaytimeSchedule.MODID, bus = Mod.EventBusSubscriber.Bus.FORGE)
public class Events {
private int tick;
@SubscribeEvent
public void registerCapabilities(RegisterCapabilitiesEvent event) {
event.register(IPlaytimeCapability.class);
}
@SubscribeEvent
public void attachCapability(AttachCapabilitiesEvent<Entity> event) {
if (!(event.getObject() instanceof Player)) return;
event.addCapability(PlaytimeCapabilityProvider.IDENTIFIER, new PlaytimeCapabilityProvider());
}
@SubscribeEvent
public void onPlayerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) {
Player player = event.getEntity();
| IPlaytimeCapability playtime = player.getCapability(PlaytimeSchedule.PLAYTIME).orElse(new PlaytimeCapability());
| 1 | 2023-11-02 12:52:02+00:00 | 2k |
EaindrayFromEarth/Collaborative_Blog_Version_Control_Management-System | java/com/we_write/config/SecurityConfig.java | [
{
"identifier": "UserRepository",
"path": "java/com/we_write/repository/UserRepository.java",
"snippet": "@Repository\r\npublic interface UserRepository extends JpaRepository<User, Long> {\r\n\r\n Optional<User> findByEmail(String email);\r\n\r\n Optional<User> findByUsernameOrEmail(String usernam... | import io.swagger.v3.oas.annotations.security.SecurityScheme;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.we_write.repository.UserRepository;
import com.we_write.security.JwtAuthenticationEntryPoint;
import com.we_write.security.JwtAuthenticationFilter;
import com.we_write.security.JwtTokenProvider;
import com.we_write.service.CustomUserDetailsService;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
| 1,598 | package com.we_write.config;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@SecurityScheme(
name = "Bear Authentication",
type = SecuritySchemeType.HTTP,
bearerFormat = "JWT",
scheme = "bearer"
)
public class SecurityConfig {
private JwtAuthenticationEntryPoint authenticationEntryPoint;
private JwtAuthenticationFilter authenticationFilter;
@Bean
public UserDetailsService userDetailsService(UserRepository userRepository) {
return new CustomUserDetailsService(userRepository);
}
@Bean
| package com.we_write.config;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@SecurityScheme(
name = "Bear Authentication",
type = SecuritySchemeType.HTTP,
bearerFormat = "JWT",
scheme = "bearer"
)
public class SecurityConfig {
private JwtAuthenticationEntryPoint authenticationEntryPoint;
private JwtAuthenticationFilter authenticationFilter;
@Bean
public UserDetailsService userDetailsService(UserRepository userRepository) {
return new CustomUserDetailsService(userRepository);
}
@Bean
| public JwtAuthenticationFilter customJwtAuthenticationFilter(JwtTokenProvider jwtTokenProvider, AuthenticationManager authenticationManager, UserDetailsService userDetailsService) {
| 3 | 2023-11-05 05:44:23+00:00 | 2k |
agomezlucena/merger | src/main/java/io/github/agomezlucena/mergers/Merger.java | [
{
"identifier": "ErrorMessageKeys",
"path": "src/main/java/io/github/agomezlucena/errors/ErrorMessageKeys.java",
"snippet": "public enum ErrorMessageKeys {\n /**\n * Represents the key used when the given collection is null\n */\n COLLECTION_IS_NULL(\"collections.isnull\"),\n /**\n ... | import io.github.agomezlucena.errors.ErrorMessageKeys;
import io.github.agomezlucena.errors.ErrorPayload;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import static io.github.agomezlucena.errors.ThrowingFunctions.throwIfNull; | 1,275 | package io.github.agomezlucena.mergers;
/**
* This class allow you to merge two collections based in a hash function to define the identity
* and a merger function to execute the merge logic.
* By default, if you don't define any hash function will Object.hashCode
*
* @param <T> the type of the resulting collection.
* @param <FC> the type of the first collection.
* @param <SC> the type of the second collection.
* @author Alejandro Gómez Lucena.
*/
public abstract class Merger<T, FC, SC> {
protected final Collection<FC> firstCollection;
protected Collection<SC> secondCollection;
protected Function<T, Integer> hashFunction = Object::hashCode;
protected BiFunction<T, T, T> mergerFunction;
/**
* Allows you to create a Merger object with a not null collection of objects of type FC
* @param firstCollection not null collection
* @throws IllegalArgumentException if firstCollection is null
*/
protected Merger(Collection<FC> firstCollection) { | package io.github.agomezlucena.mergers;
/**
* This class allow you to merge two collections based in a hash function to define the identity
* and a merger function to execute the merge logic.
* By default, if you don't define any hash function will Object.hashCode
*
* @param <T> the type of the resulting collection.
* @param <FC> the type of the first collection.
* @param <SC> the type of the second collection.
* @author Alejandro Gómez Lucena.
*/
public abstract class Merger<T, FC, SC> {
protected final Collection<FC> firstCollection;
protected Collection<SC> secondCollection;
protected Function<T, Integer> hashFunction = Object::hashCode;
protected BiFunction<T, T, T> mergerFunction;
/**
* Allows you to create a Merger object with a not null collection of objects of type FC
* @param firstCollection not null collection
* @throws IllegalArgumentException if firstCollection is null
*/
protected Merger(Collection<FC> firstCollection) { | throwIfNull(firstCollection, ErrorPayload.of(ErrorMessageKeys.COLLECTION_IS_NULL, IllegalArgumentException.class)); | 0 | 2023-11-05 15:29:30+00:00 | 2k |
af19git5/EasyImage | src/main/java/io/github/af19git5/entity/Text.java | [
{
"identifier": "PositionX",
"path": "src/main/java/io/github/af19git5/type/PositionX.java",
"snippet": "@Getter\npublic enum PositionX {\n\n /** 無指定位置 */\n NONE,\n\n /** 置左 */\n LEFT,\n\n /** 置中 */\n MIDDLE,\n\n /** 置右 */\n RIGHT\n}"
},
{
"identifier": "PositionY",
"... | import io.github.af19git5.type.PositionX;
import io.github.af19git5.type.PositionY;
import lombok.Getter;
import lombok.NonNull;
import java.awt.*; | 813 | package io.github.af19git5.entity;
/**
* 插入文字物件
*
* @author Jimmy Kang
*/
@Getter
public class Text extends Item {
private final String text;
private final Color color;
private final Font font;
/**
* @param x 放置x軸位置
* @param y 放置y軸位置
* @param text 文字內容
* @param color 文字顏色
*/
public Text(int x, int y, @NonNull String text, @NonNull Color color) {
this.setX(x);
this.setY(y);
this.text = text;
this.color = color;
this.font = null;
}
/**
* @param x 放置x軸位置
* @param y 放置y軸位置
* @param text 文字內容
* @param colorHex 文字顏色(16進位色碼)
*/
public Text(int x, int y, @NonNull String text, @NonNull String colorHex) {
this.setX(x);
this.setY(y);
this.text = text;
this.color = Color.decode(colorHex);
this.font = null;
}
/**
* @param x 放置x軸位置
* @param y 放置y軸位置
* @param text 文字內容
* @param color 文字顏色
* @param font 文字字體
*/
public Text(int x, int y, @NonNull String text, @NonNull Color color, Font font) {
this.setX(x);
this.setY(y);
this.text = text;
this.color = color;
this.font = font;
}
/**
* @param x 放置x軸位置
* @param y 放置y軸位置
* @param text 文字內容
* @param colorHex 文字顏色(16進位色碼)
* @param font 文字字體
*/
public Text(int x, int y, @NonNull String text, @NonNull String colorHex, Font font) {
this.setX(x);
this.setY(y);
this.text = text;
this.color = Color.decode(colorHex);
this.font = font;
}
/**
* @param positionX 放置x軸位置
* @param y 放置y軸位置
* @param text 文字內容
* @param color 文字顏色
*/ | package io.github.af19git5.entity;
/**
* 插入文字物件
*
* @author Jimmy Kang
*/
@Getter
public class Text extends Item {
private final String text;
private final Color color;
private final Font font;
/**
* @param x 放置x軸位置
* @param y 放置y軸位置
* @param text 文字內容
* @param color 文字顏色
*/
public Text(int x, int y, @NonNull String text, @NonNull Color color) {
this.setX(x);
this.setY(y);
this.text = text;
this.color = color;
this.font = null;
}
/**
* @param x 放置x軸位置
* @param y 放置y軸位置
* @param text 文字內容
* @param colorHex 文字顏色(16進位色碼)
*/
public Text(int x, int y, @NonNull String text, @NonNull String colorHex) {
this.setX(x);
this.setY(y);
this.text = text;
this.color = Color.decode(colorHex);
this.font = null;
}
/**
* @param x 放置x軸位置
* @param y 放置y軸位置
* @param text 文字內容
* @param color 文字顏色
* @param font 文字字體
*/
public Text(int x, int y, @NonNull String text, @NonNull Color color, Font font) {
this.setX(x);
this.setY(y);
this.text = text;
this.color = color;
this.font = font;
}
/**
* @param x 放置x軸位置
* @param y 放置y軸位置
* @param text 文字內容
* @param colorHex 文字顏色(16進位色碼)
* @param font 文字字體
*/
public Text(int x, int y, @NonNull String text, @NonNull String colorHex, Font font) {
this.setX(x);
this.setY(y);
this.text = text;
this.color = Color.decode(colorHex);
this.font = font;
}
/**
* @param positionX 放置x軸位置
* @param y 放置y軸位置
* @param text 文字內容
* @param color 文字顏色
*/ | public Text(@NonNull PositionX positionX, int y, @NonNull String text, @NonNull Color color) { | 0 | 2023-11-01 03:55:06+00:00 | 2k |
schadfield/shogi-explorer | src/main/java/com/chadfield/shogiexplorer/utils/ImageUtils.java | [
{
"identifier": "Coordinate",
"path": "src/main/java/com/chadfield/shogiexplorer/objects/Coordinate.java",
"snippet": "public class Coordinate {\n\n private Integer x;\n private Integer y;\n\n public Coordinate() {\n\n }\n\n public Coordinate(Integer x, Integer y) {\n this.x = x;\n... | import java.awt.Image;
import java.awt.image.BaseMultiResolutionImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import com.chadfield.shogiexplorer.objects.Coordinate;
import com.chadfield.shogiexplorer.objects.Dimension;
import com.chadfield.shogiexplorer.objects.ImageCache;
import java.awt.Color;
import java.awt.Font;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import org.apache.batik.transcoder.SVGAbstractTranscoder;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder; | 1,166 | /*
Copyright © 2021, 2022 Stephen R Chadfield.
This file is part of Shogi Explorer.
Shogi Explorer is free software: you can redistribute it and/or modify it under the terms of the
GNU General Public License as published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Shogi Explorer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with Shogi Explorer.
If not, see <https://www.gnu.org/licenses/>.
*/
package com.chadfield.shogiexplorer.utils;
public class ImageUtils {
private static final String OS = System.getProperty("os.name").toLowerCase();
public static final boolean IS_WINDOWS = (OS.contains("win"));
public static final boolean IS_MAC = (OS.contains("mac"));
public static final boolean IS_LINUX = (OS.contains("nux"));
private ImageUtils() {
throw new IllegalStateException("Utility class");
}
| /*
Copyright © 2021, 2022 Stephen R Chadfield.
This file is part of Shogi Explorer.
Shogi Explorer is free software: you can redistribute it and/or modify it under the terms of the
GNU General Public License as published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Shogi Explorer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with Shogi Explorer.
If not, see <https://www.gnu.org/licenses/>.
*/
package com.chadfield.shogiexplorer.utils;
public class ImageUtils {
private static final String OS = System.getProperty("os.name").toLowerCase();
public static final boolean IS_WINDOWS = (OS.contains("win"));
public static final boolean IS_MAC = (OS.contains("mac"));
public static final boolean IS_LINUX = (OS.contains("nux"));
private ImageUtils() {
throw new IllegalStateException("Utility class");
}
| public static JLabel getPieceLabelForKoma(Image image, Coordinate boardCoord, Dimension offset, Coordinate imageLocation) { | 1 | 2023-11-08 09:24:57+00:00 | 2k |
F3F5/SpawnAuth | src/main/java/f3f5/SpawnAuth/events/OnPlayerLoginEvent.java | [
{
"identifier": "GameHelper",
"path": "src/main/java/f3f5/SpawnAuth/helpers/GameHelper.java",
"snippet": "public class GameHelper {\r\n public AuthMeApi authMeApi;\r\n public SaveHelper saveHelper;\r\n\r\n public GameHelper(AuthMeApi authMeApi) {\r\n this.authMeApi = authMeApi;\r\n }\... | import f3f5.SpawnAuth.helpers.GameHelper;
import f3f5.SpawnAuth.helpers.SaveHelper;
import fr.xephi.authme.events.LoginEvent;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
| 1,089 | package f3f5.SpawnAuth.events;
public class OnPlayerLoginEvent implements Listener {
private final SaveHelper saveHelper;
| package f3f5.SpawnAuth.events;
public class OnPlayerLoginEvent implements Listener {
private final SaveHelper saveHelper;
| private final GameHelper gameHelper;
| 0 | 2023-11-04 14:43:05+00:00 | 2k |
Akshayp02/Enlight21 | app/src/main/java/com/example/enlight21/signupActivity.java | [
{
"identifier": "USER_NODE",
"path": "app/src/main/java/com/example/enlight21/Utils/Constant.java",
"snippet": "public static final String USER_NODE = \"users\";"
},
{
"identifier": "User",
"path": "app/src/main/java/com/example/enlight21/Models/User.java",
"snippet": "public class User ... | import static android.content.ContentValues.TAG;
import static com.example.enlight21.Utils.Constant.USER_NODE;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.example.enlight21.Models.User;
import com.example.enlight21.databinding.ActivitySignupBinding;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.FirebaseFirestore; | 1,019 | package com.example.enlight21;
// ... (other import statements)
public class signupActivity extends AppCompatActivity {
private ActivitySignupBinding binding;
private FirebaseAuth mAuth;
FirebaseFirestore db = FirebaseFirestore.getInstance();
@Override
protected void onStart() {
super.onStart();
// Check if the user is signed in
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser != null) {
// User is already signed in, navigate to the main activity
Intent intent = new Intent(signupActivity.this, MainActivity.class);
startActivity(intent);
finish(); // Close the current activity to prevent the user from going back
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivitySignupBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
binding.signupBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = binding.Email.getText().toString();
String password = validatePassword(binding.Password.getText().toString(), binding.ConfirmPassword.getText().toString());
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password) || TextUtils.isEmpty(binding.ConfirmPassword.getText()) || TextUtils.isEmpty(binding.Username.getText())) {
Toast.makeText(signupActivity.this, "Please fill the Information", Toast.LENGTH_SHORT).show();
} else {
if (password != null) {
Task<AuthResult> authResultTask = mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(signupActivity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
User user = new User( binding.Username.getText().toString(), password,email,null,null);
// to strore data in firebase | package com.example.enlight21;
// ... (other import statements)
public class signupActivity extends AppCompatActivity {
private ActivitySignupBinding binding;
private FirebaseAuth mAuth;
FirebaseFirestore db = FirebaseFirestore.getInstance();
@Override
protected void onStart() {
super.onStart();
// Check if the user is signed in
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser != null) {
// User is already signed in, navigate to the main activity
Intent intent = new Intent(signupActivity.this, MainActivity.class);
startActivity(intent);
finish(); // Close the current activity to prevent the user from going back
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivitySignupBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
binding.signupBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = binding.Email.getText().toString();
String password = validatePassword(binding.Password.getText().toString(), binding.ConfirmPassword.getText().toString());
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password) || TextUtils.isEmpty(binding.ConfirmPassword.getText()) || TextUtils.isEmpty(binding.Username.getText())) {
Toast.makeText(signupActivity.this, "Please fill the Information", Toast.LENGTH_SHORT).show();
} else {
if (password != null) {
Task<AuthResult> authResultTask = mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(signupActivity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
User user = new User( binding.Username.getText().toString(), password,email,null,null);
// to strore data in firebase | db.collection(USER_NODE).document(mAuth.getCurrentUser().getUid()).set(user) | 0 | 2023-11-04 08:22:36+00:00 | 2k |
refrainsclub/npcs | src/main/java/nz/blair/npcs/listeners/PacketInboundListener.java | [
{
"identifier": "ClickAction",
"path": "src/main/java/nz/blair/npcs/npcs/ClickAction.java",
"snippet": "public interface ClickAction {\n void onClick(Player player, ClickType clickType);\n}"
},
{
"identifier": "ClickType",
"path": "src/main/java/nz/blair/npcs/npcs/ClickType.java",
"sn... | import net.minecraft.server.v1_8_R3.Packet;
import net.minecraft.server.v1_8_R3.PacketPlayInUseEntity;
import nz.blair.npcs.npcs.ClickAction;
import nz.blair.npcs.npcs.ClickType;
import nz.blair.npcs.npcs.NpcManager;
import nz.blair.npcs.utils.NmsUtil;
import org.bukkit.entity.Player; | 1,196 | package nz.blair.npcs.listeners;
public class PacketInboundListener {
private final NpcManager npcManager;
public PacketInboundListener(NpcManager npcManager) {
this.npcManager = npcManager;
}
@SuppressWarnings("SameReturnValue") // Keep the cancel return value for future use
public boolean onPacketInbound(Player player, Packet<?> packet) {
if (!(packet instanceof PacketPlayInUseEntity)) {
return false;
}
PacketPlayInUseEntity useEntityPacket = (PacketPlayInUseEntity) packet;
PacketPlayInUseEntity.EnumEntityUseAction action = useEntityPacket.a();
Object entityIdObj = NmsUtil.getField(useEntityPacket, "a");
if (!(entityIdObj instanceof Integer)) {
return false;
}
int entityId = (int) entityIdObj;
npcManager.getNpcs().forEach(npc -> {
if (npc.getEntityId() == entityId) {
ClickAction clickAction = npc.getClickAction();
if (clickAction == null) {
return;
}
| package nz.blair.npcs.listeners;
public class PacketInboundListener {
private final NpcManager npcManager;
public PacketInboundListener(NpcManager npcManager) {
this.npcManager = npcManager;
}
@SuppressWarnings("SameReturnValue") // Keep the cancel return value for future use
public boolean onPacketInbound(Player player, Packet<?> packet) {
if (!(packet instanceof PacketPlayInUseEntity)) {
return false;
}
PacketPlayInUseEntity useEntityPacket = (PacketPlayInUseEntity) packet;
PacketPlayInUseEntity.EnumEntityUseAction action = useEntityPacket.a();
Object entityIdObj = NmsUtil.getField(useEntityPacket, "a");
if (!(entityIdObj instanceof Integer)) {
return false;
}
int entityId = (int) entityIdObj;
npcManager.getNpcs().forEach(npc -> {
if (npc.getEntityId() == entityId) {
ClickAction clickAction = npc.getClickAction();
if (clickAction == null) {
return;
}
| ClickType clickType = ClickType.fromNms(action); | 1 | 2023-11-01 01:14:41+00:00 | 2k |
cyljx9999/talktime-Java | talktime-framework/talktime-service/src/main/java/com/qingmeng/service/impl/SysUserAuthServiceImpl.java | [
{
"identifier": "SysUserAuthDao",
"path": "talktime-framework/talktime-dao/src/main/java/com/qingmeng/dao/SysUserAuthDao.java",
"snippet": "@Service\npublic class SysUserAuthDao extends ServiceImpl<SysUserAuthMapper, SysUserAuth>{\n\n /**\n * 通过openId查询授权信息\n *\n * @param openId 第三方应用唯一凭证... | import com.qingmeng.dao.SysUserAuthDao;
import com.qingmeng.entity.SysUserAuth;
import com.qingmeng.service.SysUserAuthService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource; | 787 | package com.qingmeng.service.impl;
/**
* @author 清梦
* @version 1.0.0
* @Description
* @createTime 2023年11月10日 11:19:00
*/
@Service
public class SysUserAuthServiceImpl implements SysUserAuthService {
@Resource
private SysUserAuthDao sysUserAuthDao;
/**
* 使用 Open ID 获取授权信息
*
* @param openId 开放 ID
* @return {@link SysUserAuth }
* @author qingmeng
* @createTime: 2023/11/20 08:36:15
*/
@Override | package com.qingmeng.service.impl;
/**
* @author 清梦
* @version 1.0.0
* @Description
* @createTime 2023年11月10日 11:19:00
*/
@Service
public class SysUserAuthServiceImpl implements SysUserAuthService {
@Resource
private SysUserAuthDao sysUserAuthDao;
/**
* 使用 Open ID 获取授权信息
*
* @param openId 开放 ID
* @return {@link SysUserAuth }
* @author qingmeng
* @createTime: 2023/11/20 08:36:15
*/
@Override | public SysUserAuth getAuthInfoWithOpenId(String openId) { | 1 | 2023-11-07 16:04:55+00:00 | 2k |
TianqiCS/AIChatLib-Fabric | src/main/java/com/citrusmc/aichatlib/client/TextParser.java | [
{
"identifier": "ClientConfig",
"path": "src/main/java/com/citrusmc/aichatlib/configs/ClientConfig.java",
"snippet": "public class ClientConfig extends Config{\n static ClientConfig instance = null;\n\n private ClientConfig() {\n String configFileLocation = \"config/AIChatLib/ClientConfig.y... | import com.citrusmc.aichatlib.configs.ClientConfig;
import com.citrusmc.aichatlib.configs.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | 1,028 | package com.citrusmc.aichatlib.client;
/**
* TextParser class
* <p>
* This class is used to parse the chat message and game message.
* <p>
*/
public class TextParser {
private static final Logger LOGGER = LoggerFactory.getLogger("ChatBot-TextParser"); | package com.citrusmc.aichatlib.client;
/**
* TextParser class
* <p>
* This class is used to parse the chat message and game message.
* <p>
*/
public class TextParser {
private static final Logger LOGGER = LoggerFactory.getLogger("ChatBot-TextParser"); | private static final Config CONFIG = ClientConfig.getInstance(); | 0 | 2023-11-06 00:04:54+00:00 | 2k |
Griefed/AddEmAll | fabric/src/main/java/de/griefed/addemall/FabricRegistrationFactory.java | [
{
"identifier": "RegistrationProvider",
"path": "common/src/main/java/de/griefed/addemall/registry/RegistrationProvider.java",
"snippet": "public interface RegistrationProvider<T> {\n\n /**\n * Gets a provider for specified {@code modId} and {@code resourceKey}. <br>\n * It is <i>recommended<... | import de.griefed.addemall.registry.RegistrationProvider;
import de.griefed.addemall.registry.RegistryObject;
import net.minecraft.core.Holder;
import net.minecraft.core.Registry;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Supplier; | 1,384 | package de.griefed.addemall;
public class FabricRegistrationFactory implements RegistrationProvider.Factory {
@Override
public <T> RegistrationProvider<T> create(ResourceKey<? extends Registry<T>> resourceKey, String modId) {
return new Provider<>(modId, resourceKey);
}
@Override
public <T> RegistrationProvider<T> create(Registry<T> registry, String modId) {
return new Provider<>(modId, registry);
}
private static class Provider<T> implements RegistrationProvider<T> {
private final String modId;
private final Registry<T> registry;
| package de.griefed.addemall;
public class FabricRegistrationFactory implements RegistrationProvider.Factory {
@Override
public <T> RegistrationProvider<T> create(ResourceKey<? extends Registry<T>> resourceKey, String modId) {
return new Provider<>(modId, resourceKey);
}
@Override
public <T> RegistrationProvider<T> create(Registry<T> registry, String modId) {
return new Provider<>(modId, registry);
}
private static class Provider<T> implements RegistrationProvider<T> {
private final String modId;
private final Registry<T> registry;
| private final Set<RegistryObject<T>> entries = new HashSet<>(); | 1 | 2023-11-06 12:50:10+00:00 | 2k |
wicksonZhang/data-structure | 10-Map/src/test/java/com/wickson/set/ComparisonTest.java | [
{
"identifier": "FileInfo",
"path": "9-Set/src/main/java/com/wickson/file/FileInfo.java",
"snippet": "public class FileInfo {\n\tprivate int lines;\n\tprivate int files;\n\tprivate String content = \"\";\n\t\n\tpublic String[] words() {\n\t\treturn content.split(\"[^a-zA-Z]+\");\n\t}\n\t\n\tpublic int g... | import com.wickson.file.FileInfo;
import com.wickson.file.Files;
import com.wickson.utils.Times;
import org.junit.jupiter.api.Test; | 1,134 | package com.wickson.set;
/**
* 性能对比:红黑树和链表
*/
public class ComparisonTest {
@Test
public void ListSetTest() {
Times.test("ListSet", () -> common(new ListSet<>(), file()));
}
@Test
public void treeSetTest() {
Times.test("TreeSet", () -> common(new TreeSet<>(), file()));
}
public String[] file() { | package com.wickson.set;
/**
* 性能对比:红黑树和链表
*/
public class ComparisonTest {
@Test
public void ListSetTest() {
Times.test("ListSet", () -> common(new ListSet<>(), file()));
}
@Test
public void treeSetTest() {
Times.test("TreeSet", () -> common(new TreeSet<>(), file()));
}
public String[] file() { | FileInfo fileInfo = Files.read("C:\\Users\\wicks\\Desktop\\java-source\\java\\util", | 0 | 2023-11-06 16:33:25+00:00 | 2k |
Royal-Code-Master/File-Generation-Spring-Reactive | SendMoney/src/main/java/com/money/app/controller/UserController.java | [
{
"identifier": "User",
"path": "SendMoney/src/main/java/com/money/app/pojo/User.java",
"snippet": "@Document(collection = \"userdetails\")\r\npublic class User {\r\n\r\n\t@Id\r\n\tprivate long uid;\r\n\r\n\t@Indexed(unique = true)\r\n\tprivate String accountNumber;\r\n\r\n\tprivate float amount;\r\n\r\... | 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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.money.app.pojo.User;
import com.money.app.service.UserService;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
| 1,232 | package com.money.app.controller;
@RestController
@RequestMapping("/bank")
public class UserController {
@Autowired
private UserService userService;
// account creation end point
@PostMapping("/newAccount")
| package com.money.app.controller;
@RestController
@RequestMapping("/bank")
public class UserController {
@Autowired
private UserService userService;
// account creation end point
@PostMapping("/newAccount")
| public Mono<User> newAccountEndPoint(@RequestBody User user) {
| 0 | 2023-11-09 12:42:24+00:00 | 2k |
arunk140/ollm.chat | app/src/main/java/com/arunk140/ollmchat/SettingsActivity.java | [
{
"identifier": "Settings",
"path": "app/src/main/java/com/arunk140/ollmchat/Config/Settings.java",
"snippet": "public class Settings {\n public int maxTokens = -1;\n public String apiUrl = \"https://api.openai.com/\";\n public String apiKey = \"\";\n public float temperature = 0.7F;\n pu... | import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import com.arunk140.ollmchat.Config.Settings;
import com.arunk140.ollmchat.DB.Manager; | 1,001 | package com.arunk140.ollmchat;
public class SettingsActivity extends AppCompatActivity {
private EditText apiKeyEditText;
private EditText maxTokensEditText;
private EditText modelEditText;
private EditText apiUrlEditText;
private EditText temperatureEditText;
private EditText systemPromptMultiLine;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
apiKeyEditText = findViewById(R.id.apiKey);
modelEditText = findViewById(R.id.model);
maxTokensEditText = findViewById(R.id.maxTokens);
apiUrlEditText = findViewById(R.id.apiUrl);
temperatureEditText = findViewById(R.id.temperature);
systemPromptMultiLine = findViewById(R.id.systemPrompt);
Manager manager = new Manager(this);
manager.open(); | package com.arunk140.ollmchat;
public class SettingsActivity extends AppCompatActivity {
private EditText apiKeyEditText;
private EditText maxTokensEditText;
private EditText modelEditText;
private EditText apiUrlEditText;
private EditText temperatureEditText;
private EditText systemPromptMultiLine;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
apiKeyEditText = findViewById(R.id.apiKey);
modelEditText = findViewById(R.id.model);
maxTokensEditText = findViewById(R.id.maxTokens);
apiUrlEditText = findViewById(R.id.apiUrl);
temperatureEditText = findViewById(R.id.temperature);
systemPromptMultiLine = findViewById(R.id.systemPrompt);
Manager manager = new Manager(this);
manager.open(); | Settings settings = manager.getSettings(); | 0 | 2023-11-01 00:44:14+00:00 | 2k |
MonstrousSoftware/Tut3D | core/src/main/java/com/monstrous/tut3d/GameObject.java | [
{
"identifier": "Behaviour",
"path": "core/src/main/java/com/monstrous/tut3d/behaviours/Behaviour.java",
"snippet": "public class Behaviour {\n protected final GameObject go;\n\n protected Behaviour(GameObject go) {\n this.go = go;\n }\n\n public void update(World world, float deltaTi... | import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Disposable;
import com.monstrous.tut3d.behaviours.Behaviour;
import com.monstrous.tut3d.physics.PhysicsBody;
import net.mgsx.gltf.scene3d.scene.Scene; | 1,248 | package com.monstrous.tut3d;
public class GameObject implements Disposable {
public final GameObjectType type;
public final Scene scene;
public final PhysicsBody body;
public final Vector3 direction;
public boolean visible;
public float health; | package com.monstrous.tut3d;
public class GameObject implements Disposable {
public final GameObjectType type;
public final Scene scene;
public final PhysicsBody body;
public final Vector3 direction;
public boolean visible;
public float health; | public Behaviour behaviour; | 0 | 2023-11-04 13:15:48+00:00 | 2k |
DioxideCN/movie-repository | src/main/java/cn/dioxide/movierepository/service/RatingDefinitionService.java | [
{
"identifier": "UserHistory",
"path": "src/main/java/cn/dioxide/movierepository/entity/UserHistory.java",
"snippet": "@Data\npublic class UserHistory {\n\n private Integer movieId; // 电影ID 映射自movies\n\n private String title; // 电影标题 映射自movies\n\n private Integer rating; // 电... | import cn.dioxide.movierepository.entity.UserHistory;
import cn.dioxide.movierepository.infra.PageResult;
import cn.dioxide.movierepository.mapper.TagResultMapper;
import cn.dioxide.movierepository.mapper.UserHistoryMapper;
import cn.dioxide.movierepository.service.impl.IRatingDefinitionService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryColumn;
import com.mybatisflex.core.query.QueryTable;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors; | 734 | package cn.dioxide.movierepository.service;
/**
* 采用异步并行流优化
* @author Dioxide.CN
* @date 2023/11/28
* @since 1.0
*/
@Service
public class RatingDefinitionService implements IRatingDefinitionService {
@Resource | package cn.dioxide.movierepository.service;
/**
* 采用异步并行流优化
* @author Dioxide.CN
* @date 2023/11/28
* @since 1.0
*/
@Service
public class RatingDefinitionService implements IRatingDefinitionService {
@Resource | UserHistoryMapper userHistoryMapper; | 3 | 2023-11-09 01:58:58+00:00 | 2k |
Einzieg/EinziegCloud | src/test/java/com/cloud/LogTest.java | [
{
"identifier": "Log",
"path": "src/main/java/com/cloud/entity/Log.java",
"snippet": "@Data\n@Builder\n@TableName(\"cloud_log\")\npublic class Log {\n\n\t/**\n\t * 主键\n\t */\n\t@TableId(value = \"ID\", type = IdType.AUTO)\n\tprivate Long id;\n\n\t/**\n\t * 运行结果\n\t */\n\t@TableField(value = \"OUTCOME\")... | import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cloud.entity.Log;
import com.cloud.service.impl.LogServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; | 1,021 | package com.cloud;
@Slf4j
@SpringBootTest(classes = EinziegCloudApplication.class)
@RunWith(SpringRunner.class)
public class LogTest {
@Resource | package com.cloud;
@Slf4j
@SpringBootTest(classes = EinziegCloudApplication.class)
@RunWith(SpringRunner.class)
public class LogTest {
@Resource | LogServiceImpl logServiceImpl; | 1 | 2023-11-07 07:27:53+00:00 | 2k |
Bergerk1/Big-Data-Analytics | src/main/java/de/ddm/actors/profiling/InputReader.java | [
{
"identifier": "AkkaSerializable",
"path": "src/main/java/de/ddm/serialization/AkkaSerializable.java",
"snippet": "@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)\npublic interface AkkaSerializable extends Serializable {\n}"
},
{
"identifier": "DomainConfigurationSingleton",
... | import akka.actor.typed.ActorRef;
import akka.actor.typed.Behavior;
import akka.actor.typed.PostStop;
import akka.actor.typed.javadsl.AbstractBehavior;
import akka.actor.typed.javadsl.ActorContext;
import akka.actor.typed.javadsl.Behaviors;
import akka.actor.typed.javadsl.Receive;
import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvValidationException;
import de.ddm.serialization.AkkaSerializable;
import de.ddm.singletons.DomainConfigurationSingleton;
import de.ddm.singletons.InputConfigurationSingleton;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List; | 682 | package de.ddm.actors.profiling;
public class InputReader extends AbstractBehavior<InputReader.Message> {
////////////////////
// Actor Messages //
////////////////////
public interface Message extends AkkaSerializable {
}
@Getter
@NoArgsConstructor
@AllArgsConstructor
public static class ReadHeaderMessage implements Message {
private static final long serialVersionUID = 1729062814525657711L;
ActorRef<DependencyMiner.Message> replyTo;
}
@Getter
@NoArgsConstructor
@AllArgsConstructor
public static class ReadBatchMessage implements Message {
private static final long serialVersionUID = -7915854043207237318L;
ActorRef<DependencyMiner.Message> replyTo;
}
////////////////////////
// Actor Construction //
////////////////////////
public static final String DEFAULT_NAME = "inputReader";
public static Behavior<Message> create(final int id, final File inputFile) {
return Behaviors.setup(context -> new InputReader(context, id, inputFile));
}
private InputReader(ActorContext<Message> context, final int id, final File inputFile) throws IOException, CsvValidationException {
super(context);
this.id = id;
this.reader = InputConfigurationSingleton.get().createCSVReader(inputFile);
this.header = InputConfigurationSingleton.get().getHeader(inputFile);
if (InputConfigurationSingleton.get().isFileHasHeader())
this.reader.readNext();
}
/////////////////
// Actor State //
/////////////////
private final int id; | package de.ddm.actors.profiling;
public class InputReader extends AbstractBehavior<InputReader.Message> {
////////////////////
// Actor Messages //
////////////////////
public interface Message extends AkkaSerializable {
}
@Getter
@NoArgsConstructor
@AllArgsConstructor
public static class ReadHeaderMessage implements Message {
private static final long serialVersionUID = 1729062814525657711L;
ActorRef<DependencyMiner.Message> replyTo;
}
@Getter
@NoArgsConstructor
@AllArgsConstructor
public static class ReadBatchMessage implements Message {
private static final long serialVersionUID = -7915854043207237318L;
ActorRef<DependencyMiner.Message> replyTo;
}
////////////////////////
// Actor Construction //
////////////////////////
public static final String DEFAULT_NAME = "inputReader";
public static Behavior<Message> create(final int id, final File inputFile) {
return Behaviors.setup(context -> new InputReader(context, id, inputFile));
}
private InputReader(ActorContext<Message> context, final int id, final File inputFile) throws IOException, CsvValidationException {
super(context);
this.id = id;
this.reader = InputConfigurationSingleton.get().createCSVReader(inputFile);
this.header = InputConfigurationSingleton.get().getHeader(inputFile);
if (InputConfigurationSingleton.get().isFileHasHeader())
this.reader.readNext();
}
/////////////////
// Actor State //
/////////////////
private final int id; | private final int batchSize = DomainConfigurationSingleton.get().getInputReaderBatchSize(); | 1 | 2023-11-01 11:57:53+00:00 | 2k |
20dinosaurs/BassScript | src/main/java/miro/bassscript/functionutils/Function.java | [
{
"identifier": "BSLogger",
"path": "src/main/java/miro/bassscript/BSLogger.java",
"snippet": "public class BSLogger {\n\n private final Logger LOGGER;\n\n public BSLogger() {\n LOGGER = LoggerFactory.getLogger(\"bassscript\");\n }\n\n public void logDebug(String s) {\n LOGGER.... | import miro.bassscript.BSLogger;
import miro.bassscript.BassScript;
import miro.bassscript.ITimeable;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.ClientPlayerEntity;
import net.minecraft.client.world.ClientWorld; | 774 | package miro.bassscript.functionutils;
/**
* All Functions extend this class.
* Provides access to the Function's {@link BassScript} instance.
*/
public abstract class Function implements ITimeable {
/**
* The current instance of BassScript.
*/
protected BassScript bassScript;
/**
* The logger.
*/ | package miro.bassscript.functionutils;
/**
* All Functions extend this class.
* Provides access to the Function's {@link BassScript} instance.
*/
public abstract class Function implements ITimeable {
/**
* The current instance of BassScript.
*/
protected BassScript bassScript;
/**
* The logger.
*/ | protected BSLogger logger; | 0 | 2023-11-08 05:28:18+00:00 | 2k |
hlysine/create_power_loader | src/main/java/com/hlysine/create_power_loader/content/ContraptionRenderer.java | [
{
"identifier": "AndesiteChunkLoaderRenderer",
"path": "src/main/java/com/hlysine/create_power_loader/content/andesitechunkloader/AndesiteChunkLoaderRenderer.java",
"snippet": "public class AndesiteChunkLoaderRenderer extends AbstractChunkLoaderRenderer {\n\n public AndesiteChunkLoaderRenderer(BlockE... | import com.hlysine.create_power_loader.content.andesitechunkloader.AndesiteChunkLoaderRenderer;
import com.hlysine.create_power_loader.content.brasschunkloader.BrassChunkLoaderRenderer;
import com.jozufozu.flywheel.core.virtual.VirtualRenderWorld;
import com.simibubi.create.content.contraptions.behaviour.MovementContext;
import com.simibubi.create.content.contraptions.render.ContraptionMatrices;
import net.minecraft.client.renderer.MultiBufferSource; | 670 | package com.hlysine.create_power_loader.content;
public class ContraptionRenderer {
private static final AndesiteChunkLoaderRenderer ANDESITE_RENDERER = new AndesiteChunkLoaderRenderer(null); | package com.hlysine.create_power_loader.content;
public class ContraptionRenderer {
private static final AndesiteChunkLoaderRenderer ANDESITE_RENDERER = new AndesiteChunkLoaderRenderer(null); | private static final BrassChunkLoaderRenderer BRASS_RENDERER = new BrassChunkLoaderRenderer(null); | 1 | 2023-11-09 04:29:33+00:00 | 2k |
dingodb/dingo-expr | runtime/src/main/java/io/dingodb/expr/runtime/op/mathematical/AbsCheckFun.java | [
{
"identifier": "ExprEvaluatingException",
"path": "runtime/src/main/java/io/dingodb/expr/runtime/exception/ExprEvaluatingException.java",
"snippet": "public class ExprEvaluatingException extends RuntimeException {\n private static final long serialVersionUID = 3903309327153427907L;\n\n /**\n ... | import io.dingodb.expr.annotations.Operators;
import io.dingodb.expr.runtime.exception.ExprEvaluatingException;
import io.dingodb.expr.runtime.op.UnaryNumericOp;
import io.dingodb.expr.runtime.utils.ExceptionUtils;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.math.BigDecimal; | 837 | /*
* Copyright 2021 DataCanvas
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.dingodb.expr.runtime.op.mathematical;
@Operators
abstract class AbsCheckFun extends UnaryNumericOp {
public static final String NAME = "ABS";
private static final long serialVersionUID = 6834907753646404442L;
static int abs(int num) {
if (num == Integer.MIN_VALUE) { | /*
* Copyright 2021 DataCanvas
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.dingodb.expr.runtime.op.mathematical;
@Operators
abstract class AbsCheckFun extends UnaryNumericOp {
public static final String NAME = "ABS";
private static final long serialVersionUID = 6834907753646404442L;
static int abs(int num) {
if (num == Integer.MIN_VALUE) { | throw new ExprEvaluatingException(ExceptionUtils.exceedsIntRange()); | 0 | 2023-11-04 08:43:49+00:00 | 2k |
sesamecare/stripe-mock | src/main/java/com/sesame/oss/stripemock/entities/RefundManager.java | [
{
"identifier": "QueryParameters",
"path": "src/main/java/com/sesame/oss/stripemock/http/QueryParameters.java",
"snippet": "public class QueryParameters {\n private final String wholeQueryParameterString;\n private final Map<String, List<String>> keyValuePairs = new HashMap<>();\n\n public Quer... | import com.sesame.oss.stripemock.http.QueryParameters;
import com.sesame.oss.stripemock.http.ResponseCodeException;
import com.stripe.model.PaymentIntent;
import com.stripe.model.Refund;
import java.time.Clock;
import java.util.List;
import java.util.Map; | 1,401 | package com.sesame.oss.stripemock.entities;
class RefundManager extends AbstractEntityManager<Refund> {
private final StripeEntities stripeEntities;
protected RefundManager(Clock clock, StripeEntities stripeEntities) {
super(clock, Refund.class, "re", 24);
this.stripeEntities = stripeEntities;
}
@Override
protected Refund initialize(Refund refund, Map<String, Object> formData) throws ResponseCodeException {
refund.setStatus("succeeded");
if (refund.getAmount() == null && refund.getPaymentIntent() != null) {
refund.setAmount(stripeEntities.getEntityManager(PaymentIntent.class)
.get(refund.getPaymentIntent())
.orElseThrow(() -> ResponseCodeException.noSuchEntity(400, "payment_intent", refund.getPaymentIntent()))
.getAmount());
}
return refund;
}
@Override
protected void validate(Refund refund) throws ResponseCodeException {
super.validate(refund);
String paymentIntentId = refund.getPaymentIntent();
if (paymentIntentId == null && refund.getCharge() == null) {
throw new ResponseCodeException(400, "One of the following params should be provided for this request: payment_intent or charge.");
}
// todo: support charges too
PaymentIntent paymentIntent = stripeEntities.getEntityManager(PaymentIntent.class)
.get(paymentIntentId)
.orElseThrow(() -> ResponseCodeException.noSuchEntity(400, "payment_intent", paymentIntentId));
if (!paymentIntent.getStatus()
.equals("succeeded")) {
throw new ResponseCodeException(400, String.format("This PaymentIntent (%s) does not have a successful charge to refund.", paymentIntentId));
}
}
@Override
protected Refund perform(Refund existingRefund, Refund updatedRefund, String operation, Map<String, Object> formData) throws ResponseCodeException {
if (operation.equals("cancel")) {
String status = updatedRefund.getStatus();
if (status.equals("pending")) {
updatedRefund.setStatus("canceled");
} else if (status.equals("canceled")) {
// Already canceled, nothing to be done
} else {
throw new ResponseCodeException(400, "Can't cancel a refund that is in status: " + status);
}
return updatedRefund;
}
return super.perform(existingRefund, updatedRefund, operation, formData);
}
@Override
public boolean canPerformOperation(String operation) {
return operation.equals("cancel");
}
@Override | package com.sesame.oss.stripemock.entities;
class RefundManager extends AbstractEntityManager<Refund> {
private final StripeEntities stripeEntities;
protected RefundManager(Clock clock, StripeEntities stripeEntities) {
super(clock, Refund.class, "re", 24);
this.stripeEntities = stripeEntities;
}
@Override
protected Refund initialize(Refund refund, Map<String, Object> formData) throws ResponseCodeException {
refund.setStatus("succeeded");
if (refund.getAmount() == null && refund.getPaymentIntent() != null) {
refund.setAmount(stripeEntities.getEntityManager(PaymentIntent.class)
.get(refund.getPaymentIntent())
.orElseThrow(() -> ResponseCodeException.noSuchEntity(400, "payment_intent", refund.getPaymentIntent()))
.getAmount());
}
return refund;
}
@Override
protected void validate(Refund refund) throws ResponseCodeException {
super.validate(refund);
String paymentIntentId = refund.getPaymentIntent();
if (paymentIntentId == null && refund.getCharge() == null) {
throw new ResponseCodeException(400, "One of the following params should be provided for this request: payment_intent or charge.");
}
// todo: support charges too
PaymentIntent paymentIntent = stripeEntities.getEntityManager(PaymentIntent.class)
.get(paymentIntentId)
.orElseThrow(() -> ResponseCodeException.noSuchEntity(400, "payment_intent", paymentIntentId));
if (!paymentIntent.getStatus()
.equals("succeeded")) {
throw new ResponseCodeException(400, String.format("This PaymentIntent (%s) does not have a successful charge to refund.", paymentIntentId));
}
}
@Override
protected Refund perform(Refund existingRefund, Refund updatedRefund, String operation, Map<String, Object> formData) throws ResponseCodeException {
if (operation.equals("cancel")) {
String status = updatedRefund.getStatus();
if (status.equals("pending")) {
updatedRefund.setStatus("canceled");
} else if (status.equals("canceled")) {
// Already canceled, nothing to be done
} else {
throw new ResponseCodeException(400, "Can't cancel a refund that is in status: " + status);
}
return updatedRefund;
}
return super.perform(existingRefund, updatedRefund, operation, formData);
}
@Override
public boolean canPerformOperation(String operation) {
return operation.equals("cancel");
}
@Override | public List<Refund> list(QueryParameters query) { | 0 | 2023-11-03 08:51:13+00:00 | 2k |
Bo-Vane/Chatbot-api | chatbot-api-interface/src/test/java/com/bo/chatbot/api/test/SpringBootRunTest.java | [
{
"identifier": "IOpenAI",
"path": "chatbot-api-domain/src/main/java/com/bo/chatbot/api/domain/ai/IOpenAI.java",
"snippet": "public interface IOpenAI {\n String doChatGLM(String question) throws IOException;\n}"
},
{
"identifier": "IZsxqApi",
"path": "chatbot-api-domain/src/main/java/com/... | import com.alibaba.fastjson.JSON;
import com.bo.chatbot.api.domain.ai.IOpenAI;
import com.bo.chatbot.api.domain.zsxq.IZsxqApi;
import com.bo.chatbot.api.domain.zsxq.aggregates.QuestionAggregates;
import com.bo.chatbot.api.domain.zsxq.vo.Favorites;
import com.bo.chatbot.api.domain.zsxq.vo.Topic;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import java.io.IOException; | 1,597 | package com.bo.chatbot.api.test;
@SpringBootTest
@RunWith(SpringRunner.class)
public class SpringBootRunTest {
private Logger logger = LoggerFactory.getLogger(SpringBootRunTest.class);
@Value("${chatbot-api.groupId}")
private String groupId;
@Value("${chatbot-api.cookie}")
private String cookie;
@Resource
private IZsxqApi zsxqApi;
@Resource
private IOpenAI openAI;
@Test
public void test_zsxqApi() throws IOException { | package com.bo.chatbot.api.test;
@SpringBootTest
@RunWith(SpringRunner.class)
public class SpringBootRunTest {
private Logger logger = LoggerFactory.getLogger(SpringBootRunTest.class);
@Value("${chatbot-api.groupId}")
private String groupId;
@Value("${chatbot-api.cookie}")
private String cookie;
@Resource
private IZsxqApi zsxqApi;
@Resource
private IOpenAI openAI;
@Test
public void test_zsxqApi() throws IOException { | QuestionAggregates questionAggregates = zsxqApi.queryQuestion(groupId, cookie); | 2 | 2023-11-06 08:52:38+00:00 | 2k |
Arborsm/ArborCore | src/main/java/org/arbor/gtnn/api/recipe/PlantCasingCondition.java | [
{
"identifier": "IChemicalPlantReceiver",
"path": "src/main/java/org/arbor/gtnn/api/capability/IChemicalPlantReceiver.java",
"snippet": "public interface IChemicalPlantReceiver {\n /**\n * @return the cleanroom the machine is receiving from\n */\n @Nullable\n IChemicalPlantProvider getC... | import com.google.gson.JsonObject;
import com.gregtechceu.gtceu.api.machine.MetaMachine;
import com.gregtechceu.gtceu.api.machine.feature.multiblock.IMultiController;
import com.gregtechceu.gtceu.api.machine.trait.RecipeLogic;
import com.gregtechceu.gtceu.api.recipe.GTRecipe;
import com.gregtechceu.gtceu.api.recipe.RecipeCondition;
import lombok.Getter;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.chat.Component;
import net.minecraft.util.GsonHelper;
import org.arbor.gtnn.api.capability.IChemicalPlantReceiver;
import org.arbor.gtnn.api.machine.feature.IChemicalPlantProvider;
import org.arbor.gtnn.block.PlantCasingBlock;
import org.jetbrains.annotations.NotNull; | 1,235 | package org.arbor.gtnn.api.recipe;
@Getter
public class PlantCasingCondition extends RecipeCondition {
public final static PlantCasingCondition INSTANCE = new PlantCasingCondition();
| package org.arbor.gtnn.api.recipe;
@Getter
public class PlantCasingCondition extends RecipeCondition {
public final static PlantCasingCondition INSTANCE = new PlantCasingCondition();
| private PlantCasingBlock.PlantCasing plantCasing = PlantCasingBlock.PlantCasing.BRONZE; | 2 | 2023-11-04 07:59:02+00:00 | 2k |
satisfyu/HerbalBrews | common/src/main/java/satisfyu/herbalbrews/compat/rei/display/TeaKettleDisplay.java | [
{
"identifier": "TeaKettleCategory",
"path": "common/src/main/java/satisfyu/herbalbrews/compat/rei/category/TeaKettleCategory.java",
"snippet": "public class TeaKettleCategory implements DisplayCategory<TeaKettleDisplay> {\n\n\n public static final CategoryIdentifier<TeaKettleDisplay> COOKING_CAULDRO... | import me.shedaniel.rei.api.common.category.CategoryIdentifier;
import me.shedaniel.rei.api.common.display.basic.BasicDisplay;
import me.shedaniel.rei.api.common.entry.EntryIngredient;
import me.shedaniel.rei.api.common.util.EntryIngredients;
import net.minecraft.resources.ResourceLocation;
import satisfyu.herbalbrews.compat.rei.category.TeaKettleCategory;
import satisfyu.herbalbrews.recipe.TeaKettleRecipe;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional; | 1,583 | package satisfyu.herbalbrews.compat.rei.display;
public class TeaKettleDisplay extends BasicDisplay {
public TeaKettleDisplay(TeaKettleRecipe recipe) {
this(EntryIngredients.ofIngredients(new ArrayList<>(recipe.getIngredients())), Collections.singletonList(EntryIngredients.of(recipe.getResultItem(BasicDisplay.registryAccess()))), Optional.ofNullable(recipe.getId()));
}
public TeaKettleDisplay(List<EntryIngredient> inputs, List<EntryIngredient> outputs, Optional<ResourceLocation> location) {
super(inputs, outputs, location);
}
@Override
public CategoryIdentifier<?> getCategoryIdentifier() { | package satisfyu.herbalbrews.compat.rei.display;
public class TeaKettleDisplay extends BasicDisplay {
public TeaKettleDisplay(TeaKettleRecipe recipe) {
this(EntryIngredients.ofIngredients(new ArrayList<>(recipe.getIngredients())), Collections.singletonList(EntryIngredients.of(recipe.getResultItem(BasicDisplay.registryAccess()))), Optional.ofNullable(recipe.getId()));
}
public TeaKettleDisplay(List<EntryIngredient> inputs, List<EntryIngredient> outputs, Optional<ResourceLocation> location) {
super(inputs, outputs, location);
}
@Override
public CategoryIdentifier<?> getCategoryIdentifier() { | return TeaKettleCategory.COOKING_CAULDRON_DISPLAY; | 0 | 2023-11-05 16:46:52+00:00 | 2k |
sizdshi/download-server | server/common/src/main/java/com/example/utils/ResultUtils.java | [
{
"identifier": "ErrorCode",
"path": "server/common/src/main/java/com/example/common/ErrorCode.java",
"snippet": "public enum ErrorCode {\r\n /**\r\n * 成功\r\n */\r\n SUCCESS(0, \"ok\"),\r\n /**\r\n * 请求参数错误\r\n */\r\n PARAMS_ERROR(40000, \"请求参数错误\"),\r\n /**\r\n * 未登录\... | import com.example.common.ErrorCode;
import com.example.model.BaseResponse;
| 745 | package com.example.utils;
/**
* @Author: Kenneth shi
* @Description:
**/
public class ResultUtils {
/**
* 成功
*
* @param data 数据
* @return {@link BaseResponse}<{@link T}>
*/
public static <T> BaseResponse<T> success(T data) {
return new BaseResponse<>(0, data, "ok");
}
/**
* 错误
* 失败
*
* @param errorCode 错误代码
* @return {@link BaseResponse}
*/
| package com.example.utils;
/**
* @Author: Kenneth shi
* @Description:
**/
public class ResultUtils {
/**
* 成功
*
* @param data 数据
* @return {@link BaseResponse}<{@link T}>
*/
public static <T> BaseResponse<T> success(T data) {
return new BaseResponse<>(0, data, "ok");
}
/**
* 错误
* 失败
*
* @param errorCode 错误代码
* @return {@link BaseResponse}
*/
| public static <T> BaseResponse<T> error(ErrorCode errorCode) {
| 0 | 2023-11-02 06:09:03+00:00 | 2k |
RapierXbox/Benium-Client | src/main/java/net/rapierxbox/beniumclient/hacks/KillAura.java | [
{
"identifier": "Hack",
"path": "src/main/java/net/rapierxbox/beniumclient/util/Hack.java",
"snippet": "public class Hack {\r\n private final String name;\r\n\r\n private static boolean enabled;\r\n public Hack(String name)\r\n {\r\n this.name = name;\r\n }\r\n\r\n public static... | import net.minecraft.client.MinecraftClient;
import net.minecraft.entity.Entity;
import net.minecraft.util.Hand;
import net.rapierxbox.beniumclient.util.Hack;
import net.rapierxbox.beniumclient.util.BUtil;
import java.util.Random;
| 746 | package net.rapierxbox.beniumclient.hacks;
public class KillAura extends Hack {
public KillAura() {
super("KillAura");
}
private Entity target;
private static int cooldown = 5;
@Override
protected void tick(MinecraftClient client) {
| package net.rapierxbox.beniumclient.hacks;
public class KillAura extends Hack {
public KillAura() {
super("KillAura");
}
private Entity target;
private static int cooldown = 5;
@Override
protected void tick(MinecraftClient client) {
| if (BUtil.getNearestEntity(client) != null && cooldown <= 0) {
| 1 | 2023-11-09 13:23:48+00:00 | 2k |
SatyaRajAwasth1/smart-credit-manager | src/main/java/np/com/satyarajawasthi/smartcreditmanager/controller/CredentialDialogController.java | [
{
"identifier": "Credential",
"path": "src/main/java/np/com/satyarajawasthi/smartcreditmanager/model/Credential.java",
"snippet": "public class Credential {\n\n private int id;\n private String toolName;\n private String username;\n private String password;\n private String email;\n pr... | import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.stage.Stage;
import javafx.util.Duration;
import np.com.satyarajawasthi.smartcreditmanager.model.Credential;
import np.com.satyarajawasthi.smartcreditmanager.manager.CredentialManager; | 816 | package np.com.satyarajawasthi.smartcreditmanager.controller;
public class CredentialDialogController {
@FXML
private TextField toolNameField;
@FXML
private TextField usernameField;
@FXML
private TextField passwordField;
@FXML
private TextField emailField;
@FXML
private TextField remarksField;
@FXML
private DialogPane dialogPane;
private CredentialManager credentialManager;
private Stage dialogStage; | package np.com.satyarajawasthi.smartcreditmanager.controller;
public class CredentialDialogController {
@FXML
private TextField toolNameField;
@FXML
private TextField usernameField;
@FXML
private TextField passwordField;
@FXML
private TextField emailField;
@FXML
private TextField remarksField;
@FXML
private DialogPane dialogPane;
private CredentialManager credentialManager;
private Stage dialogStage; | private Credential credential; // For storing the credential to edit | 0 | 2023-11-05 03:53:02+00:00 | 2k |
AmokDev/DeathNote | src/main/java/dev/amok/DeathNote/Plugin.java | [
{
"identifier": "SQLite",
"path": "src/main/java/dev/amok/DeathNote/Database/SQLite.java",
"snippet": "public class SQLite {\n static Connection dbConnection;\n\n public static void getConnection() throws SQLException {\n dbConnection = DriverManager.getConnection(String.format(\"jdbc:sqlit... | import java.sql.SQLException;
import org.bukkit.plugin.java.JavaPlugin;
import dev.amok.DeathNote.Database.SQLite;
import dev.amok.DeathNote.Initializers.CommandInit;
import dev.amok.DeathNote.Initializers.EventInit; | 1,063 | package dev.amok.DeathNote;
public class Plugin extends JavaPlugin {
public static JavaPlugin plugin;
private static Plugin instance;
@Override
public void onEnable() {
Plugin.plugin = this;
instance = this;
getLogger().info("Loading config...");
this.saveDefaultConfig();
getLogger().info("Loading database...");
try { SQLite.getConnection(); } catch (SQLException e) { e.printStackTrace(); }
try { SQLite.createDB(); } catch (SQLException e) { e.printStackTrace(); }
CommandInit.init(); | package dev.amok.DeathNote;
public class Plugin extends JavaPlugin {
public static JavaPlugin plugin;
private static Plugin instance;
@Override
public void onEnable() {
Plugin.plugin = this;
instance = this;
getLogger().info("Loading config...");
this.saveDefaultConfig();
getLogger().info("Loading database...");
try { SQLite.getConnection(); } catch (SQLException e) { e.printStackTrace(); }
try { SQLite.createDB(); } catch (SQLException e) { e.printStackTrace(); }
CommandInit.init(); | EventInit.init(); | 2 | 2023-11-03 09:03:34+00:00 | 2k |
wqj666666/embyboot | src/main/java/com/emby/boot/controller/EmbyUserController.java | [
{
"identifier": "EmbyUser",
"path": "src/main/java/com/emby/boot/dao/entity/EmbyUser.java",
"snippet": "@Schema(description = \"emby用户成员变量\")\n@Data\n@TableName(\"user\")\npublic class EmbyUser {\n @Schema(description = \"电报用户id\",example = \"123\")\n private String chatid;\n\n @Schema(descript... | import com.emby.boot.dao.entity.EmbyUser;
import com.emby.boot.dto.resp.EmbyUserInfoResp;
import com.emby.boot.dto.resp.RestResp;
import com.emby.boot.service.EmbyUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; | 1,109 | package com.emby.boot.controller;
/**
* @author laojian
* @date 2023/10/9 17:32
*/
@Tag(name = "EmbyUserController",description = "emby用户控制类")
@RestController
@RequestMapping("/emby")
@RequiredArgsConstructor
public class EmbyUserController {
private final EmbyUserService embyUserService;
/**
* emby用户注册接口
* @param name
* @return
*/
@Operation(summary = "emby用户注册接口")
@PostMapping("/userNew") | package com.emby.boot.controller;
/**
* @author laojian
* @date 2023/10/9 17:32
*/
@Tag(name = "EmbyUserController",description = "emby用户控制类")
@RestController
@RequestMapping("/emby")
@RequiredArgsConstructor
public class EmbyUserController {
private final EmbyUserService embyUserService;
/**
* emby用户注册接口
* @param name
* @return
*/
@Operation(summary = "emby用户注册接口")
@PostMapping("/userNew") | public RestResp<EmbyUser> userNew(String name, String chatid){ | 0 | 2023-11-09 17:15:57+00:00 | 2k |
BaderTim/minecraft-measurement-mod | src/main/java/io/github/mmm/renderer/SurveyRenderer.java | [
{
"identifier": "Edge",
"path": "src/main/java/io/github/mmm/measurement/survey/objects/graph/Edge.java",
"snippet": "public class Edge {\n\n private Vertex startVertex;\n private Vertex endVertex;\n private int index;\n\n public Edge(Vertex startVertex, Vertex endVertex, int index) {\n ... | import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.*;
import io.github.mmm.measurement.survey.objects.graph.Edge;
import io.github.mmm.measurement.survey.objects.graph.Vertex;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.ShaderInstance;
import net.minecraft.client.renderer.entity.DisplayRenderer;
import net.minecraft.client.renderer.entity.EntityRenderer;
import net.minecraft.client.renderer.entity.EntityRenderers;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.client.event.RenderGuiOverlayEvent;
import net.minecraftforge.client.event.RenderLevelStageEvent;
import org.joml.Quaternionf;
import org.joml.Vector3f;
import java.awt.*;
import static io.github.mmm.MMM.SURVEY_CONTROLLER; | 681 | package io.github.mmm.renderer;
public class SurveyRenderer {
private Tesselator tesselator;
private BufferBuilder buffer;
private VertexBuffer vertexBuffer;
private Color edgeColor;
private Color vertexColor;
public SurveyRenderer() {
this.edgeColor = Color.RED;
this.vertexColor = Color.WHITE;
}
public void renderGraph(RenderLevelStageEvent event) {
renderVerticesNew(event);
beginRender();
renderEdges();
endRender(event);
}
private void renderVerticesNew(RenderLevelStageEvent event) {
Font fontRenderer = Minecraft.getInstance().font;
PoseStack matrixStack = event.getPoseStack();
Vec3 viewerPos = Minecraft.getInstance().gameRenderer.getMainCamera().getPosition();
Quaternionf viewerRot = Minecraft.getInstance().gameRenderer.getMainCamera().rotation();
| package io.github.mmm.renderer;
public class SurveyRenderer {
private Tesselator tesselator;
private BufferBuilder buffer;
private VertexBuffer vertexBuffer;
private Color edgeColor;
private Color vertexColor;
public SurveyRenderer() {
this.edgeColor = Color.RED;
this.vertexColor = Color.WHITE;
}
public void renderGraph(RenderLevelStageEvent event) {
renderVerticesNew(event);
beginRender();
renderEdges();
endRender(event);
}
private void renderVerticesNew(RenderLevelStageEvent event) {
Font fontRenderer = Minecraft.getInstance().font;
PoseStack matrixStack = event.getPoseStack();
Vec3 viewerPos = Minecraft.getInstance().gameRenderer.getMainCamera().getPosition();
Quaternionf viewerRot = Minecraft.getInstance().gameRenderer.getMainCamera().rotation();
| for(Vertex vertex : SURVEY_CONTROLLER.getSurvey().getVertices()) { | 2 | 2023-11-06 16:56:46+00:00 | 2k |
Guzz-drk/api_gestao_vagas | src/main/java/br/com/guzz/gestao_vagas/modules/candidate/useCases/CreateCandidateUseCase.java | [
{
"identifier": "UserFoundException",
"path": "src/main/java/br/com/guzz/gestao_vagas/exceptions/UserFoundException.java",
"snippet": "public class UserFoundException extends RuntimeException{\n \n public UserFoundException(){\n super(\"Usuário já existe!\");\n }\n}"
},
{
"identi... | import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import br.com.guzz.gestao_vagas.exceptions.UserFoundException;
import br.com.guzz.gestao_vagas.modules.candidate.entity.CandidateEntity;
import br.com.guzz.gestao_vagas.modules.candidate.repository.CandidateRepository; | 659 | package br.com.guzz.gestao_vagas.modules.candidate.useCases;
@Service
public class CreateCandidateUseCase {
@Autowired
private CandidateRepository candidateRepository;
@Autowired
private PasswordEncoder passwordEncoder;
public CandidateEntity execute(CandidateEntity candidateEntity) {
this.candidateRepository.findByUsernameOrEmail(candidateEntity.getUsername(), candidateEntity.getEmail())
.ifPresent((user) -> { | package br.com.guzz.gestao_vagas.modules.candidate.useCases;
@Service
public class CreateCandidateUseCase {
@Autowired
private CandidateRepository candidateRepository;
@Autowired
private PasswordEncoder passwordEncoder;
public CandidateEntity execute(CandidateEntity candidateEntity) {
this.candidateRepository.findByUsernameOrEmail(candidateEntity.getUsername(), candidateEntity.getEmail())
.ifPresent((user) -> { | throw new UserFoundException(); | 0 | 2023-11-05 13:45:16+00:00 | 2k |
alejandalb/metaIoT-operation-manager-service | src/main/java/com/upv/alalca3/metaIoT/operationmanager/controllers/rest/OperationController.java | [
{
"identifier": "Operation",
"path": "src/main/java/com/upv/alalca3/metaIoT/operationmanager/model/Operation.java",
"snippet": "@Entity\npublic class Operation {\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate Long id;\n\n\tprivate String type;\n\tprivate String parameters;\n\tp... | import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.upv.alalca3.metaIoT.operationmanager.model.Operation;
import com.upv.alalca3.metaIoT.operationmanager.service.IMqttService;
import com.upv.alalca3.metaIoT.operationmanager.service.impl.OperationServiceImpl; | 936 | /**
*
*/
package com.upv.alalca3.metaIoT.operationmanager.controllers.rest;
/**
*
*/
@RestController
public class OperationController {
@Autowired
private IMqttService mqttService;
@Autowired | /**
*
*/
package com.upv.alalca3.metaIoT.operationmanager.controllers.rest;
/**
*
*/
@RestController
public class OperationController {
@Autowired
private IMqttService mqttService;
@Autowired | private OperationServiceImpl opService; | 2 | 2023-11-06 18:25:36+00:00 | 2k |
hoffmann-g/trabalho-final-poo | src/main/java/application/tabs/RentalTab.java | [
{
"identifier": "DataAccessObject",
"path": "src/main/java/model/dao/DataAccessObject.java",
"snippet": "public interface DataAccessObject<T> {\n\n List<T> readRows();\n void insertRow(T t);\n void deleteRow(T t);\n boolean contains(T t);\n}"
},
{
"identifier": "CarRental",
"path... | import model.dao.DataAccessObject;
import model.entities.CarRental;
import model.entities.Vehicle;
import model.services.RentalService;
import javax.swing.*;
import java.security.InvalidParameterException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List; | 907 | package application.tabs;
public class RentalTab extends Tab<CarRental>{
private final InvoiceTab invoiceTab;
private final DataAccessObject<CarRental> carRentalDao;
private final DataAccessObject<Vehicle> vehicleDao; | package application.tabs;
public class RentalTab extends Tab<CarRental>{
private final InvoiceTab invoiceTab;
private final DataAccessObject<CarRental> carRentalDao;
private final DataAccessObject<Vehicle> vehicleDao; | private final RentalService rentalService; | 3 | 2023-11-08 15:22:05+00:00 | 2k |
InfantinoAndrea00/polimi-software-engineering-project-2022 | src/main/java/it/polimi/ingsw/server/controller/states/Initialize.java | [
{
"identifier": "Server",
"path": "src/main/java/it/polimi/ingsw/server/Server.java",
"snippet": "public class Server {\n public static final int PORT = 5555;\n public static ViewObserver viewObserver;\n public static AtomicBoolean creatingGame;\n public static Game game;\n\n public stati... | import it.polimi.ingsw.server.Server;
import it.polimi.ingsw.server.controller.GameController;
import it.polimi.ingsw.server.controller.GameControllerState;
import it.polimi.ingsw.server.model.GameRound;
import java.util.ArrayList;
import java.util.List; | 1,354 | package it.polimi.ingsw.server.controller.states;
/**
* Class in which the game is initialized
*/
public class Initialize implements GameControllerState {
@Override
public void nextState(GameController g) {
g.setState(new RefillCloudTiles());
}
@Override
public void Action(Object nullObject1, Object nullObject2) {
int firstPlayerId = (int) (Math.random() * Server.game.getPlayerNumber());
List<Integer> currentRound = new ArrayList<>();
int i;
for(i=firstPlayerId; i<Server.game.getPlayerNumber(); i++)
currentRound.add(i);
for(i=0; i<firstPlayerId; i++)
currentRound.add(i); | package it.polimi.ingsw.server.controller.states;
/**
* Class in which the game is initialized
*/
public class Initialize implements GameControllerState {
@Override
public void nextState(GameController g) {
g.setState(new RefillCloudTiles());
}
@Override
public void Action(Object nullObject1, Object nullObject2) {
int firstPlayerId = (int) (Math.random() * Server.game.getPlayerNumber());
List<Integer> currentRound = new ArrayList<>();
int i;
for(i=firstPlayerId; i<Server.game.getPlayerNumber(); i++)
currentRound.add(i);
for(i=0; i<firstPlayerId; i++)
currentRound.add(i); | Server.game.currentRound = new GameRound(currentRound); | 3 | 2023-11-06 00:50:18+00:00 | 2k |
Space-shooter-III/game | game/src/main/java/com/github/spaceshooteriii/game/display/compoments/GamePanel.java | [
{
"identifier": "Game",
"path": "game/src/main/java/com/github/spaceshooteriii/game/Game.java",
"snippet": "public class Game {\n\n private JFrame frame;\n private GamePanel gamePanel;\n private static @Getter GameState state;\n\n public static final int WIDTH = 820;\n public static final... | import com.github.spaceshooteriii.game.Game;
import com.github.spaceshooteriii.game.event.listeners.KeyBoardEventListener;
import com.github.spaceshooteriii.game.event.listeners.MouseEventListener;
import com.github.spaceshooteriii.game.event.listeners.MouseMotionEventListener;
import com.github.spaceshooteriii.game.event.listeners.MouseWheelEventListener;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints; | 1,024 | package com.github.spaceshooteriii.game.display.compoments;
public class GamePanel extends JPanel implements Runnable {
private Thread gameThread;
private final int FPS;
| package com.github.spaceshooteriii.game.display.compoments;
public class GamePanel extends JPanel implements Runnable {
private Thread gameThread;
private final int FPS;
| private KeyBoardEventListener keyListener; | 1 | 2023-11-03 11:18:00+00:00 | 2k |
conductor-oss/conductor | core/src/main/java/com/netflix/conductor/core/storage/DummyPayloadStorage.java | [
{
"identifier": "ExternalStorageLocation",
"path": "common/src/main/java/com/netflix/conductor/common/run/ExternalStorageLocation.java",
"snippet": "public class ExternalStorageLocation {\n\n private String uri;\n private String path;\n\n public String getUri() {\n return uri;\n }\n\n... | import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.UUID;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.netflix.conductor.common.run.ExternalStorageLocation;
import com.netflix.conductor.common.utils.ExternalPayloadStorage;
import com.fasterxml.jackson.databind.ObjectMapper; | 1,184 | /*
* Copyright 2022 Conductor Authors.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.netflix.conductor.core.storage;
/**
* A dummy implementation of {@link ExternalPayloadStorage} used when no external payload is
* configured
*/
public class DummyPayloadStorage implements ExternalPayloadStorage {
private static final Logger LOGGER = LoggerFactory.getLogger(DummyPayloadStorage.class);
private ObjectMapper objectMapper;
private File payloadDir;
public DummyPayloadStorage() {
try {
this.objectMapper = new ObjectMapper();
this.payloadDir = Files.createTempDirectory("payloads").toFile();
LOGGER.info(
"{} initialized in directory: {}",
this.getClass().getSimpleName(),
payloadDir.getAbsolutePath());
} catch (IOException ioException) {
LOGGER.error(
"Exception encountered while creating payloads directory : {}",
ioException.getMessage());
}
}
@Override | /*
* Copyright 2022 Conductor Authors.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.netflix.conductor.core.storage;
/**
* A dummy implementation of {@link ExternalPayloadStorage} used when no external payload is
* configured
*/
public class DummyPayloadStorage implements ExternalPayloadStorage {
private static final Logger LOGGER = LoggerFactory.getLogger(DummyPayloadStorage.class);
private ObjectMapper objectMapper;
private File payloadDir;
public DummyPayloadStorage() {
try {
this.objectMapper = new ObjectMapper();
this.payloadDir = Files.createTempDirectory("payloads").toFile();
LOGGER.info(
"{} initialized in directory: {}",
this.getClass().getSimpleName(),
payloadDir.getAbsolutePath());
} catch (IOException ioException) {
LOGGER.error(
"Exception encountered while creating payloads directory : {}",
ioException.getMessage());
}
}
@Override | public ExternalStorageLocation getLocation( | 0 | 2023-12-08 06:06:09+00:00 | 2k |
specmock/specmock | specmock/src/test/java/io/specmock/core/HttpExchangeTest.java | [
{
"identifier": "Example1Request",
"path": "specmock/src/test/java/io/specmock/core/example/Example1Request.java",
"snippet": "public class Example1Request {\n private String stringValue;\n private Integer integerValue;\n private Long longValue;\n private BigDecimal bigDecimalValue;\n\n /... | import static org.assertj.core.api.Assertions.assertThat;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import io.specmock.core.example.Example1Request;
import io.specmock.core.example.Example1Response;
import io.specmock.core.example.Example3Response; | 1,193 | /*
* Copyright 2023 SpecMock
* (c) 2023 SpecMock Contributors
* SPDX-License-Identifier: Apache-2.0
*
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.specmock.core;
class HttpExchangeTest {
private final Example1Request exampleRequest = new Example1Request("REQ", 1, 1L, BigDecimal.ONE);
private final Example1Response exampleResponse = new Example1Response("RES");
@Test
void matchRequest() {
final HttpExchange exchange = HttpExchange.builder()
.requestObject(exampleRequest)
.responseStatus(HttpStatus.OK)
.responseObject(exampleResponse)
.build();
// Correct Class
assertThat(exchange.isMatchRequest(Example1Request.class, Example1Response.class)).isTrue();
assertThat(exchange.isNotMatchRequest(Example1Request.class, Example1Response.class)).isFalse();
// Incorrect Class | /*
* Copyright 2023 SpecMock
* (c) 2023 SpecMock Contributors
* SPDX-License-Identifier: Apache-2.0
*
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.specmock.core;
class HttpExchangeTest {
private final Example1Request exampleRequest = new Example1Request("REQ", 1, 1L, BigDecimal.ONE);
private final Example1Response exampleResponse = new Example1Response("RES");
@Test
void matchRequest() {
final HttpExchange exchange = HttpExchange.builder()
.requestObject(exampleRequest)
.responseStatus(HttpStatus.OK)
.responseObject(exampleResponse)
.build();
// Correct Class
assertThat(exchange.isMatchRequest(Example1Request.class, Example1Response.class)).isTrue();
assertThat(exchange.isNotMatchRequest(Example1Request.class, Example1Response.class)).isFalse();
// Incorrect Class | assertThat(exchange.isMatchRequest(Example1Request.class, Example3Response.class)).isFalse(); | 2 | 2023-12-13 10:43:07+00:00 | 2k |
kdhrubo/db2rest | src/main/java/com/homihq/db2rest/rsql/parser/MyBatisFilterVisitor.java | [
{
"identifier": "OperatorV2",
"path": "src/main/java/com/homihq/db2rest/rsql/operators/OperatorV2.java",
"snippet": "public interface OperatorV2 {\n\n SqlCriterion handle(SqlColumn<Object> column, String value, Class type);\n\n default SqlCriterion handle(SqlColumn<Object> column, List<String> val... | import static org.mybatis.dynamic.sql.SqlBuilder.*;
import java.util.ArrayList;
import java.util.List;
import com.homihq.db2rest.rsql.operators.OperatorV2;
import com.homihq.db2rest.rsql.operators.RSQLOperatorHandlers;
import cz.jirutka.rsql.parser.ast.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.dynamic.sql.*; | 772 | package com.homihq.db2rest.rsql.parser;
@RequiredArgsConstructor
@Slf4j
public class MyBatisFilterVisitor implements RSQLVisitor<SqlCriterion, Object> {
private final SqlTable sqlTable;
@Override
public SqlCriterion visit(AndNode node, Object optionalParameter) {
List<AndOrCriteriaGroup> criterionList = new ArrayList<>();
for (Node child : node.getChildren()) {
criterionList.add(and(child.accept(this, optionalParameter)));
}
return processCriteriaGroup(criterionList);
}
@Override
public SqlCriterion visit(OrNode node, Object optionalParameter) {
List<AndOrCriteriaGroup> criterionList = new ArrayList<>();
for (Node child : node.getChildren()) {
criterionList.add(or(child.accept(this, optionalParameter)));
}
return processCriteriaGroup(criterionList);
}
@Override
public SqlCriterion visit(ComparisonNode comparisonNode, Object optionalParameter) {
ComparisonOperator op = comparisonNode.getOperator();
String columnName = comparisonNode.getSelector();
| package com.homihq.db2rest.rsql.parser;
@RequiredArgsConstructor
@Slf4j
public class MyBatisFilterVisitor implements RSQLVisitor<SqlCriterion, Object> {
private final SqlTable sqlTable;
@Override
public SqlCriterion visit(AndNode node, Object optionalParameter) {
List<AndOrCriteriaGroup> criterionList = new ArrayList<>();
for (Node child : node.getChildren()) {
criterionList.add(and(child.accept(this, optionalParameter)));
}
return processCriteriaGroup(criterionList);
}
@Override
public SqlCriterion visit(OrNode node, Object optionalParameter) {
List<AndOrCriteriaGroup> criterionList = new ArrayList<>();
for (Node child : node.getChildren()) {
criterionList.add(or(child.accept(this, optionalParameter)));
}
return processCriteriaGroup(criterionList);
}
@Override
public SqlCriterion visit(ComparisonNode comparisonNode, Object optionalParameter) {
ComparisonOperator op = comparisonNode.getOperator();
String columnName = comparisonNode.getSelector();
| OperatorV2 operatorHandler = RSQLOperatorHandlers.getOperatorHandler(op.getSymbol()); | 0 | 2023-12-14 19:26:05+00:00 | 2k |
kaifangqian/open-sign | src/main/java/com/resrun/service/verify/SignVerifyService.java | [
{
"identifier": "SignPdfInfoVo",
"path": "src/main/java/com/resrun/service/pojo/SignPdfInfoVo.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@ApiModel(\"数字签名信息返回对象\")\npublic class SignPdfInfoVo {\n /**\n * PDF名称\n */\n @ApiModelProperty(value = \"PDF名称\")\n private ... | import com.resrun.service.pojo.SignPdfInfoVo;
import com.resrun.controller.vo.response.VerifyResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; | 1,125 | package com.resrun.service.verify;
/**
* @Description: 在线签名验签服务实现类
* @Package: com.resrun.service.verify
* @ClassName: SignVerifyServiceImpl
* @copyright 北京资源律动科技有限公司
*/
@Slf4j
@Service
public class SignVerifyService{
/**
* 获取pdf签名图片信息
* @return 提取结果
*/
public VerifyResponse getImageFromPdf(byte[] bytes, String fileName) {
VerifyResponse response = new VerifyResponse(); | package com.resrun.service.verify;
/**
* @Description: 在线签名验签服务实现类
* @Package: com.resrun.service.verify
* @ClassName: SignVerifyServiceImpl
* @copyright 北京资源律动科技有限公司
*/
@Slf4j
@Service
public class SignVerifyService{
/**
* 获取pdf签名图片信息
* @return 提取结果
*/
public VerifyResponse getImageFromPdf(byte[] bytes, String fileName) {
VerifyResponse response = new VerifyResponse(); | SignPdfInfoVo signPdfInfo = new SignPdfInfoVo(); | 0 | 2023-12-14 06:53:32+00:00 | 2k |
Mahmud0808/ColorBlendr | app/src/main/java/com/drdisagree/colorblendr/config/RPrefs.java | [
{
"identifier": "EXCLUDED_PREFS_FROM_BACKUP",
"path": "app/src/main/java/com/drdisagree/colorblendr/common/Const.java",
"snippet": "public static Set<String> EXCLUDED_PREFS_FROM_BACKUP = new HashSet<>(\n Arrays.asList(\n PREF_WORKING_METHOD,\n MONET_LAST_UPDATED\n ... | import static android.content.Context.MODE_PRIVATE;
import static com.drdisagree.colorblendr.common.Const.EXCLUDED_PREFS_FROM_BACKUP;
import android.content.SharedPreferences;
import android.util.Log;
import androidx.annotation.NonNull;
import com.drdisagree.colorblendr.ColorBlendr;
import com.drdisagree.colorblendr.common.Const;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map; | 1,120 | package com.drdisagree.colorblendr.config;
@SuppressWarnings("unused")
public class RPrefs {
private static final String TAG = RPrefs.class.getSimpleName();
| package com.drdisagree.colorblendr.config;
@SuppressWarnings("unused")
public class RPrefs {
private static final String TAG = RPrefs.class.getSimpleName();
| public static SharedPreferences prefs = ColorBlendr.getAppContext().createDeviceProtectedStorageContext().getSharedPreferences(Const.SharedPrefs, MODE_PRIVATE); | 1 | 2023-12-06 13:20:16+00:00 | 2k |
bzvs1992/spring-boot-holiday-starter | src/main/java/cn/bzvs/holiday/util/HolidayFix.java | [
{
"identifier": "ConstantData",
"path": "src/main/java/cn/bzvs/holiday/autoconfigure/ConstantData.java",
"snippet": "public class ConstantData {\n\n /**\n * 所有日期数据\n */\n private static final Map<String, CalendarVO> ALL_DATE_MAP = new ConcurrentHashMap<>();\n\n /**\n * 初始化,并设置数据\n ... | import cn.bzvs.holiday.autoconfigure.ConstantData;
import cn.bzvs.holiday.autoconfigure.properties.HolidayProperties;
import cn.bzvs.holiday.entity.vo.CalendarVO;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson2.JSON;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.List; | 828 | package cn.bzvs.holiday.util;
/**
* 节假日修复工具
*
* @author bzvs
* @date 2024/12/04
* @since 1.0.0
*/
@Slf4j
public class HolidayFix {
private HolidayFix() {
}
/**
* 重置数据
*
* @param file JSON文件
* @return boolean
*/
public static boolean reset(@NonNull File file) {
String json = FileUtil.readString(file, StandardCharsets.UTF_8);
return reset(json);
}
/**
* 重置数据
*
* @param json JSON数据
* @return boolean
*/
public static boolean reset(String json) {
try { | package cn.bzvs.holiday.util;
/**
* 节假日修复工具
*
* @author bzvs
* @date 2024/12/04
* @since 1.0.0
*/
@Slf4j
public class HolidayFix {
private HolidayFix() {
}
/**
* 重置数据
*
* @param file JSON文件
* @return boolean
*/
public static boolean reset(@NonNull File file) {
String json = FileUtil.readString(file, StandardCharsets.UTF_8);
return reset(json);
}
/**
* 重置数据
*
* @param json JSON数据
* @return boolean
*/
public static boolean reset(String json) {
try { | List<CalendarVO> calendarVOList = JSON.parseArray(json, CalendarVO.class); | 2 | 2023-12-05 10:59:02+00:00 | 2k |
HelpChat/DeluxeMenus | src/main/java/com/extendedclip/deluxemenus/utils/ItemUtils.java | [
{
"identifier": "INVENTORY_ITEM_ACCESSORS",
"path": "src/main/java/com/extendedclip/deluxemenus/utils/Constants.java",
"snippet": "public static final Map<String, Function<PlayerInventory, ItemStack>> INVENTORY_ITEM_ACCESSORS = ImmutableMap.<String, Function<PlayerInventory, ItemStack>>builder()\r\n ... | import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.PotionData;
import org.bukkit.potion.PotionType;
import org.jetbrains.annotations.NotNull;
import static com.extendedclip.deluxemenus.utils.Constants.INVENTORY_ITEM_ACCESSORS;
import static com.extendedclip.deluxemenus.utils.Constants.ITEMSADDER_PREFIX;
import static com.extendedclip.deluxemenus.utils.Constants.MMOITEMS_PREFIX;
import static com.extendedclip.deluxemenus.utils.Constants.ORAXEN_PREFIX;
import static com.extendedclip.deluxemenus.utils.Constants.PLACEHOLDER_PREFIX;
import static com.extendedclip.deluxemenus.utils.Constants.WATER_BOTTLE; | 999 | package com.extendedclip.deluxemenus.utils;
public final class ItemUtils {
private ItemUtils() {
throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
}
/**
* Checks if the string starts with the substring "placeholder-". The check is case-sensitive.
*
* @param material The string to check
* @return true if the string starts with "placeholder-", false otherwise
*/
public static boolean isPlaceholderMaterial(@NotNull final String material) {
return material.startsWith(PLACEHOLDER_PREFIX);
}
/**
* Checks if the string is a player item. The check is case-sensitive.
* Player items are: "main_hand", "off_hand", "armor_helmet", "armor_chestplate", "armor_leggings", "armor_boots"
*
* @param material The string to check
* @return true if the string is a player item, false otherwise
*/
public static boolean isPlayerItem(@NotNull final String material) {
return INVENTORY_ITEM_ACCESSORS.containsKey(material);
}
/**
* Checks if the string is an ItemsAdder item. The check is case-sensitive.
* ItemsAdder items are: "itemsadder-{namespace:name}"
*
* @param material The string to check
* @return true if the string is an ItemsAdder item, false otherwise
*/
public static boolean isItemsAdderItem(@NotNull final String material) {
return material.startsWith(ITEMSADDER_PREFIX);
}
/**
* Checks if the string is an Oraxen item. The check is case-sensitive.
* Oraxen items are: "oraxen-{namespace:name}"
*
* @param material The string to check
* @return true if the string is an Oraxen item, false otherwise
*/
public static boolean isOraxenItem(@NotNull final String material) {
return material.startsWith(ORAXEN_PREFIX);
}
/**
* Checks if the string is an MMOItems item. The check is case-sensitive.
* MMOItems items are: "mmoitems-{namespace:name}"
*
* @param material The string to check
* @return true if the string is an MMOItem item, false otherwise
*/
public static boolean isMMOItemsItem(@NotNull final String material) { | package com.extendedclip.deluxemenus.utils;
public final class ItemUtils {
private ItemUtils() {
throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
}
/**
* Checks if the string starts with the substring "placeholder-". The check is case-sensitive.
*
* @param material The string to check
* @return true if the string starts with "placeholder-", false otherwise
*/
public static boolean isPlaceholderMaterial(@NotNull final String material) {
return material.startsWith(PLACEHOLDER_PREFIX);
}
/**
* Checks if the string is a player item. The check is case-sensitive.
* Player items are: "main_hand", "off_hand", "armor_helmet", "armor_chestplate", "armor_leggings", "armor_boots"
*
* @param material The string to check
* @return true if the string is a player item, false otherwise
*/
public static boolean isPlayerItem(@NotNull final String material) {
return INVENTORY_ITEM_ACCESSORS.containsKey(material);
}
/**
* Checks if the string is an ItemsAdder item. The check is case-sensitive.
* ItemsAdder items are: "itemsadder-{namespace:name}"
*
* @param material The string to check
* @return true if the string is an ItemsAdder item, false otherwise
*/
public static boolean isItemsAdderItem(@NotNull final String material) {
return material.startsWith(ITEMSADDER_PREFIX);
}
/**
* Checks if the string is an Oraxen item. The check is case-sensitive.
* Oraxen items are: "oraxen-{namespace:name}"
*
* @param material The string to check
* @return true if the string is an Oraxen item, false otherwise
*/
public static boolean isOraxenItem(@NotNull final String material) {
return material.startsWith(ORAXEN_PREFIX);
}
/**
* Checks if the string is an MMOItems item. The check is case-sensitive.
* MMOItems items are: "mmoitems-{namespace:name}"
*
* @param material The string to check
* @return true if the string is an MMOItem item, false otherwise
*/
public static boolean isMMOItemsItem(@NotNull final String material) { | return material.startsWith(MMOITEMS_PREFIX); | 2 | 2023-12-14 23:41:07+00:00 | 2k |
lxs2601055687/contextAdminRuoYi | ruoyi-common/src/main/java/com/ruoyi/common/jackson/SensitiveJsonSerializer.java | [
{
"identifier": "SensitiveService",
"path": "ruoyi-common/src/main/java/com/ruoyi/common/core/service/SensitiveService.java",
"snippet": "public interface SensitiveService {\n\n /**\n * 是否脱敏\n */\n boolean isSensitive();\n\n}"
},
{
"identifier": "SensitiveStrategy",
"path": "ru... | import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.ruoyi.common.annotation.Sensitive;
import com.ruoyi.common.core.service.SensitiveService;
import com.ruoyi.common.enums.SensitiveStrategy;
import com.ruoyi.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import java.io.IOException;
import java.util.Objects; | 1,000 | package com.ruoyi.common.jackson;
/**
* 数据脱敏json序列化工具
*
* @author Yjoioooo
*/
@Slf4j
public class SensitiveJsonSerializer extends JsonSerializer<String> implements ContextualSerializer {
| package com.ruoyi.common.jackson;
/**
* 数据脱敏json序列化工具
*
* @author Yjoioooo
*/
@Slf4j
public class SensitiveJsonSerializer extends JsonSerializer<String> implements ContextualSerializer {
| private SensitiveStrategy strategy; | 1 | 2023-12-07 12:06:21+00:00 | 2k |
DHBin/isme-java-serve | src/main/java/cn/dhbin/isme/pms/service/RoleService.java | [
{
"identifier": "Page",
"path": "src/main/java/cn/dhbin/isme/common/response/Page.java",
"snippet": "@Data\npublic class Page<T> {\n\n private List<T> pageData;\n\n private Long total;\n\n\n /**\n * mpPage转成Page\n *\n * @param mpPage mp的分页结果\n * @param <T> 类型\n * @return ... | import cn.dhbin.isme.common.response.Page;
import cn.dhbin.isme.pms.domain.dto.PermissionDto;
import cn.dhbin.isme.pms.domain.dto.RolePageDto;
import cn.dhbin.isme.pms.domain.entity.Role;
import cn.dhbin.isme.pms.domain.request.AddRolePermissionsRequest;
import cn.dhbin.isme.pms.domain.request.AddRoleUsersRequest;
import cn.dhbin.isme.pms.domain.request.CreateRoleRequest;
import cn.dhbin.isme.pms.domain.request.RemoveRoleUsersRequest;
import cn.dhbin.isme.pms.domain.request.RolePageRequest;
import cn.dhbin.isme.pms.domain.request.UpdateRoleRequest;
import cn.hutool.core.lang.tree.Tree;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List; | 1,522 | package cn.dhbin.isme.pms.service;
/**
* RoleService
*
* @author dhb
*/
public interface RoleService extends IService<Role> {
/**
* 根据用户id查询角色
*
* @param userId 用户id
* @return 用户角色列表
*/
List<Role> findRolesByUserId(Long userId);
/**
* 根据角色编码获取权限树
*
* @param roleCode 角色编码
* @return 权限树
*/
List<Tree<Long>> findRolePermissionsTree(String roleCode);
/**
* 根据角色编码获取角色
*
* @param roleCode 角色编码
* @return 角色
*/
Role findByCode(String roleCode);
/**
* 创建角色
*
* @param request req
*/
void createRole(CreateRoleRequest request);
/**
* 分页查询
*
* @param request 请求
* @return dto
*/
Page<RolePageDto> queryPage(RolePageRequest request);
/**
* 查询角色权限
*
* @param id 角色id
* @return 角色权限
*/
List<PermissionDto> findRolePermissions(Long id);
/**
* 更新角色,当角色标识是管理员时,不给修改
*
* @param id 角色id
* @param request req
*/
void updateRole(Long id, UpdateRoleRequest request);
/**
* 删除角色,不能删除管理员
*
* @param id 角色id
*/
void removeRole(Long id);
/**
* 给角色添加权限
*
* @param request req
*/
void addRolePermissions(AddRolePermissionsRequest request);
/**
* 给角色分配用户
*
* @param roleId 角色id
* @param request req
*/ | package cn.dhbin.isme.pms.service;
/**
* RoleService
*
* @author dhb
*/
public interface RoleService extends IService<Role> {
/**
* 根据用户id查询角色
*
* @param userId 用户id
* @return 用户角色列表
*/
List<Role> findRolesByUserId(Long userId);
/**
* 根据角色编码获取权限树
*
* @param roleCode 角色编码
* @return 权限树
*/
List<Tree<Long>> findRolePermissionsTree(String roleCode);
/**
* 根据角色编码获取角色
*
* @param roleCode 角色编码
* @return 角色
*/
Role findByCode(String roleCode);
/**
* 创建角色
*
* @param request req
*/
void createRole(CreateRoleRequest request);
/**
* 分页查询
*
* @param request 请求
* @return dto
*/
Page<RolePageDto> queryPage(RolePageRequest request);
/**
* 查询角色权限
*
* @param id 角色id
* @return 角色权限
*/
List<PermissionDto> findRolePermissions(Long id);
/**
* 更新角色,当角色标识是管理员时,不给修改
*
* @param id 角色id
* @param request req
*/
void updateRole(Long id, UpdateRoleRequest request);
/**
* 删除角色,不能删除管理员
*
* @param id 角色id
*/
void removeRole(Long id);
/**
* 给角色添加权限
*
* @param request req
*/
void addRolePermissions(AddRolePermissionsRequest request);
/**
* 给角色分配用户
*
* @param roleId 角色id
* @param request req
*/ | void addRoleUsers(Long roleId, AddRoleUsersRequest request); | 5 | 2023-12-13 17:21:04+00:00 | 2k |
Earthcomputer/ModCompatChecker | root/src/main/java/net/earthcomputer/modcompatchecker/util/InheritanceUtil.java | [
{
"identifier": "IResolvedClass",
"path": "root/src/main/java/net/earthcomputer/modcompatchecker/indexer/IResolvedClass.java",
"snippet": "public sealed interface IResolvedClass permits ClassIndex, ClasspathClass {\n AccessFlags getAccess();\n @Nullable\n String getSuperclass();\n List<Strin... | import net.earthcomputer.modcompatchecker.indexer.IResolvedClass;
import net.earthcomputer.modcompatchecker.indexer.Index;
import org.jetbrains.annotations.Nullable;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set; | 1,253 | package net.earthcomputer.modcompatchecker.util;
public final class InheritanceUtil {
private InheritanceUtil() {
}
public static boolean canOverride(String subclass, String superclass, AccessFlags superMethodAccess) {
// JVMS 21 §5.4.5, assumes no intermediate subclasses between `subclass` and `superclass` which contain methods
// that can override the super method.
if (superMethodAccess.isStatic()) {
return false;
}
return switch (superMethodAccess.accessLevel()) {
case PUBLIC, PROTECTED -> true;
case PACKAGE -> AsmUtil.areSamePackage(subclass, superclass);
case PRIVATE -> false;
};
}
@Nullable
public static OwnedClassMember lookupField(Index index, String owner, String name, String desc) {
// JVMS 21 §5.4.3.2 field resolution, 1-4 (field lookup) | package net.earthcomputer.modcompatchecker.util;
public final class InheritanceUtil {
private InheritanceUtil() {
}
public static boolean canOverride(String subclass, String superclass, AccessFlags superMethodAccess) {
// JVMS 21 §5.4.5, assumes no intermediate subclasses between `subclass` and `superclass` which contain methods
// that can override the super method.
if (superMethodAccess.isStatic()) {
return false;
}
return switch (superMethodAccess.accessLevel()) {
case PUBLIC, PROTECTED -> true;
case PACKAGE -> AsmUtil.areSamePackage(subclass, superclass);
case PRIVATE -> false;
};
}
@Nullable
public static OwnedClassMember lookupField(Index index, String owner, String name, String desc) {
// JVMS 21 §5.4.3.2 field resolution, 1-4 (field lookup) | for (IResolvedClass resolvedClass = index.findClass(owner); resolvedClass != null; resolvedClass = index.findClass(owner = resolvedClass.getSuperclass())) { | 0 | 2023-12-11 00:48:12+00:00 | 2k |
wkgcass/jdkman | src/main/java/io/vproxy/jdkman/action/InitAction.java | [
{
"identifier": "JDKManConfig",
"path": "src/main/java/io/vproxy/jdkman/entity/JDKManConfig.java",
"snippet": "public class JDKManConfig implements JSONObject {\n private String defaultJDK;\n private List<JDKInfo> jdks;\n\n public static final Rule<JDKManConfig> rule = new ObjectRule<>(() -> ne... | import io.vproxy.base.util.LogType;
import io.vproxy.base.util.Logger;
import io.vproxy.base.util.OS;
import io.vproxy.base.util.Utils;
import io.vproxy.jdkman.entity.JDKManConfig;
import io.vproxy.jdkman.ex.ErrorResult;
import io.vproxy.jdkman.res.ResConsts;
import vjson.Stringifier;
import vjson.simple.SimpleString;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set; | 1,063 | package io.vproxy.jdkman.action;
public class InitAction implements Action {
private static final Set<String> EXECUTABLES = new HashSet<>() {{
addAll(Arrays.asList(
"jar", "jarsigner", "java", "javac",
"javadoc", "javap", "jcmd", "jconsole",
"jdb", "jdeprscan", "jdeps", "jfr",
"jhsdb", "jimage", "jinfo", "jlink",
"jmap", "jmod", "jpackage", "jps",
"jrunscript", "jshell", "jstack",
"jstat", "jstatd", "jwebserver",
"keytool", "rmiregistry", "serialver"));
addAll(Arrays.asList(
"jaotc", "jpackager"
));
addAll(Arrays.asList(
"appletviewer", "extcheck", "idlj",
"javafxpackager", "javah", "javapackager",
"jhat", "jjs", "jmc", "jsadebugd",
"jvisualvm", "native2ascii", "orbd",
"pack200", "policytool", "rmic", "rmid",
"schemagen", "servertool", "tnameserv",
"unpack200", "wsgen", "wsimport", "xjc"));
addAll(Arrays.asList(
"javaws", "jcontrol", "jweblauncher"
));
}};
@Override
public String validate(String[] options) {
if (options.length != 0 && options.length != 1) {
return STR."unknown options for `init`: \{Arrays.toString(options)}";
}
if (options.length > 0 && !Set.of("sh", "pwsh").contains(options[0])) {
return STR."the first option must be 'sh|pwsh': \{options[0]}";
}
return null;
}
private enum ShellType {
shell,
pwsh,
}
@Override | package io.vproxy.jdkman.action;
public class InitAction implements Action {
private static final Set<String> EXECUTABLES = new HashSet<>() {{
addAll(Arrays.asList(
"jar", "jarsigner", "java", "javac",
"javadoc", "javap", "jcmd", "jconsole",
"jdb", "jdeprscan", "jdeps", "jfr",
"jhsdb", "jimage", "jinfo", "jlink",
"jmap", "jmod", "jpackage", "jps",
"jrunscript", "jshell", "jstack",
"jstat", "jstatd", "jwebserver",
"keytool", "rmiregistry", "serialver"));
addAll(Arrays.asList(
"jaotc", "jpackager"
));
addAll(Arrays.asList(
"appletviewer", "extcheck", "idlj",
"javafxpackager", "javah", "javapackager",
"jhat", "jjs", "jmc", "jsadebugd",
"jvisualvm", "native2ascii", "orbd",
"pack200", "policytool", "rmic", "rmid",
"schemagen", "servertool", "tnameserv",
"unpack200", "wsgen", "wsimport", "xjc"));
addAll(Arrays.asList(
"javaws", "jcontrol", "jweblauncher"
));
}};
@Override
public String validate(String[] options) {
if (options.length != 0 && options.length != 1) {
return STR."unknown options for `init`: \{Arrays.toString(options)}";
}
if (options.length > 0 && !Set.of("sh", "pwsh").contains(options[0])) {
return STR."the first option must be 'sh|pwsh': \{options[0]}";
}
return null;
}
private enum ShellType {
shell,
pwsh,
}
@Override | public boolean execute(JDKManConfig config, String[] options) throws Exception { | 0 | 2023-12-07 04:55:35+00:00 | 2k |
DantSu/studio | driver/src/main/java/studio/driver/model/fs/FsDeviceInfos.java | [
{
"identifier": "SecurityUtils",
"path": "core/src/main/java/studio/core/v1/utils/SecurityUtils.java",
"snippet": "public class SecurityUtils {\n\n private static final Logger LOGGER = LogManager.getLogger(SecurityUtils.class);\n\n private static final byte[] HEX_ARRAY = \"0123456789abcdef\".getBy... | import studio.core.v1.utils.SecurityUtils;
import studio.driver.model.DeviceInfos; | 1,159 | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package studio.driver.model.fs;
public class FsDeviceInfos extends DeviceInfos {
private byte[] deviceKey;
private long sdCardSizeInBytes;
private long usedSpaceInBytes;
public byte[] getDeviceKey() {
return deviceKey;
}
public void setDeviceKey(byte[] deviceId) {
this.deviceKey = deviceId;
}
public long getSdCardSizeInBytes() {
return sdCardSizeInBytes;
}
public void setSdCardSizeInBytes(long sdCardSizeInBytes) {
this.sdCardSizeInBytes = sdCardSizeInBytes;
}
public long getUsedSpaceInBytes() {
return usedSpaceInBytes;
}
public void setUsedSpaceInBytes(long usedSpaceInBytes) {
this.usedSpaceInBytes = usedSpaceInBytes;
}
@Override
public String toString() { | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package studio.driver.model.fs;
public class FsDeviceInfos extends DeviceInfos {
private byte[] deviceKey;
private long sdCardSizeInBytes;
private long usedSpaceInBytes;
public byte[] getDeviceKey() {
return deviceKey;
}
public void setDeviceKey(byte[] deviceId) {
this.deviceKey = deviceId;
}
public long getSdCardSizeInBytes() {
return sdCardSizeInBytes;
}
public void setSdCardSizeInBytes(long sdCardSizeInBytes) {
this.sdCardSizeInBytes = sdCardSizeInBytes;
}
public long getUsedSpaceInBytes() {
return usedSpaceInBytes;
}
public void setUsedSpaceInBytes(long usedSpaceInBytes) {
this.usedSpaceInBytes = usedSpaceInBytes;
}
@Override
public String toString() { | return "FsDeviceInfos{" + "uuid=" + SecurityUtils.encodeHex(deviceKey) + ", firmwareMajor=" + getFirmwareMajor() | 0 | 2023-12-14 15:08:35+00:00 | 2k |
cworld1/notie | app/src/main/java/com/cworld/notie/fragment/SettingsFragment.java | [
{
"identifier": "AboutActivity",
"path": "app/src/main/java/com/cworld/notie/AboutActivity.java",
"snippet": "public class AboutActivity extends AppCompatActivity {\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n EdgeToEdge.enable(this);\n super.onCreate(savedI... | import android.os.Bundle;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import com.cworld.notie.AboutActivity;
import com.cworld.notie.R;
import com.cworld.notie.util.PreferenceHelper;
import java.util.Objects;
| 909 | package com.cworld.notie.fragment;
public class SettingsFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.preferences, rootKey);
// click repo
| package com.cworld.notie.fragment;
public class SettingsFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.preferences, rootKey);
// click repo
| PreferenceHelper.clickItem(
| 1 | 2023-12-09 16:22:05+00:00 | 2k |
wuhit/slash | src/main/java/com/wuhit/core/SshClient.java | [
{
"identifier": "Logger",
"path": "src/main/java/com/wuhit/Logger.java",
"snippet": "public final class Logger {\n\n private String ruciaHome;\n\n private String fileName;\n\n private String separator;\n\n private FileWriter fileWriter;\n\n private void initFileWriter() {\n String parentDir =\n ... | import com.jcraft.jsch.*;
import com.wuhit.Logger;
import com.wuhit.SlashException;
import com.wuhit.StringUtils;
import com.wuhit.configure.*;
import com.wuhit.configure.UserInfo;
import com.wuhit.mfa.BaseMFA;
import com.wuhit.mfa.GoogleMFA;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; | 1,475 | package com.wuhit.core;
public class SshClient {
private Ssh ssh;
| package com.wuhit.core;
public class SshClient {
private Ssh ssh;
| private Logger logger; | 0 | 2023-12-13 03:35:39+00:00 | 2k |
conductor-oss/conductor-community | persistence/mysql-persistence/src/test/java/com/netflix/conductor/mysql/dao/MySQLMetadataDAOTest.java | [
{
"identifier": "TestObjectMapperConfiguration",
"path": "test-util/src/test/java/com/netflix/conductor/common/config/TestObjectMapperConfiguration.java",
"snippet": "@Configuration\npublic class TestObjectMapperConfiguration {\n\n @Bean\n public ObjectMapper testObjectMapper() {\n return n... | import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.flywaydb.core.Flyway;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import com.netflix.conductor.common.config.TestObjectMapperConfiguration;
import com.netflix.conductor.common.metadata.events.EventHandler;
import com.netflix.conductor.common.metadata.tasks.TaskDef;
import com.netflix.conductor.common.metadata.workflow.WorkflowDef;
import com.netflix.conductor.core.exception.NonTransientException;
import com.netflix.conductor.mysql.config.MySQLConfiguration;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue; | 1,120 | /*
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.netflix.conductor.mysql.dao;
@ContextConfiguration(
classes = { | /*
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.netflix.conductor.mysql.dao;
@ContextConfiguration(
classes = { | TestObjectMapperConfiguration.class, | 0 | 2023-12-08 06:06:20+00:00 | 2k |
zhouyqxy/aurora_Lite | src/main/java/com/aurora/controller/PhotoController.java | [
{
"identifier": "FilePathEnum",
"path": "src/main/java/com/aurora/enums/FilePathEnum.java",
"snippet": "@Getter\n@AllArgsConstructor\npublic enum FilePathEnum {\n\n AVATAR(\"aurora/avatar/\", \"头像路径\"),\n\n ARTICLE(\"aurora/articles/\", \"文章图片路径\"),\n\n VOICE(\"aurora/voice/\", \"音频路径\"),\n\n ... | import com.aurora.annotation.OptLog;
import com.aurora.enums.FilePathEnum;
import com.aurora.model.dto.PageResultDTO;
import com.aurora.model.dto.PhotoAdminDTO;
import com.aurora.model.dto.PhotoDTO;
import com.aurora.service.PhotoService;
import com.aurora.model.vo.*;
import com.aurora.strategy.context.UploadStrategyContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.Valid;
import java.util.List;
import static com.aurora.constant.OptTypeConstant.*; | 1,043 | package com.aurora.controller;
@Api(tags = "照片模块")
@RestController
public class PhotoController {
@Autowired
private PhotoService photoService;
@Autowired
private UploadStrategyContext uploadStrategyContext;
@OptLog(optType = UPLOAD)
@ApiOperation(value = "上传照片")
@ApiImplicitParam(name = "file", value = "照片", required = true, dataType = "MultipartFile")
@PostMapping("/admin/photos/upload")
public ResultVO<String> savePhotoAlbumCover(MultipartFile file) { | package com.aurora.controller;
@Api(tags = "照片模块")
@RestController
public class PhotoController {
@Autowired
private PhotoService photoService;
@Autowired
private UploadStrategyContext uploadStrategyContext;
@OptLog(optType = UPLOAD)
@ApiOperation(value = "上传照片")
@ApiImplicitParam(name = "file", value = "照片", required = true, dataType = "MultipartFile")
@PostMapping("/admin/photos/upload")
public ResultVO<String> savePhotoAlbumCover(MultipartFile file) { | return ResultVO.ok(uploadStrategyContext.executeUploadStrategy(file, FilePathEnum.PHOTO.getPath())); | 0 | 2023-12-05 03:38:51+00:00 | 2k |
khaHesham/Match-Reservation-System | Api/src/main/java/com/premierleague/reservation/api/service/UserService.java | [
{
"identifier": "UserDTO",
"path": "Api/src/main/java/com/premierleague/reservation/api/dtos/UserDTO.java",
"snippet": "@Setter\n@Getter\npublic class UserDTO implements Serializable {\n\n @Setter\n private Long id;\n\n @Setter\n private String username;\n\n @Setter\n private String fi... | import com.premierleague.reservation.api.dtos.UserDTO;
import com.premierleague.reservation.api.exceptions.UnauthorizedException;
import com.premierleague.reservation.api.mappers.UserMapper;
import com.premierleague.reservation.api.models.User;
import com.premierleague.reservation.api.models.enums.Role;
import com.premierleague.reservation.api.repositories.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional; | 1,250 | package com.premierleague.reservation.api.service;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private UserMapper userMapper;
@Autowired
private AuthenticationService authenticationService;
| package com.premierleague.reservation.api.service;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private UserMapper userMapper;
@Autowired
private AuthenticationService authenticationService;
| public UserDTO userProfile(String username) { | 0 | 2023-12-05 18:40:40+00:00 | 2k |
h1alexbel/cdit | src/it/postgres/src/test/java/EntryTest.java | [
{
"identifier": "Env",
"path": "src/main/java/org/cdit/Env.java",
"snippet": "public final class Env implements Scalar<String> {\n\n /**\n * Name.\n */\n private final String name;\n\n /**\n * Value.\n */\n private final String value;\n\n /**\n * Ctor.\n *\n * @param nm Name\n * @p... | import org.cdit.Env;
import org.cdit.containers.Postgres;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.hamcrest.core.IsEqual;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.GenericContainer; | 861 | /*
* Copyright (c) 2023 Aliaksei Bialiauski
*
* 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 NON-INFRINGEMENT. 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.
*/
/**
* Test suite for {@link Postgres}.
*
* @since 0.0.0
*/
final class EntryTest {
@Test
void runs() {
MatcherAssert.assertThat(
"Container is not running",
new Postgres("16").run()
.isRunning(),
new IsEqual<>(true)
);
}
@Test
void checksImageName() {
MatcherAssert.assertThat(
"PostgreSQL image is not in the right format",
new Postgres("16.0-bullseye").run().getImage().get(),
new IsEqual<>("postgres:16.0-bullseye")
);
}
@Test
void stops() {
final GenericContainer<?> started = new Postgres("latest").run();
started.stop();
MatcherAssert.assertThat(
"Container is not stopped",
started.isRunning(),
new IsEqual<>(false)
);
}
@Test
void checksEnvs() {
MatcherAssert.assertThat(
"Environment Variables are not in the right format",
new Postgres(
"latest", | /*
* Copyright (c) 2023 Aliaksei Bialiauski
*
* 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 NON-INFRINGEMENT. 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.
*/
/**
* Test suite for {@link Postgres}.
*
* @since 0.0.0
*/
final class EntryTest {
@Test
void runs() {
MatcherAssert.assertThat(
"Container is not running",
new Postgres("16").run()
.isRunning(),
new IsEqual<>(true)
);
}
@Test
void checksImageName() {
MatcherAssert.assertThat(
"PostgreSQL image is not in the right format",
new Postgres("16.0-bullseye").run().getImage().get(),
new IsEqual<>("postgres:16.0-bullseye")
);
}
@Test
void stops() {
final GenericContainer<?> started = new Postgres("latest").run();
started.stop();
MatcherAssert.assertThat(
"Container is not stopped",
started.isRunning(),
new IsEqual<>(false)
);
}
@Test
void checksEnvs() {
MatcherAssert.assertThat(
"Environment Variables are not in the right format",
new Postgres(
"latest", | new Env("POSTGRES_USER", "user"), | 0 | 2023-12-06 10:29:59+00:00 | 2k |
blueokanna/ReverseCoin | src/main/java/ReverseCoinBlockChainGeneration/BlockChainConfig.java | [
{
"identifier": "ReverseCoinBlock",
"path": "src/main/java/BlockModel/ReverseCoinBlock.java",
"snippet": "public class ReverseCoinBlock implements Serializable, ReverseCoinBlockInterface {\n\n private static final long serialVersionUID = 1145141919810L;\n private byte version;\n private int ind... | import BlockModel.ReverseCoinBlock;
import BlockModel.ReverseCoinTransaction;
import org.bouncycastle.crypto.digests.SHA3Digest;
import org.bouncycastle.util.encoders.Hex;
import org.java_websocket.WebSocket;
import java.util.concurrent.CopyOnWriteArrayList;
import ConnectionAPI.ReverseCoinChainConfigInterface; | 1,593 | package ReverseCoinBlockChainGeneration;
public class BlockChainConfig implements ReverseCoinChainConfigInterface {
private volatile CopyOnWriteArrayList<ReverseCoinBlock> BlockList = new CopyOnWriteArrayList<>(); | package ReverseCoinBlockChainGeneration;
public class BlockChainConfig implements ReverseCoinChainConfigInterface {
private volatile CopyOnWriteArrayList<ReverseCoinBlock> BlockList = new CopyOnWriteArrayList<>(); | private volatile CopyOnWriteArrayList<ReverseCoinTransaction> TransactionsList = new CopyOnWriteArrayList<>(); | 1 | 2023-12-11 05:18:04+00:00 | 2k |
Patbox/PolyDecorations | src/main/java/eu/pb4/polydecorations/polydex/PolydexCompatImpl.java | [
{
"identifier": "GuiTextures",
"path": "src/main/java/eu/pb4/polydecorations/ui/GuiTextures.java",
"snippet": "public class GuiTextures {\n public static final GuiElement EMPTY = icon16(\"empty\").get().build();\n public static final Function<Text, Text> SHELF = background(\"shelf\");\n\n publi... | import eu.pb4.polydex.api.v1.recipe.*;
import eu.pb4.factorytools.api.recipe.CountedIngredient;
import eu.pb4.factorytools.api.recipe.OutputStack;
import eu.pb4.polydecorations.ui.GuiTextures;
import eu.pb4.polydecorations.ui.GuiUtils;
import eu.pb4.sgui.api.elements.GuiElement;
import net.minecraft.recipe.RecipeType;
import net.minecraft.text.Text;
import java.util.ArrayList;
import java.util.List; | 1,018 | package eu.pb4.polydecorations.polydex;
public class PolydexCompatImpl {
public static void register() {
}
public static GuiElement getButton(RecipeType<?> type) {
var category = PolydexCategory.of(type); | package eu.pb4.polydecorations.polydex;
public class PolydexCompatImpl {
public static void register() {
}
public static GuiElement getButton(RecipeType<?> type) {
var category = PolydexCategory.of(type); | return GuiTextures.POLYDEX_BUTTON.get() | 0 | 2023-12-10 16:20:36+00:00 | 2k |
i-moonlight/Suricate | src/main/java/com/michelin/suricate/controllers/AssetController.java | [
{
"identifier": "ApiErrorDto",
"path": "src/main/java/com/michelin/suricate/model/dto/api/error/ApiErrorDto.java",
"snippet": "@Data\n@NoArgsConstructor\n@EqualsAndHashCode(callSuper = false)\n@Schema(description = \"Api error response\")\npublic class ApiErrorDto extends AbstractDto {\n @Schema(desc... | import com.michelin.suricate.model.dto.api.error.ApiErrorDto;
import com.michelin.suricate.model.entities.Asset;
import com.michelin.suricate.services.api.AssetService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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.context.request.WebRequest; | 1,251 | /*
*
* * Copyright 2012-2021 the original author or authors.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package com.michelin.suricate.controllers;
/**
* Asset controller.
*/
@RestController
@RequestMapping("/api") | /*
*
* * Copyright 2012-2021 the original author or authors.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package com.michelin.suricate.controllers;
/**
* Asset controller.
*/
@RestController
@RequestMapping("/api") | @Tag(name = "Asset", description = "Asset Controller") | 1 | 2023-12-11 11:28:37+00:00 | 2k |
NaerQAQ/js4bukkit | src/main/java/org/js4bukkit/io/config/ConfigManager.java | [
{
"identifier": "Js4Bukkit",
"path": "src/main/java/org/js4bukkit/Js4Bukkit.java",
"snippet": "public class Js4Bukkit extends JavaPlugin {\n /**\n * 实例。\n */\n @Getter\n @Setter\n private static Js4Bukkit instance;\n\n /**\n * 服务器版本。\n */\n @Getter\n @Setter\n pri... | import de.leonhard.storage.Yaml;
import lombok.*;
import org.apache.commons.io.FileUtils;
import org.js4bukkit.Js4Bukkit;
import org.js4bukkit.io.file.impl.YamlManager;
import java.io.File;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile; | 1,227 | package org.js4bukkit.io.config;
/**
* 配置文件管理类。
*
* <p>
* 该类提供配置文件的创建、获取等等。
* </p>
*
* @author NaerQAQ
* @version 1.0
* @since 2023/7/29
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ConfigManager {
static {
loadConfigs("configs");
loadConfigs("plugins");
}
/**
* {@code config.yml} 配置文件实例。
*/
@Getter | package org.js4bukkit.io.config;
/**
* 配置文件管理类。
*
* <p>
* 该类提供配置文件的创建、获取等等。
* </p>
*
* @author NaerQAQ
* @version 1.0
* @since 2023/7/29
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ConfigManager {
static {
loadConfigs("configs");
loadConfigs("plugins");
}
/**
* {@code config.yml} 配置文件实例。
*/
@Getter | private static final Yaml config = YamlManager.getInstance().get( | 1 | 2023-12-14 13:50:24+00:00 | 2k |
Rainnny7/Feather | src/main/java/me/braydon/feather/database/Repository.java | [
{
"identifier": "FeatherSettings",
"path": "src/main/java/me/braydon/feather/FeatherSettings.java",
"snippet": "public final class FeatherSettings {\n /**\n * The {@link Gson} instance to use for serialization.\n */\n @Setter @Getter private static Gson gson = new GsonBuilder()\n ... | import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NonNull;
import me.braydon.feather.FeatherSettings;
import me.braydon.feather.annotation.Serializable;
import me.braydon.feather.common.FieldUtils;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
import java.util.UUID; | 1,080 | /*
* Copyright (c) 2023 Braydon (Rainnny). All rights reserved.
*
* For inquiries, please contact braydonrainnny@gmail.com
*/
package me.braydon.feather.database;
/**
* A repository belonging to a {@link IDatabase}.
*
* @author Braydon
* @param <D> the database this repository uses
* @param <ID> the identifier for type for entities
* @param <E> the entity type this repository stores
*/
@AllArgsConstructor @Getter(AccessLevel.PROTECTED)
public abstract class Repository<D extends IDatabase<?, ?>, ID, E> {
/**
* The database this repository belongs to.
*
* @see D for database
*/
@NonNull private final D database;
/**
* The class for the entity this repository uses.
*
* @see E for entity
*/
@NonNull private final Class<? extends E> entityClass;
/**
* Get the entity with the given id.
*
* @param id the entity id
* @return the entity with the id, null if none
* @see ID for id
* @see E for entity
*/
public abstract E find(@NonNull ID id);
/**
* Get all entities within this repository.
*
* @return the entities
* @see E for entity
*/
public abstract List<E> findAll();
/**
* Save the given entity to the database.
*
* @param entity the entity to save
* @see E for entity
*/
public void save(@NonNull E entity) {
saveAll(entity);
}
/**
* Save the given entities.
*
* @param entities the entities to save
* @see E for entity
*/
public abstract void saveAll(@NonNull E... entities);
/**
* Get the amount of stored entities.
*
* @return the amount of stored entities
* @see E for entity
*/
public abstract long count();
/**
* Drop the entity with the given id.
*
* @param id the entity id to drop
* @see ID for id
* @see E for entity
*/
public abstract void dropById(@NonNull ID id);
/**
* Drop the given entity.
*
* @param entity the entity to drop
* @see E for entity
*/
public abstract void drop(@NonNull E entity);
/**
* Construct a new entity from the given mapped data.
*
* @param mappedData the mapped data to parse
* @return the created entity, null if none
* @see E for entity
*/
protected final E newEntity(Map<String, ?> mappedData) {
if (mappedData == null) { // No mapped data given
return null;
}
try {
Constructor<? extends E> constructor = entityClass.getConstructor(); // Get the no args constructor
E entity = constructor.newInstance(); // Create the entity
// Get the field tagged with @Id
for (Field field : entityClass.getDeclaredFields()) { | /*
* Copyright (c) 2023 Braydon (Rainnny). All rights reserved.
*
* For inquiries, please contact braydonrainnny@gmail.com
*/
package me.braydon.feather.database;
/**
* A repository belonging to a {@link IDatabase}.
*
* @author Braydon
* @param <D> the database this repository uses
* @param <ID> the identifier for type for entities
* @param <E> the entity type this repository stores
*/
@AllArgsConstructor @Getter(AccessLevel.PROTECTED)
public abstract class Repository<D extends IDatabase<?, ?>, ID, E> {
/**
* The database this repository belongs to.
*
* @see D for database
*/
@NonNull private final D database;
/**
* The class for the entity this repository uses.
*
* @see E for entity
*/
@NonNull private final Class<? extends E> entityClass;
/**
* Get the entity with the given id.
*
* @param id the entity id
* @return the entity with the id, null if none
* @see ID for id
* @see E for entity
*/
public abstract E find(@NonNull ID id);
/**
* Get all entities within this repository.
*
* @return the entities
* @see E for entity
*/
public abstract List<E> findAll();
/**
* Save the given entity to the database.
*
* @param entity the entity to save
* @see E for entity
*/
public void save(@NonNull E entity) {
saveAll(entity);
}
/**
* Save the given entities.
*
* @param entities the entities to save
* @see E for entity
*/
public abstract void saveAll(@NonNull E... entities);
/**
* Get the amount of stored entities.
*
* @return the amount of stored entities
* @see E for entity
*/
public abstract long count();
/**
* Drop the entity with the given id.
*
* @param id the entity id to drop
* @see ID for id
* @see E for entity
*/
public abstract void dropById(@NonNull ID id);
/**
* Drop the given entity.
*
* @param entity the entity to drop
* @see E for entity
*/
public abstract void drop(@NonNull E entity);
/**
* Construct a new entity from the given mapped data.
*
* @param mappedData the mapped data to parse
* @return the created entity, null if none
* @see E for entity
*/
protected final E newEntity(Map<String, ?> mappedData) {
if (mappedData == null) { // No mapped data given
return null;
}
try {
Constructor<? extends E> constructor = entityClass.getConstructor(); // Get the no args constructor
E entity = constructor.newInstance(); // Create the entity
// Get the field tagged with @Id
for (Field field : entityClass.getDeclaredFields()) { | String key = FieldUtils.extractKey(field); // The key of the database field | 1 | 2023-12-12 04:20:32+00:00 | 2k |
xyzbtw/boze-anti-6b6t | src/main/java/com/example/addon/ExampleAddon.java | [
{
"identifier": "ExampleAddonDispatcher",
"path": "src/main/java/com/example/addon/impl/ExampleAddonDispatcher.java",
"snippet": "public class ExampleAddonDispatcher implements AddonDispatcher {\n private final CommandDispatcher<CommandSource> DISPATCHER = new CommandDispatcher<>();\n\n @Override\... | import com.example.addon.impl.ExampleAddonDispatcher;
import com.example.addon.impl.ExampleAddonModule;
import com.google.gson.JsonObject;
import dev.boze.api.BozeInstance;
import dev.boze.api.Globals;
import dev.boze.api.addon.Addon;
import dev.boze.api.addon.AddonMetadata;
import dev.boze.api.addon.AddonVersion;
import dev.boze.api.addon.command.AddonDispatcher;
import dev.boze.api.addon.module.AddonModule;
import dev.boze.api.config.Serializable;
import dev.boze.api.exception.AddonInitializationException;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.loader.impl.util.log.Log;
import net.fabricmc.loader.impl.util.log.LogCategory;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.ServerInfo;
import net.minecraft.client.option.ServerList;
import java.util.ArrayList;
import java.util.List; | 990 | package com.example.addon;
public class ExampleAddon implements ModInitializer, Addon, Serializable<ExampleAddon> {
public final AddonMetadata metadata = new AddonMetadata(
"example-addon",
"Example Addon",
"An example addon for Boze",
new AddonVersion(1, 0, 0));
private final ArrayList<AddonModule> modules = new ArrayList<>();
| package com.example.addon;
public class ExampleAddon implements ModInitializer, Addon, Serializable<ExampleAddon> {
public final AddonMetadata metadata = new AddonMetadata(
"example-addon",
"Example Addon",
"An example addon for Boze",
new AddonVersion(1, 0, 0));
private final ArrayList<AddonModule> modules = new ArrayList<>();
| private ExampleAddonDispatcher dispatcher; | 0 | 2023-12-06 21:02:03+00:00 | 2k |
litongjava/ai-server | whisper-asr/whisper-asr-service/src/main/java/com/litongjava/ai/server/single/LocalWhisper.java | [
{
"identifier": "WhisperSegment",
"path": "whisper-asr/whisper-asr-service/src/main/java/com/litongjava/ai/server/model/WhisperSegment.java",
"snippet": "public class WhisperSegment {\n private long start, end;\n private String sentence;\n\n public WhisperSegment() {\n }\n\n public WhisperSegment(l... | import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import com.litongjava.ai.server.model.WhisperSegment;
import com.litongjava.ai.server.property.WhiserAsrProperties;
import com.litongjava.ai.server.service.WhisperCppJni;
import com.litongjava.ai.server.utils.WhisperExecutorServiceUtils;
import com.litongjava.jfinal.aop.Aop;
import io.github.givimad.whisperjni.WhisperFullParams;
import io.github.givimad.whisperjni.WhisperJNI;
import lombok.extern.slf4j.Slf4j; | 1,024 | package com.litongjava.ai.server.single;
@Slf4j
public enum LocalWhisper {
INSTANCE;
private ThreadLocal<WhisperCppJni> threadLocalWhisper;
private WhisperFullParams defaultPararams = new WhisperFullParams();
LocalWhisper() {
try {
WhisperJNI.loadLibrary();
} catch (IOException e1) {
e1.printStackTrace();
}
// C:\Users\Administrator\.cache\whisper
String userHome = System.getProperty("user.home");
String modelName = Aop.get(WhiserAsrProperties.class).getModelName();
Path path = Paths.get(userHome, ".cache", "whisper", modelName);
threadLocalWhisper = ThreadLocal.withInitial(() -> {
WhisperCppJni whisper = new WhisperCppJni();
try {
whisper.initContext(path);
} catch (IOException e) {
e.printStackTrace();
}
return whisper;
});
defaultPararams.printProgress = false;
}
| package com.litongjava.ai.server.single;
@Slf4j
public enum LocalWhisper {
INSTANCE;
private ThreadLocal<WhisperCppJni> threadLocalWhisper;
private WhisperFullParams defaultPararams = new WhisperFullParams();
LocalWhisper() {
try {
WhisperJNI.loadLibrary();
} catch (IOException e1) {
e1.printStackTrace();
}
// C:\Users\Administrator\.cache\whisper
String userHome = System.getProperty("user.home");
String modelName = Aop.get(WhiserAsrProperties.class).getModelName();
Path path = Paths.get(userHome, ".cache", "whisper", modelName);
threadLocalWhisper = ThreadLocal.withInitial(() -> {
WhisperCppJni whisper = new WhisperCppJni();
try {
whisper.initContext(path);
} catch (IOException e) {
e.printStackTrace();
}
return whisper;
});
defaultPararams.printProgress = false;
}
| public List<WhisperSegment> fullTranscribeWithTime(float[] audioData, int numSamples, WhisperFullParams params) { | 0 | 2023-12-13 15:12:36+00:00 | 2k |
i-moonlight/Beluga | server/src/main/java/com/amnesica/belugaproject/services/data/RangeDataService.java | [
{
"identifier": "StaticValues",
"path": "server/src/main/java/com/amnesica/belugaproject/config/StaticValues.java",
"snippet": "public class StaticValues {\n // Lokale Feeder - Scheduler\n public static final int INTERVAL_UPDATE_LOCAL_FEEDER = 2000; // 2 Sekunden\n public static final int INTER... | import com.amnesica.belugaproject.config.StaticValues;
import com.amnesica.belugaproject.entities.aircraft.Aircraft;
import com.amnesica.belugaproject.entities.data.RangeData;
import com.amnesica.belugaproject.repositories.data.RangeDataRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.text.DateFormat;
import java.util.Date;
import java.util.List; | 1,244 | package com.amnesica.belugaproject.services.data;
@Slf4j
@Service
public class RangeDataService {
@Autowired
private RangeDataRepository rangeDataRepository;
/**
* Gibt eine Liste mit Range-Data, Start- und Endpunkt von Flugzeugen,
* welche in dem Zeitslot empfangen wurden
*
* @param startTime long
* @param endTime long
* @return List<RangeData>
*/ | package com.amnesica.belugaproject.services.data;
@Slf4j
@Service
public class RangeDataService {
@Autowired
private RangeDataRepository rangeDataRepository;
/**
* Gibt eine Liste mit Range-Data, Start- und Endpunkt von Flugzeugen,
* welche in dem Zeitslot empfangen wurden
*
* @param startTime long
* @param endTime long
* @return List<RangeData>
*/ | public List<RangeData> getRangeDataBetweenTimestamps(long startTime, long endTime) { | 2 | 2023-12-11 11:37:46+00:00 | 2k |
fiber-net-gateway/fiber-net-gateway | fiber-gateway-common/src/main/java/io/fiber/net/common/async/internal/MappedSingle.java | [
{
"identifier": "Disposable",
"path": "fiber-gateway-common/src/main/java/io/fiber/net/common/async/Disposable.java",
"snippet": "public interface Disposable {\n boolean isDisposed();\n\n boolean dispose();\n}"
},
{
"identifier": "Function",
"path": "fiber-gateway-common/src/main/java/... | import io.fiber.net.common.async.Disposable;
import io.fiber.net.common.async.Function;
import io.fiber.net.common.async.Scheduler;
import io.fiber.net.common.async.Single; | 1,108 | package io.fiber.net.common.async.internal;
public class MappedSingle<T, U> implements Single<U> {
private final Function<? super T, ? extends U> map;
private final Single<T> source;
public MappedSingle(Function<? super T, ? extends U> fc, Single<T> source) {
this.map = fc;
this.source = source;
}
@Override
public void subscribe(Observer<? super U> observer) {
source.subscribe(new MapOb<>(map, observer));
}
private static class MapOb<T, U> implements Observer<T> {
private final Function<? super T, ? extends U> map;
private final Observer<? super U> c;
private MapOb(Function<T, U> map, Observer<? super U> c) {
this.map = map;
this.c = c;
}
@Override | package io.fiber.net.common.async.internal;
public class MappedSingle<T, U> implements Single<U> {
private final Function<? super T, ? extends U> map;
private final Single<T> source;
public MappedSingle(Function<? super T, ? extends U> fc, Single<T> source) {
this.map = fc;
this.source = source;
}
@Override
public void subscribe(Observer<? super U> observer) {
source.subscribe(new MapOb<>(map, observer));
}
private static class MapOb<T, U> implements Observer<T> {
private final Function<? super T, ? extends U> map;
private final Observer<? super U> c;
private MapOb(Function<T, U> map, Observer<? super U> c) {
this.map = map;
this.c = c;
}
@Override | public void onSubscribe(Disposable d) { | 0 | 2023-12-08 15:18:05+00:00 | 2k |
i-moonlight/IPFS_Gateway_Checker | ipfs-status-service/src/main/java/com/fooock/ipfs/status/task/GatewayCheckWritableTask.java | [
{
"identifier": "Gateway",
"path": "ipfs-status-service/src/main/java/com/fooock/ipfs/status/model/Gateway.java",
"snippet": "@Data\n@RequiredArgsConstructor\n@EqualsAndHashCode(doNotUseGetters = true, exclude = {\"startTime\", \"latency\", \"lastUpdate\"})\npublic class Gateway {\n public static fin... | import com.fooock.ipfs.status.model.Gateway;
import com.fooock.ipfs.status.model.Report;
import com.fooock.ipfs.status.repository.ReportMemoryRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import java.util.List; | 965 | package com.fooock.ipfs.status.task;
/**
* Check if the public gateway has public writable access
*/
@Configuration
@EnableScheduling
@Slf4j
public class GatewayCheckWritableTask {
private final static long THREE_HOURS = 60 * 60 * 1000 * 3;
private final static long ONE_MINUTE = 60000;
private final ReportMemoryRepository reportMemoryRepository;
private final WebClient webClient;
public GatewayCheckWritableTask(ReportMemoryRepository reportMemoryRepository, WebClient webClient) {
this.reportMemoryRepository = reportMemoryRepository;
this.webClient = webClient;
}
/**
* Execute check every three hours and save result to repository.
*/
@Scheduled(fixedRate = THREE_HOURS, initialDelay = ONE_MINUTE)
public void checkWritable() {
log.debug("Prepared to check writable nodes...");
List<Report> online = reportMemoryRepository.findOnline();
if (online.isEmpty()) {
log.warn("No online gateways...");
return;
}
log.info("Check writable state of {} gateways...", online.size());
online.forEach(gateway -> {
Mono<ClientResponse> clientResponse = webClient.post()
.uri(buildPostUrl(gateway.getName()))
.exchange();
clientResponse.subscribe(s -> checkGatewayResponse(gateway, s), | package com.fooock.ipfs.status.task;
/**
* Check if the public gateway has public writable access
*/
@Configuration
@EnableScheduling
@Slf4j
public class GatewayCheckWritableTask {
private final static long THREE_HOURS = 60 * 60 * 1000 * 3;
private final static long ONE_MINUTE = 60000;
private final ReportMemoryRepository reportMemoryRepository;
private final WebClient webClient;
public GatewayCheckWritableTask(ReportMemoryRepository reportMemoryRepository, WebClient webClient) {
this.reportMemoryRepository = reportMemoryRepository;
this.webClient = webClient;
}
/**
* Execute check every three hours and save result to repository.
*/
@Scheduled(fixedRate = THREE_HOURS, initialDelay = ONE_MINUTE)
public void checkWritable() {
log.debug("Prepared to check writable nodes...");
List<Report> online = reportMemoryRepository.findOnline();
if (online.isEmpty()) {
log.warn("No online gateways...");
return;
}
log.info("Check writable state of {} gateways...", online.size());
online.forEach(gateway -> {
Mono<ClientResponse> clientResponse = webClient.post()
.uri(buildPostUrl(gateway.getName()))
.exchange();
clientResponse.subscribe(s -> checkGatewayResponse(gateway, s), | throwable -> updateWritableState(gateway, Gateway.GATEWAY_NO_WRITABLE)); | 0 | 2023-12-11 10:11:41+00:00 | 2k |
sigbla/sigbla-pds | src/main/java/sigbla/app/pds/collection/internal/adapter/Adapters.java | [
{
"identifier": "Function",
"path": "src/main/java/sigbla/app/pds/collection/Function.java",
"snippet": "public interface Function<P, R> {\n R invoke(P parameter);\n}"
},
{
"identifier": "Traversable",
"path": "src/main/java/sigbla/app/pds/collection/Traversable.java",
"snippet": "pub... | import sigbla.app.pds.collection.Function;
import sigbla.app.pds.collection.Traversable;
import sigbla.app.pds.collection.internal.base.Break;
import org.jetbrains.annotations.NotNull;
import java.util.Collection; | 1,055 | /*
* Copyright (c) 2014 Andrew O'Malley
*
* 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 sigbla.app.pds.collection.internal.adapter;
/**
*
*/
public class Adapters {
public static <E> boolean containsAll(@NotNull Traversable<E> traversable, @NotNull Collection<?> c) {
for (Object e : c) {
if (!contains(traversable, e)) {
return false;
}
}
return true;
}
@SuppressWarnings("unchecked")
public static <E> boolean contains(@NotNull Traversable<E> traversable, final Object o) {
try { | /*
* Copyright (c) 2014 Andrew O'Malley
*
* 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 sigbla.app.pds.collection.internal.adapter;
/**
*
*/
public class Adapters {
public static <E> boolean containsAll(@NotNull Traversable<E> traversable, @NotNull Collection<?> c) {
for (Object e : c) {
if (!contains(traversable, e)) {
return false;
}
}
return true;
}
@SuppressWarnings("unchecked")
public static <E> boolean contains(@NotNull Traversable<E> traversable, final Object o) {
try { | traversable.forEach(new Function<E, Object>() { | 0 | 2023-12-10 15:10:13+00:00 | 2k |
AdanJoGoHe/sunandbeach | src/main/java/com/serex/beachandsun/items/HoneyRumItem.java | [
{
"identifier": "ItemInit",
"path": "src/main/java/com/serex/beachandsun/ItemInit.java",
"snippet": "public class ItemInit {\n public static final Item TROPICAL_CAN = registerItem(\"tropical\", new TropicalCanItem(new FabricItemSettings()));\n public static final Item EMPTY_TROPICAL_CAN = registerItem... | import com.serex.beachandsun.ItemInit;
import com.serex.beachandsun.sound.ModSounds;
import java.util.List;
import net.minecraft.advancement.criterion.Criteria;
import net.minecraft.client.item.TooltipContext;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.effect.StatusEffectInstance;
import net.minecraft.entity.effect.StatusEffects;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUsage;
import net.minecraft.potion.PotionUtil;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.stat.Stats;
import net.minecraft.text.Text;
import net.minecraft.util.Hand;
import net.minecraft.util.TypedActionResult;
import net.minecraft.util.UseAction;
import net.minecraft.world.World;
import net.minecraft.world.event.GameEvent;
import org.jetbrains.annotations.Nullable; | 1,444 | package com.serex.beachandsun.items;
public class HoneyRumItem extends Item {
public HoneyRumItem(Settings settings) {
super(settings);
}
public TypedActionResult<ItemStack> use(World world, PlayerEntity user, Hand hand) {
return ItemUsage.consumeHeldItem(world, user, hand);
}
@Override
public UseAction getUseAction(ItemStack stack) {
return UseAction.DRINK;
}
@Override
public int getMaxUseTime(ItemStack stack) {
return 32;
}
@Override
public ItemStack finishUsing(ItemStack stack, World world, LivingEntity user) {
PlayerEntity playerEntity;
PlayerEntity playerEntity2 = playerEntity = user instanceof PlayerEntity ? (PlayerEntity)user : null;
if (playerEntity instanceof ServerPlayerEntity) {
Criteria.CONSUME_ITEM.trigger((ServerPlayerEntity)playerEntity, stack);
}
if (!world.isClient) {
List<StatusEffectInstance> list = PotionUtil.getPotionEffects(stack);
for (StatusEffectInstance statusEffectInstance : list) {
if (statusEffectInstance.getEffectType().isInstant()) {
statusEffectInstance.getEffectType().applyInstantEffect(playerEntity, playerEntity, user, statusEffectInstance.getAmplifier(), 1.0);
continue;
}
user.addStatusEffect(new StatusEffectInstance(statusEffectInstance));
}
}
if (playerEntity == null || !playerEntity.getAbilities().creativeMode) { | package com.serex.beachandsun.items;
public class HoneyRumItem extends Item {
public HoneyRumItem(Settings settings) {
super(settings);
}
public TypedActionResult<ItemStack> use(World world, PlayerEntity user, Hand hand) {
return ItemUsage.consumeHeldItem(world, user, hand);
}
@Override
public UseAction getUseAction(ItemStack stack) {
return UseAction.DRINK;
}
@Override
public int getMaxUseTime(ItemStack stack) {
return 32;
}
@Override
public ItemStack finishUsing(ItemStack stack, World world, LivingEntity user) {
PlayerEntity playerEntity;
PlayerEntity playerEntity2 = playerEntity = user instanceof PlayerEntity ? (PlayerEntity)user : null;
if (playerEntity instanceof ServerPlayerEntity) {
Criteria.CONSUME_ITEM.trigger((ServerPlayerEntity)playerEntity, stack);
}
if (!world.isClient) {
List<StatusEffectInstance> list = PotionUtil.getPotionEffects(stack);
for (StatusEffectInstance statusEffectInstance : list) {
if (statusEffectInstance.getEffectType().isInstant()) {
statusEffectInstance.getEffectType().applyInstantEffect(playerEntity, playerEntity, user, statusEffectInstance.getAmplifier(), 1.0);
continue;
}
user.addStatusEffect(new StatusEffectInstance(statusEffectInstance));
}
}
if (playerEntity == null || !playerEntity.getAbilities().creativeMode) { | playerEntity.playSound(ModSounds.QUICK_REVIVE_SOUND,100,1); | 1 | 2023-12-06 10:53:54+00:00 | 2k |
netty/netty-incubator-codec-ohttp | codec-ohttp/src/main/java/io/netty/incubator/codec/ohttp/OHttpServerPublicKeys.java | [
{
"identifier": "CryptoException",
"path": "codec-ohttp-hpke/src/main/java/io/netty/incubator/codec/hpke/CryptoException.java",
"snippet": "public final class CryptoException extends Exception {\n\n public CryptoException(String message) {\n super(message);\n }\n\n public CryptoException... | import io.netty.incubator.codec.hpke.KDF;
import io.netty.incubator.codec.hpke.KEM;
import static java.util.Objects.requireNonNull;
import io.netty.incubator.codec.hpke.CryptoException;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import io.netty.incubator.codec.hpke.AEAD; | 1,535 | /*
* Copyright 2023 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.incubator.codec.ohttp;
/**
* Set of server public keys and cipher suites for a OHTTP client.
*/
public final class OHttpServerPublicKeys implements Iterable<Map.Entry<Byte, OHttpKey.PublicKey>> {
private final Map<Byte, OHttpKey.PublicKey> keys;
public OHttpServerPublicKeys(Map<Byte, OHttpKey.PublicKey> keys) {
this.keys = Collections.unmodifiableMap(requireNonNull(keys, "keys"));
}
/**
* Return all {@link OHttpKey.PublicKey}s.
*
* @return keys.
*/
public Collection<OHttpKey.PublicKey> keys() {
return keys.values();
}
/**
* Return the {@link OHttpKey.PublicKey} for the given id or {@code null} if there is no key for the id.
*
* @param keyId the id of the key.
* @return key the key.
*/
public OHttpKey.PublicKey key(byte keyId) {
return keys.get(keyId);
}
@Override
public Iterator<Map.Entry<Byte, OHttpKey.PublicKey>> iterator() {
return keys.entrySet().iterator();
}
@Override
public String toString() {
return keys.values()
.stream()
.map(k -> "{ciphers=" +
k.ciphersuites().stream()
.map(OHttpCiphersuite::toString)
.collect(Collectors.joining(", ", "[", "]")) +
", publicKey=" + ByteBufUtil.hexDump(k.pkEncoded()) + "}")
.collect(Collectors.joining(", ", "[", "]"));
}
/*
* Decode a serialized {@link ServerPublicKeys} on the client.
*/ | /*
* Copyright 2023 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.incubator.codec.ohttp;
/**
* Set of server public keys and cipher suites for a OHTTP client.
*/
public final class OHttpServerPublicKeys implements Iterable<Map.Entry<Byte, OHttpKey.PublicKey>> {
private final Map<Byte, OHttpKey.PublicKey> keys;
public OHttpServerPublicKeys(Map<Byte, OHttpKey.PublicKey> keys) {
this.keys = Collections.unmodifiableMap(requireNonNull(keys, "keys"));
}
/**
* Return all {@link OHttpKey.PublicKey}s.
*
* @return keys.
*/
public Collection<OHttpKey.PublicKey> keys() {
return keys.values();
}
/**
* Return the {@link OHttpKey.PublicKey} for the given id or {@code null} if there is no key for the id.
*
* @param keyId the id of the key.
* @return key the key.
*/
public OHttpKey.PublicKey key(byte keyId) {
return keys.get(keyId);
}
@Override
public Iterator<Map.Entry<Byte, OHttpKey.PublicKey>> iterator() {
return keys.entrySet().iterator();
}
@Override
public String toString() {
return keys.values()
.stream()
.map(k -> "{ciphers=" +
k.ciphersuites().stream()
.map(OHttpCiphersuite::toString)
.collect(Collectors.joining(", ", "[", "]")) +
", publicKey=" + ByteBufUtil.hexDump(k.pkEncoded()) + "}")
.collect(Collectors.joining(", ", "[", "]"));
}
/*
* Decode a serialized {@link ServerPublicKeys} on the client.
*/ | public static OHttpServerPublicKeys decode(ByteBuf input) throws CryptoException { | 0 | 2023-12-06 09:14:09+00:00 | 2k |
xia0ne/NotificationTools | src/main/java/com/example/notificationtools/controller/RedisController.java | [
{
"identifier": "RedisServiceImpl",
"path": "src/main/java/com/example/notificationtools/service/impl/RedisServiceImpl.java",
"snippet": "@Service\n@Log\npublic class RedisServiceImpl implements RedisService {\n\t@Resource\n\tprivate RedisTemplate<String, Object> redisTemplate;\n\n\t/*\n\t-1 custom\n\t0... | import com.example.notificationtools.service.impl.RedisServiceImpl;
import com.example.notificationtools.utils.ResponseResult;
import jakarta.annotation.Resource;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List; | 902 | package com.example.notificationtools.controller;
@RestController
@RequestMapping("/logs")
@Log
public class RedisController {
@Resource | package com.example.notificationtools.controller;
@RestController
@RequestMapping("/logs")
@Log
public class RedisController {
@Resource | RedisServiceImpl redisService; | 0 | 2023-12-05 06:46:58+00:00 | 2k |
Ender-Cube/Endercube | Parkour/src/main/java/net/endercube/Parkour/listeners/MinigamePlayerJoin.java | [
{
"identifier": "MinigamePlayerJoinEvent",
"path": "Common/src/main/java/net/endercube/Common/events/MinigamePlayerJoinEvent.java",
"snippet": "public class MinigamePlayerJoinEvent implements PlayerMinigameEvent {\n\n private final String minigame;\n private final EndercubePlayer player;\n priv... | import net.endercube.Common.events.MinigamePlayerJoinEvent;
import net.endercube.Common.players.EndercubePlayer;
import net.endercube.Parkour.InventoryItems;
import net.minestom.server.MinecraftServer;
import net.minestom.server.event.EventListener;
import net.minestom.server.instance.InstanceContainer;
import net.minestom.server.tag.Tag;
import org.jetbrains.annotations.NotNull;
import static net.endercube.Common.EndercubeMinigame.logger;
import static net.endercube.Parkour.ParkourMinigame.database;
import static net.endercube.Parkour.ParkourMinigame.parkourMinigame; | 1,502 | package net.endercube.Parkour.listeners;
public class MinigamePlayerJoin implements EventListener<MinigamePlayerJoinEvent> {
@Override
public @NotNull Class<MinigamePlayerJoinEvent> eventType() {
return MinigamePlayerJoinEvent.class;
}
@Override
public @NotNull Result run(@NotNull MinigamePlayerJoinEvent event) { | package net.endercube.Parkour.listeners;
public class MinigamePlayerJoin implements EventListener<MinigamePlayerJoinEvent> {
@Override
public @NotNull Class<MinigamePlayerJoinEvent> eventType() {
return MinigamePlayerJoinEvent.class;
}
@Override
public @NotNull Result run(@NotNull MinigamePlayerJoinEvent event) { | EndercubePlayer player = event.getPlayer(); | 1 | 2023-12-10 12:08:18+00:00 | 2k |
lukebemishprojects/Tempest | common/src/main/java/dev/lukebemish/tempest/impl/mixin/LevelMixin.java | [
{
"identifier": "Services",
"path": "common/src/main/java/dev/lukebemish/tempest/impl/Services.java",
"snippet": "public final class Services {\n private Services() {}\n\n public static final Platform PLATFORM = load(Platform.class);\n\n private static final List<Snower> SNOWERS;\n private s... | import dev.lukebemish.tempest.impl.Services;
import dev.lukebemish.tempest.impl.data.WeatherCategory;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Level;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; | 1,417 | package dev.lukebemish.tempest.impl.mixin;
@Mixin(Level.class)
public class LevelMixin {
@Inject(
method = "isRainingAt(Lnet/minecraft/core/BlockPos;)Z",
at = @At("HEAD"),
cancellable = true
)
private void tempest$isRainingAt(BlockPos pos, CallbackInfoReturnable<Boolean> cir) {
//noinspection DataFlowIssue
var level = (Level) (Object) this; | package dev.lukebemish.tempest.impl.mixin;
@Mixin(Level.class)
public class LevelMixin {
@Inject(
method = "isRainingAt(Lnet/minecraft/core/BlockPos;)Z",
at = @At("HEAD"),
cancellable = true
)
private void tempest$isRainingAt(BlockPos pos, CallbackInfoReturnable<Boolean> cir) {
//noinspection DataFlowIssue
var level = (Level) (Object) this; | var data = Services.PLATFORM.getChunkData(level.getChunkAt(pos)); | 0 | 2023-12-06 23:23:31+00:00 | 2k |
aws-samples/codecatalyst-java-workflow-sample | src/main/java/com/example/calculator/restcalculator/rest/SumController.java | [
{
"identifier": "ResultDto",
"path": "src/main/java/com/example/calculator/restcalculator/dto/ResultDto.java",
"snippet": "public class ResultDto {\n\n private String result;\n\n public String getResult() {\n return result;\n }\n\n public void setResult(String result) {\n this.... | import com.example.calculator.restcalculator.dto.ResultDto;
import com.example.calculator.restcalculator.dto.SumDto;
import com.example.calculator.restcalculator.service.Calculator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController; | 756 | package com.example.calculator.restcalculator.rest;
@RestController
public class SumController {
@Autowired | package com.example.calculator.restcalculator.rest;
@RestController
public class SumController {
@Autowired | private Calculator calculator; | 2 | 2023-12-14 10:24:15+00:00 | 2k |
RennanMendes/healthnove-backend | src/test/java/com/healthnove/schedulingHealthNove/domain/service/DoctorServiceTest.java | [
{
"identifier": "Gender",
"path": "src/main/java/com/healthnove/schedulingHealthNove/domain/enumerated/Gender.java",
"snippet": "public enum Gender {\n MALE, FEMALE\n}"
},
{
"identifier": "Speciality",
"path": "src/main/java/com/healthnove/schedulingHealthNove/domain/enumerated/Speciality... | import com.healthnove.schedulingHealthNove.domain.dto.doctor.DoctorRequestDto;
import com.healthnove.schedulingHealthNove.domain.dto.doctor.DoctorResponseDto;
import com.healthnove.schedulingHealthNove.domain.dto.doctor.DoctorUpdateDto;
import com.healthnove.schedulingHealthNove.domain.enumerated.Gender;
import com.healthnove.schedulingHealthNove.domain.enumerated.Speciality;
import com.healthnove.schedulingHealthNove.domain.enumerated.UserType;
import com.healthnove.schedulingHealthNove.domain.exception.DoctorAlreadyRegisteredException;
import com.healthnove.schedulingHealthNove.domain.exception.DoctorNotFoundException;
import com.healthnove.schedulingHealthNove.domain.model.Doctor;
import com.healthnove.schedulingHealthNove.domain.model.User;
import com.healthnove.schedulingHealthNove.domain.repository.DoctorRepository;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import static org.mockito.ArgumentMatchers.any;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.when; | 1,546 | package com.healthnove.schedulingHealthNove.domain.service;
@SpringBootTest
class DoctorServiceTest {
private static final Long ID = 1L;
@InjectMocks
private DoctorService doctorService;
@Mock | package com.healthnove.schedulingHealthNove.domain.service;
@SpringBootTest
class DoctorServiceTest {
private static final Long ID = 1L;
@InjectMocks
private DoctorService doctorService;
@Mock | private DoctorRepository repository; | 7 | 2023-12-14 21:54:29+00:00 | 2k |
xhtcode/xht-cloud-parent | xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/poetry/service/ISysDictPoetryService.java | [
{
"identifier": "PageResponse",
"path": "xht-cloud-framework/xht-cloud-framework-core/src/main/java/com/xht/cloud/framework/core/api/response/PageResponse.java",
"snippet": "@Data\n@Schema(description = \"分页信息响应实体\")\npublic class PageResponse<T> extends Response {\n\n /**\n * 当前页\n */\n @... | import com.xht.cloud.framework.core.api.response.PageResponse;
import com.xht.cloud.system.module.poetry.controller.request.SysDictPoetryAddRequest;
import com.xht.cloud.system.module.poetry.controller.request.SysDictPoetryQueryRequest;
import com.xht.cloud.system.module.poetry.controller.request.SysDictPoetryUpdateRequest;
import com.xht.cloud.system.module.poetry.controller.response.SysDictPoetryResponse;
import java.util.List; | 1,228 | package com.xht.cloud.system.module.poetry.service;
/**
* 描述 :
*
* @author : xht
**/
public interface ISysDictPoetryService{
/**
* 创建
*
* @param addRequest {@link SysDictPoetryAddRequest}
* @return {@link String} 主键
*/
String create(SysDictPoetryAddRequest addRequest);
/**
* 根据id修改
*
* @param updateRequest {@link SysDictPoetryUpdateRequest}
*/
void update(SysDictPoetryUpdateRequest updateRequest);
/**
* 删除
*
* @param ids {@link List<String>} id集合
*/
void remove(List<String> ids);
/**
* 根据id查询详细
*
* @param id {@link String} 数据库主键
* @return {@link SysDictPoetryResponse}
*/ | package com.xht.cloud.system.module.poetry.service;
/**
* 描述 :
*
* @author : xht
**/
public interface ISysDictPoetryService{
/**
* 创建
*
* @param addRequest {@link SysDictPoetryAddRequest}
* @return {@link String} 主键
*/
String create(SysDictPoetryAddRequest addRequest);
/**
* 根据id修改
*
* @param updateRequest {@link SysDictPoetryUpdateRequest}
*/
void update(SysDictPoetryUpdateRequest updateRequest);
/**
* 删除
*
* @param ids {@link List<String>} id集合
*/
void remove(List<String> ids);
/**
* 根据id查询详细
*
* @param id {@link String} 数据库主键
* @return {@link SysDictPoetryResponse}
*/ | SysDictPoetryResponse findById(String id); | 4 | 2023-12-12 08:16:30+00:00 | 2k |
Utils4J/JavaUtils | src/test/java/CustomTableTest.java | [
{
"identifier": "CustomTable",
"path": "src/test/java/data/CustomTable.java",
"snippet": "public interface CustomTable extends Table<TestClass> {\n\t@NotNull\n\t@Override\n\tCustomTable createTable();\n\n\tdefault List<TestClass> select2() {\n\t\treturn selectAll(Order.empty().limit(2));\n\t}\n}"
},
... | import data.CustomTable;
import data.TestClass;
import de.mineking.javautils.database.DatabaseManager;
import org.junit.jupiter.api.Test; | 1,573 |
public class CustomTableTest {
public final DatabaseManager manager;
public final CustomTable table;
public CustomTableTest() {
manager = new DatabaseManager("jdbc:postgresql://localhost:5433/test", "postgres", "test123"); |
public class CustomTableTest {
public final DatabaseManager manager;
public final CustomTable table;
public CustomTableTest() {
manager = new DatabaseManager("jdbc:postgresql://localhost:5433/test", "postgres", "test123"); | table = manager.getTable(CustomTable.class, TestClass.class, this::createInstance, "test").createTable(); | 1 | 2023-12-13 14:05:17+00:00 | 2k |
serendipitk/LunarCore | src/main/java/emu/lunarcore/data/excel/RelicSubAffixExcel.java | [
{
"identifier": "GameDepot",
"path": "src/main/java/emu/lunarcore/data/GameDepot.java",
"snippet": "public class GameDepot {\n // Exp\n @Getter private static List<AvatarExpItemExcel> avatarExpExcels = new ArrayList<>();\n @Getter private static List<EquipmentExpItemExcel> equipmentExpExcels = ... | import emu.lunarcore.data.GameDepot;
import emu.lunarcore.data.GameResource;
import emu.lunarcore.data.ResourceType;
import emu.lunarcore.data.ResourceType.LoadPriority;
import emu.lunarcore.game.enums.AvatarPropertyType;
import lombok.Getter; | 1,508 | package emu.lunarcore.data.excel;
@Getter
@ResourceType(name = {"RelicSubAffixConfig.json"}, loadPriority = LoadPriority.NORMAL)
public class RelicSubAffixExcel extends GameResource {
private int GroupID;
private int AffixID; | package emu.lunarcore.data.excel;
@Getter
@ResourceType(name = {"RelicSubAffixConfig.json"}, loadPriority = LoadPriority.NORMAL)
public class RelicSubAffixExcel extends GameResource {
private int GroupID;
private int AffixID; | private AvatarPropertyType Property; | 2 | 2023-12-08 14:13:04+00:00 | 2k |
adabox-aio/dextreme-sdk | src/main/java/io/adabox/dextreme/dex/api/SpectrumApi.java | [
{
"identifier": "Api",
"path": "src/main/java/io/adabox/dextreme/dex/api/base/Api.java",
"snippet": "@Getter\npublic abstract class Api {\n\n private final HttpClient client = HttpClient.newHttpClient();\n private final ObjectMapper objectMapper = new ObjectMapper();\n private final DexType dex... | import com.bloxbean.cardano.client.util.HexUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.NullNode;
import io.adabox.dextreme.dex.api.base.Api;
import io.adabox.dextreme.dex.base.DexType;
import io.adabox.dextreme.model.Asset;
import io.adabox.dextreme.model.LiquidityPool;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URI;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static com.bloxbean.cardano.client.common.CardanoConstants.LOVELACE; | 1,414 | package io.adabox.dextreme.dex.api;
/**
* Spectrum API Class
*/
@Slf4j
@Getter
public class SpectrumApi extends Api {
private static final String BASE_URL = "https://analytics.spectrum.fi";
public SpectrumApi() { | package io.adabox.dextreme.dex.api;
/**
* Spectrum API Class
*/
@Slf4j
@Getter
public class SpectrumApi extends Api {
private static final String BASE_URL = "https://analytics.spectrum.fi";
public SpectrumApi() { | super(DexType.Spectrum); | 1 | 2023-12-10 12:14:48+00:00 | 2k |
lucas0headshot/ODS-Agro-ADS2-BackEnd | agro/src/main/java/com/ods/agro/controller/VendaController.java | [
{
"identifier": "Venda",
"path": "agro/src/main/java/com/ods/agro/entities/Venda.java",
"snippet": "@Entity(name = \"venda\")\n@Getter\n@Setter\npublic class Venda extends EntityID{\n\n @ManyToOne\n @JoinColumn(name = \"cliente_id\", referencedColumnName = \"id\", nullable = false)\n private Cl... | import com.ods.agro.entities.Venda;
import com.ods.agro.services.VendaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.net.URI;
import java.util.List; | 693 | package com.ods.agro.controller;
@RestController
@RequestMapping("/api/vendas")
public class VendaController extends AbstractController{
@Autowired | package com.ods.agro.controller;
@RestController
@RequestMapping("/api/vendas")
public class VendaController extends AbstractController{
@Autowired | VendaService service; | 1 | 2023-12-05 22:16:35+00:00 | 2k |
zhaw-iwi/promise | src/main/java/ch/zhaw/statefulconversation/controllers/AgentController.java | [
{
"identifier": "Agent",
"path": "src/main/java/ch/zhaw/statefulconversation/model/Agent.java",
"snippet": "@Entity\npublic class Agent {\n\n // @TODO: maybe have an attribute or getter method is active?\n\n @Id\n @GeneratedValue\n private UUID id;\n\n public UUID getId() {\n retur... | import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ch.zhaw.statefulconversation.model.Agent;
import ch.zhaw.statefulconversation.model.Utterance;
import ch.zhaw.statefulconversation.repositories.AgentRepository;
import ch.zhaw.statefulconversation.views.AgentInfoView;
import ch.zhaw.statefulconversation.views.ResponseView; | 1,403 | package ch.zhaw.statefulconversation.controllers;
@RestController
public class AgentController {
@Autowired | package ch.zhaw.statefulconversation.controllers;
@RestController
public class AgentController {
@Autowired | private AgentRepository repository; | 2 | 2023-12-06 09:36:58+00:00 | 2k |
SkyDynamic/QuickBackupM-Fabric | src/main/java/dev/skydynamic/quickbackupmulti/mixin/MinecraftServer_ClientMixin.java | [
{
"identifier": "Config",
"path": "src/main/java/dev/skydynamic/quickbackupmulti/utils/config/Config.java",
"snippet": "public class Config {\n public static QuickBackupMultiConfig INSTANCE = new QuickBackupMultiConfig();\n public static QbmTempConfig TEMP_CONFIG = new QbmTempConfig();\n}"
},
... | import dev.skydynamic.quickbackupmulti.utils.config.Config;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.server.MinecraftServer;
import org.quartz.SchedulerException;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.nio.file.Path;
import static dev.skydynamic.quickbackupmulti.QuickBackupMulti.LOGGER;
import static dev.skydynamic.quickbackupmulti.utils.QbmManager.createBackupDir;
import static dev.skydynamic.quickbackupmulti.utils.schedule.CronUtil.buildScheduler; | 647 | package dev.skydynamic.quickbackupmulti.mixin;
@Environment(EnvType.CLIENT)
@Mixin(MinecraftServer.class)
public class MinecraftServer_ClientMixin {
@Inject(method = "loadWorld", at = @At("RETURN"))
private void initQuickBackupMultiClient(CallbackInfo ci) {
MinecraftServer server = (MinecraftServer) (Object) this;
Config.TEMP_CONFIG.setServerValue(server);
String worldName = server.getSaveProperties().getLevelName();
Config.TEMP_CONFIG.setWorldName(worldName);
Path backupDir = Path.of(System.getProperty("user.dir") + "/QuickBackupMulti/").resolve(worldName); | package dev.skydynamic.quickbackupmulti.mixin;
@Environment(EnvType.CLIENT)
@Mixin(MinecraftServer.class)
public class MinecraftServer_ClientMixin {
@Inject(method = "loadWorld", at = @At("RETURN"))
private void initQuickBackupMultiClient(CallbackInfo ci) {
MinecraftServer server = (MinecraftServer) (Object) this;
Config.TEMP_CONFIG.setServerValue(server);
String worldName = server.getSaveProperties().getLevelName();
Config.TEMP_CONFIG.setWorldName(worldName);
Path backupDir = Path.of(System.getProperty("user.dir") + "/QuickBackupMulti/").resolve(worldName); | createBackupDir(backupDir); | 2 | 2023-12-09 13:51:17+00:00 | 2k |
quentin452/Garden-Stuff-Continuation | src/main/resources/com/jaquadro/minecraft/gardencore/item/ItemCompost.java | [
{
"identifier": "GardenCore",
"path": "src/main/java/com/jaquadro/minecraft/gardencore/GardenCore.java",
"snippet": "@Mod(modid = \"GardenCore\", name = \"Garden Core\", version = \"1.7.10-1.7.0\")\npublic class GardenCore {\n\n public static final String MOD_ID = \"GardenCore\";\n public static f... | import com.jaquadro.minecraft.gardencore.GardenCore;
import com.jaquadro.minecraft.gardencore.api.event.EnrichedSoilEvent;
import com.jaquadro.minecraft.gardencore.config.ConfigManager;
import com.jaquadro.minecraft.gardencore.core.ModCreativeTabs;
import cpw.mods.fml.common.eventhandler.Event.Result;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemDye;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge; | 1,403 | package com.jaquadro.minecraft.gardencore.item;
public class ItemCompost extends Item {
public ItemCompost(String unlocalizedName) {
this.setUnlocalizedName(unlocalizedName);
this.setMaxStackSize(64);
this.setTextureName("GardenCore:compost_pile");
this.setCreativeTab(ModCreativeTabs.tabGardenCore);
}
public boolean onItemUse(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) {
return !player.canPlayerEdit(x, y, z, side, itemStack) ? false : this.applyEnrichment(itemStack, world, x, y, z, player);
}
public boolean applyEnrichment(ItemStack itemStack, World world, int x, int y, int z, EntityPlayer player) { | package com.jaquadro.minecraft.gardencore.item;
public class ItemCompost extends Item {
public ItemCompost(String unlocalizedName) {
this.setUnlocalizedName(unlocalizedName);
this.setMaxStackSize(64);
this.setTextureName("GardenCore:compost_pile");
this.setCreativeTab(ModCreativeTabs.tabGardenCore);
}
public boolean onItemUse(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) {
return !player.canPlayerEdit(x, y, z, side, itemStack) ? false : this.applyEnrichment(itemStack, world, x, y, z, player);
}
public boolean applyEnrichment(ItemStack itemStack, World world, int x, int y, int z, EntityPlayer player) { | ConfigManager config = GardenCore.config; | 2 | 2023-12-12 08:13:16+00:00 | 2k |
joyheros/realworld | app-article/src/main/java/io/zhifou/realworld/article/infra/ArticleFavoriteRepository.java | [
{
"identifier": "ArticleFavorite",
"path": "app-article/src/main/java/io/zhifou/realworld/article/domain/ArticleFavorite.java",
"snippet": "public class ArticleFavorite {\n\tprivate Long articleId;\n\tprivate Long userId;\n\n\tpublic ArticleFavorite() {\n\t}\n\n\tpublic ArticleFavorite(Long articleId, L... | import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import io.zhifou.realworld.article.domain.ArticleFavorite;
import io.zhifou.realworld.article.domain.support.ArticleFavoriteProvider;
import io.zhifou.realworld.article.infra.mapper.ArticleFavoriteMapper; | 750 | package io.zhifou.realworld.article.infra;
@Repository
public class ArticleFavoriteRepository implements ArticleFavoriteProvider { | package io.zhifou.realworld.article.infra;
@Repository
public class ArticleFavoriteRepository implements ArticleFavoriteProvider { | private ArticleFavoriteMapper mapper; | 2 | 2023-12-14 07:28:49+00:00 | 2k |
Zergatul/java-scripting-language | src/main/java/com/zergatul/scripting/compiler/variables/VariableEntry.java | [
{
"identifier": "CompilerMethodVisitor",
"path": "src/main/java/com/zergatul/scripting/compiler/CompilerMethodVisitor.java",
"snippet": "public abstract class CompilerMethodVisitor {\r\n public abstract String getClassName();\r\n public abstract VariableContextStack getContextStack();\r\n publi... | import com.zergatul.scripting.compiler.CompilerMethodVisitor;
import com.zergatul.scripting.compiler.types.SType;
| 1,460 | package com.zergatul.scripting.compiler.variables;
public abstract class VariableEntry {
protected final SType type;
protected VariableEntry(SType type) {
this.type = type;
}
public SType getType() {
return type;
}
| package com.zergatul.scripting.compiler.variables;
public abstract class VariableEntry {
protected final SType type;
protected VariableEntry(SType type) {
this.type = type;
}
public SType getType() {
return type;
}
| public abstract void compileLoad(CompilerMethodVisitor visitor);
| 0 | 2023-12-10 00:37:27+00:00 | 2k |
microsphere-projects/microsphere-multiactive | microsphere-multiactive-spring-cloud/src/main/java/io/microsphere/multiple/active/zone/aws/Ec2AvailabilityZoneEndpointZoneLocator.java | [
{
"identifier": "AbstractZoneLocator",
"path": "microsphere-multiactive-spring-cloud/src/main/java/io/microsphere/multiple/active/zone/AbstractZoneLocator.java",
"snippet": "public abstract class AbstractZoneLocator implements ZoneLocator, BeanNameAware, Ordered {\n\n protected final Logger logger = ... | import io.microsphere.multiple.active.zone.AbstractZoneLocator;
import io.microsphere.multiple.active.zone.HttpUtils;
import io.microsphere.multiple.active.zone.ZoneLocator;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import static io.microsphere.multiple.active.zone.ZoneConstants.DEFAULT_TIMEOUT;
import static io.microsphere.multiple.active.zone.ZoneConstants.LOCATOR_TIMEOUT_PROPERTY_NAME; | 1,022 | package io.microsphere.multiple.active.zone.aws;
/**
* Amazon EC2 Availability Zone Endpoint {@link ZoneLocator}
*
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy<a/>
* @see ZoneLocator
* @since 1.0.0
*/
public class Ec2AvailabilityZoneEndpointZoneLocator extends AbstractZoneLocator implements EnvironmentAware {
public static final String AVAILABILITY_ZONE_ENDPOINT_URI_PROPERTY_NAME = "EC2_AVAILABILITY_ZONE_ENDPOINT_URI";
public static final String DEFAULT_AVAILABILITY_ZONE_ENDPOINT_URI = "http://169.254.169.254/latest/meta-data/placement/availability-zone";
public static final int DEFAULT_ORDER = 15;
private int timeout = DEFAULT_TIMEOUT;
public Ec2AvailabilityZoneEndpointZoneLocator() {
super(DEFAULT_ORDER);
}
@Override
public boolean supports(Environment environment) {
return true;
}
@Override
public String locate(Environment environment) {
String uri = getAvailabilityZoneEndpointURI(environment);
String zone = null;
if (StringUtils.hasText(uri)) {
try { | package io.microsphere.multiple.active.zone.aws;
/**
* Amazon EC2 Availability Zone Endpoint {@link ZoneLocator}
*
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy<a/>
* @see ZoneLocator
* @since 1.0.0
*/
public class Ec2AvailabilityZoneEndpointZoneLocator extends AbstractZoneLocator implements EnvironmentAware {
public static final String AVAILABILITY_ZONE_ENDPOINT_URI_PROPERTY_NAME = "EC2_AVAILABILITY_ZONE_ENDPOINT_URI";
public static final String DEFAULT_AVAILABILITY_ZONE_ENDPOINT_URI = "http://169.254.169.254/latest/meta-data/placement/availability-zone";
public static final int DEFAULT_ORDER = 15;
private int timeout = DEFAULT_TIMEOUT;
public Ec2AvailabilityZoneEndpointZoneLocator() {
super(DEFAULT_ORDER);
}
@Override
public boolean supports(Environment environment) {
return true;
}
@Override
public String locate(Environment environment) {
String uri = getAvailabilityZoneEndpointURI(environment);
String zone = null;
if (StringUtils.hasText(uri)) {
try { | zone = HttpUtils.doGet(uri, timeout); | 1 | 2023-12-11 09:23:26+00:00 | 2k |
Serilum/Collective | Fabric/src/main/java/com/natamus/collective/fabric/mixin/MinecraftServerMixin.java | [
{
"identifier": "CollectiveLifecycleEvents",
"path": "Fabric/src/main/java/com/natamus/collective/fabric/callbacks/CollectiveLifecycleEvents.java",
"snippet": "public class CollectiveLifecycleEvents {\n\tprivate CollectiveLifecycleEvents() { }\n\t \n public static final Event<Minecraft_Loaded> MINECR... | import com.mojang.datafixers.DataFixer;
import com.natamus.collective.fabric.callbacks.CollectiveLifecycleEvents;
import com.natamus.collective.fabric.callbacks.CollectiveMinecraftServerEvents;
import com.natamus.collective.fabric.callbacks.CollectiveWorldEvents;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.Services;
import net.minecraft.server.WorldStem;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.progress.ChunkProgressListenerFactory;
import net.minecraft.server.packs.repository.PackRepository;
import net.minecraft.world.level.storage.LevelStorageSource;
import net.minecraft.world.level.storage.ServerLevelData;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.net.Proxy; | 1,118 | package com.natamus.collective.fabric.mixin;
@Mixin(value = MinecraftServer.class, priority = 1001)
public class MinecraftServerMixin {
@Inject(method = "<init>(Ljava/lang/Thread;Lnet/minecraft/world/level/storage/LevelStorageSource$LevelStorageAccess;Lnet/minecraft/server/packs/repository/PackRepository;Lnet/minecraft/server/WorldStem;Ljava/net/Proxy;Lcom/mojang/datafixers/DataFixer;Lnet/minecraft/server/Services;Lnet/minecraft/server/level/progress/ChunkProgressListenerFactory;)V", at = @At(value = "TAIL"))
public void MinecraftServer_init(Thread thread, LevelStorageSource.LevelStorageAccess levelStorageAccess, PackRepository packRepository, WorldStem worldStem, Proxy proxy, DataFixer dataFixer, Services services, ChunkProgressListenerFactory chunkProgressListenerFactory, CallbackInfo ci) {
((MinecraftServer)(Object)this).execute(() -> {
CollectiveLifecycleEvents.MINECRAFT_LOADED.invoker().onMinecraftLoad(false);
});
}
@Inject(method = "setInitialSpawn", at = @At(value = "RETURN"))
private static void MinecraftServer_setInitialSpawn(ServerLevel serverLevel, ServerLevelData serverLevelData, boolean bl, boolean bl2, CallbackInfo ci) {
CollectiveMinecraftServerEvents.WORLD_SET_SPAWN.invoker().onSetSpawn(serverLevel, serverLevelData);
}
@ModifyVariable(method = "stopServer", at = @At(value= "INVOKE", target = "Lnet/minecraft/server/level/ServerLevel;close()V", ordinal = 0))
public ServerLevel MinecraftServer_stopServer(ServerLevel serverlevel1) { | package com.natamus.collective.fabric.mixin;
@Mixin(value = MinecraftServer.class, priority = 1001)
public class MinecraftServerMixin {
@Inject(method = "<init>(Ljava/lang/Thread;Lnet/minecraft/world/level/storage/LevelStorageSource$LevelStorageAccess;Lnet/minecraft/server/packs/repository/PackRepository;Lnet/minecraft/server/WorldStem;Ljava/net/Proxy;Lcom/mojang/datafixers/DataFixer;Lnet/minecraft/server/Services;Lnet/minecraft/server/level/progress/ChunkProgressListenerFactory;)V", at = @At(value = "TAIL"))
public void MinecraftServer_init(Thread thread, LevelStorageSource.LevelStorageAccess levelStorageAccess, PackRepository packRepository, WorldStem worldStem, Proxy proxy, DataFixer dataFixer, Services services, ChunkProgressListenerFactory chunkProgressListenerFactory, CallbackInfo ci) {
((MinecraftServer)(Object)this).execute(() -> {
CollectiveLifecycleEvents.MINECRAFT_LOADED.invoker().onMinecraftLoad(false);
});
}
@Inject(method = "setInitialSpawn", at = @At(value = "RETURN"))
private static void MinecraftServer_setInitialSpawn(ServerLevel serverLevel, ServerLevelData serverLevelData, boolean bl, boolean bl2, CallbackInfo ci) {
CollectiveMinecraftServerEvents.WORLD_SET_SPAWN.invoker().onSetSpawn(serverLevel, serverLevelData);
}
@ModifyVariable(method = "stopServer", at = @At(value= "INVOKE", target = "Lnet/minecraft/server/level/ServerLevel;close()V", ordinal = 0))
public ServerLevel MinecraftServer_stopServer(ServerLevel serverlevel1) { | CollectiveWorldEvents.WORLD_UNLOAD.invoker().onWorldUnload(serverlevel1); | 2 | 2023-12-11 22:37:15+00:00 | 2k |
MrXiaoM/plugin-template | src/main/java/top/mrxiaom/example/func/DatabaseManager.java | [
{
"identifier": "ExamplePlugin",
"path": "src/main/java/top/mrxiaom/example/ExamplePlugin.java",
"snippet": "@SuppressWarnings({\"unused\"})\npublic class ExamplePlugin extends JavaPlugin implements Listener, TabCompleter {\n private static ExamplePlugin instance;\n public static ExamplePlugin get... | import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.bukkit.configuration.MemoryConfiguration;
import org.jetbrains.annotations.Nullable;
import top.mrxiaom.example.ExamplePlugin;
import top.mrxiaom.example.db.IDatabase;
import top.mrxiaom.example.db.ExampleDatabase;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List; | 1,151 | package top.mrxiaom.example.func;
public class DatabaseManager extends AbstractPluginHolder {
HikariDataSource dataSource = null;
private final List<IDatabase> databases = new ArrayList<>();
@Nullable
public Connection getConnection() {
try {
return dataSource.getConnection();
} catch (Throwable t) {
t.printStackTrace();
return null;
}
}
public final ExampleDatabase example; | package top.mrxiaom.example.func;
public class DatabaseManager extends AbstractPluginHolder {
HikariDataSource dataSource = null;
private final List<IDatabase> databases = new ArrayList<>();
@Nullable
public Connection getConnection() {
try {
return dataSource.getConnection();
} catch (Throwable t) {
t.printStackTrace();
return null;
}
}
public final ExampleDatabase example; | public DatabaseManager(ExamplePlugin plugin) { | 0 | 2023-12-08 15:50:57+00:00 | 2k |
SmartPuck111/mypuchpro | src/main/java/com/blog/service/CommentServiceImpl.java | [
{
"identifier": "CommentException",
"path": "src/main/java/com/blog/exception/CommentException.java",
"snippet": "public class CommentException extends Exception {\n\n\tpublic CommentException() {\n\t\t// TODO Auto-generated constructor stub\n\t}\n\n\tpublic CommentException(String message) {\n\t\tsuper... | import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.blog.exception.CommentException;
import com.blog.exception.LoginException;
import com.blog.exception.PostException;
import com.blog.model.Comment;
import com.blog.model.CommentDTO;
import com.blog.model.CommentUpdateDTO;
import com.blog.model.Login;
import com.blog.model.Post;
import com.blog.repository.CommentRepo;
import com.blog.repository.LoginRepo;
import com.blog.repository.PostRepo; | 987 | package com.blog.service;
@Service
public class CommentServiceImpl implements CommentService {
@Autowired
private LoginRepo loginRepo;
@Autowired
private PostRepo postRepo;
@Autowired
private CommentRepo commentRepo;
// checking user login validation
public void checkLoginStatus() throws LoginException {
List<Login> loginList = loginRepo.findAll();
if (loginList.isEmpty())
throw new LoginException("User login required!");
}
// checking valid postId
public Post checkValidPostId(Integer postId) throws PostException {
Optional<Post> postOpt = postRepo.findById(postId);
if (postOpt.isEmpty())
throw new PostException("Invalid post id");
return postOpt.get();
}
@Override | package com.blog.service;
@Service
public class CommentServiceImpl implements CommentService {
@Autowired
private LoginRepo loginRepo;
@Autowired
private PostRepo postRepo;
@Autowired
private CommentRepo commentRepo;
// checking user login validation
public void checkLoginStatus() throws LoginException {
List<Login> loginList = loginRepo.findAll();
if (loginList.isEmpty())
throw new LoginException("User login required!");
}
// checking valid postId
public Post checkValidPostId(Integer postId) throws PostException {
Optional<Post> postOpt = postRepo.findById(postId);
if (postOpt.isEmpty())
throw new PostException("Invalid post id");
return postOpt.get();
}
@Override | public List<Comment> getAllComment(Integer postId) throws PostException, CommentException, LoginException { | 0 | 2023-12-10 09:21:53+00:00 | 2k |
ferhatcamgoz/modular-desing | product/src/main/java/com/layer/product/ProductServiceImpl.java | [
{
"identifier": "BasketProductService",
"path": "product/src/main/java/com/layer/product/basket/BasketProductService.java",
"snippet": "public interface BasketProductService {\n\n List<ProductDto> getBasketProductsInfo(List<Long> productIds);\n\n Product getById(long productId);\n\n\n int getSt... | import com.layer.product.basket.BasketProductService;
import com.layer.product.basket.ProductDto;
import com.layer.product.model.Product;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors; | 762 | package com.layer.product;
@Service
public class ProductServiceImpl implements ProductService, BasketProductService {
private final ProductRepo productRepo;
public ProductServiceImpl(ProductRepo productRepo) {
this.productRepo = productRepo;
}
@Override
public ProductDto getProductInfo(Long productId) {
return productRepo.findById(productId).map(ProductDto::new).orElse(new ProductDto());
}
@Override
public ProductDto createProduct(ProductDto productDto) { | package com.layer.product;
@Service
public class ProductServiceImpl implements ProductService, BasketProductService {
private final ProductRepo productRepo;
public ProductServiceImpl(ProductRepo productRepo) {
this.productRepo = productRepo;
}
@Override
public ProductDto getProductInfo(Long productId) {
return productRepo.findById(productId).map(ProductDto::new).orElse(new ProductDto());
}
@Override
public ProductDto createProduct(ProductDto productDto) { | return new ProductDto(productRepo.save(new Product(productDto))); | 2 | 2023-12-14 16:40:40+00:00 | 2k |
ExcaliburFRC/2024RobotTamplate | src/main/java/frc/robot/subsystems/LEDs.java | [
{
"identifier": "Color",
"path": "src/main/java/frc/lib/Color.java",
"snippet": "public class Color extends edu.wpi.first.wpilibj.util.Color {\n public Color(double red, double green, double blue) {\n super(green, red, blue);\n }\n\n public Color(int red, int green, int blue) {\n ... | import edu.wpi.first.math.MathUtil;
import edu.wpi.first.wpilibj.AddressableLED;
import edu.wpi.first.wpilibj.AddressableLEDBuffer;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj2.command.*;
import frc.lib.Color;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static frc.lib.Color.Colors.OFF;
import static frc.robot.Constants.LedsConstants.LEDS_PORT;
import static frc.robot.Constants.LedsConstants.LENGTH; | 816 | package frc.robot.subsystems;
public class LEDs extends SubsystemBase {
private final AddressableLED LedStrip = new AddressableLED(LEDS_PORT);
private final AddressableLEDBuffer buffer = new AddressableLEDBuffer(LENGTH);
private static LEDs instance = null;
private Random rnd = new Random();
private int tailIndex = 0;
private double offset = 0;
private LEDs() {
LedStrip.setLength(LENGTH);
LedStrip.start();
// setDefaultCommand(applyPatternCommand(LEDPattern.TRAIN_CIRCLE, BLUE.color, TEAM_GOLD.color));
}
public static LEDs getInstance() {
if (instance == null) {
instance = new LEDs();
}
return instance;
}
| package frc.robot.subsystems;
public class LEDs extends SubsystemBase {
private final AddressableLED LedStrip = new AddressableLED(LEDS_PORT);
private final AddressableLEDBuffer buffer = new AddressableLEDBuffer(LENGTH);
private static LEDs instance = null;
private Random rnd = new Random();
private int tailIndex = 0;
private double offset = 0;
private LEDs() {
LedStrip.setLength(LENGTH);
LedStrip.start();
// setDefaultCommand(applyPatternCommand(LEDPattern.TRAIN_CIRCLE, BLUE.color, TEAM_GOLD.color));
}
public static LEDs getInstance() {
if (instance == null) {
instance = new LEDs();
}
return instance;
}
| public Command applyPatternCommand(LEDPattern pattern, Color mainColor, Color accentColor) { | 0 | 2023-12-13 22:33:35+00:00 | 2k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.