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 |
|---|---|---|---|---|---|---|---|---|---|---|
Teleight/TeleightBots | src/main/java/org/teleight/teleightbots/botmanager/BotManagerImpl.java | [
{
"identifier": "TeleightBots",
"path": "src/main/java/org/teleight/teleightbots/TeleightBots.java",
"snippet": "public final class TeleightBots {\n\n private static TeleightBotsProcess teleightBotsProcess;\n\n public static @NotNull TeleightBots init() {\n updateProcess();\n return ... | import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.teleight.teleightbots.TeleightBots;
import org.teleight.teleightbots.bot.Bot;
import org.teleight.teleightbots.bot.BotSettings;
import org.teleight.teleightbots.bot.trait.LongPollingBot;
import org.teleight.teleightbots.bot.trait.TelegramBot;
import org.teleight.teleightbots.bot.trait.WebHookBot;
import org.teleight.teleightbots.updateprocessor.LongPollingUpdateProcessor;
import org.teleight.teleightbots.updateprocessor.UpdateProcessor;
import org.teleight.teleightbots.utils.ArrayUtils;
import java.util.function.Consumer; | 4,730 | package org.teleight.teleightbots.botmanager;
public final class BotManagerImpl implements BotManager {
private Bot[] registeredBots = new Bot[0];
private BotProvider botProvider = Bot::new;
public BotManagerImpl() {
}
@Override
public void registerLongPolling(@NotNull String token, @NotNull String username, @Nullable BotSettings botSettings) {
registerLongPolling(token, username, botSettings, null);
}
@Override
public void registerLongPolling(@NotNull String token, @NotNull String username, @Nullable BotSettings botSettings, @Nullable Consumer<Bot> completeCallback) {
registerBot(LongPollingBot.class, token, username, botSettings, completeCallback);
}
private <T extends TelegramBot> void registerBot(@NotNull Class<T> botType, @NotNull String token, @NotNull String username,
@Nullable BotSettings botSettings, @Nullable Consumer<Bot> completeCallback) { | package org.teleight.teleightbots.botmanager;
public final class BotManagerImpl implements BotManager {
private Bot[] registeredBots = new Bot[0];
private BotProvider botProvider = Bot::new;
public BotManagerImpl() {
}
@Override
public void registerLongPolling(@NotNull String token, @NotNull String username, @Nullable BotSettings botSettings) {
registerLongPolling(token, username, botSettings, null);
}
@Override
public void registerLongPolling(@NotNull String token, @NotNull String username, @Nullable BotSettings botSettings, @Nullable Consumer<Bot> completeCallback) {
registerBot(LongPollingBot.class, token, username, botSettings, completeCallback);
}
private <T extends TelegramBot> void registerBot(@NotNull Class<T> botType, @NotNull String token, @NotNull String username,
@Nullable BotSettings botSettings, @Nullable Consumer<Bot> completeCallback) { | if (botType == WebHookBot.class) { | 5 | 2023-11-04 16:55:27+00:00 | 8k |
DJ-Raven/swing-glasspane-popup | src/main/java/raven/alerts/SimpleAlerts.java | [
{
"identifier": "GlassPanePopup",
"path": "src/main/java/raven/popup/GlassPanePopup.java",
"snippet": "public class GlassPanePopup {\n\n private static GlassPanePopup instance;\n private JFrame mainFrame;\n protected WindowSnapshots windowSnapshots;\n protected JLayeredPane layerPane;\n p... | import com.formdev.flatlaf.FlatClientProperties;
import com.formdev.flatlaf.extras.FlatSVGIcon;
import com.formdev.flatlaf.ui.FlatUIUtils;
import com.formdev.flatlaf.util.Animator;
import com.formdev.flatlaf.util.CubicBezierEasing;
import com.formdev.flatlaf.util.Graphics2DProxy;
import net.miginfocom.swing.MigLayout;
import raven.popup.GlassPanePopup;
import raven.popup.component.GlassPaneChild;
import raven.popup.component.PopupCallbackAction;
import raven.popup.component.PopupController;
import raven.swing.AnimateIcon;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.util.Random; | 3,612 | package raven.alerts;
public class SimpleAlerts extends GlassPaneChild {
private PanelEffect panelEffect;
private final Component component;
private final int option;
public SimpleAlerts(Component component, AlertsOption alertsOption, int option, PopupCallbackAction callbackAction) {
this.component = component;
this.option = option;
this.callbackAction = callbackAction;
init(alertsOption);
}
private void init(AlertsOption alertsOption) {
setLayout(new MigLayout("wrap,fillx,insets 15 0 15 0", "[fill,400]"));
panelEffect = new PanelEffect(component, alertsOption);
add(panelEffect);
}
@Override
public void popupShow() {
panelEffect.startAnimation();
}
@Override
public int getRoundBorder() {
return 20;
}
protected class PanelEffect extends JPanel {
private AlertsOption alertsOption;
private Effect effects[];
private float animate;
private Animator animator;
private JLabel labelIcon;
private Component component;
private AnimateIcon animateIcon;
private MigLayout layout;
private Component closeButton;
protected void start() {
if (animator == null) {
animator = new Animator(2000, new Animator.TimingTarget() {
@Override
public void timingEvent(float v) {
animate = v;
if (animateIcon != null) {
animateIcon.setAnimate(v);
}
repaint();
}
@Override
public void end() {
if (alertsOption.loopAnimation && isShowing()) {
SwingUtilities.invokeLater(() -> {
startAnimation();
});
}
}
});
animator.setInterpolator(CubicBezierEasing.EASE);
}
if (animator.isRunning()) {
animator.stop();
}
animator.start();
}
private void startAnimation() {
createEffect();
start();
}
private void createEffect() {
if (alertsOption.effectOption != null) {
effects = new Effect[30];
for (int i = 0; i < effects.length; i++) {
effects[i] = new Effect(alertsOption.effectOption.randomEffect);
}
}
}
public PanelEffect(Component component, AlertsOption alertsOption) {
this.component = component;
this.alertsOption = alertsOption;
layout = new MigLayout("fillx,wrap,insets 0", "[fill,center]", "0[]3[]20[]5");
setLayout(layout);
if (alertsOption.icon instanceof AnimateIcon) {
animateIcon = (AnimateIcon) alertsOption.icon;
}
labelIcon = new JLabel(alertsOption.icon);
labelIcon.putClientProperty(FlatClientProperties.STYLE, "" +
"border:25,5,10,5");
boolean ltr = getComponentOrientation().isLeftToRight();
closeButton = createCloseButton();
add(closeButton, "pos " + (ltr ? "100%-pref-25" : "25") + " 2");
add(labelIcon);
add(component);
add(createActionButton(option, alertsOption.baseColor));
}
@Override
public void applyComponentOrientation(ComponentOrientation o) {
super.applyComponentOrientation(o);
boolean ltr = getComponentOrientation().isLeftToRight();
layout.setComponentConstraints(closeButton, "pos " + (ltr ? "100%-pref-25" : "25") + " 2");
}
protected Component createCloseButton() {
JButton cmdClose = new JButton(new FlatSVGIcon("raven/popup/icon/close.svg", 0.8f));
cmdClose.putClientProperty(FlatClientProperties.STYLE, "" +
"arc:999;" +
"borderWidth:0;" +
"focusWidth:0;" +
"innerFocusWidth:0;" +
"background:null");
applyCloseButtonEvent(cmdClose, PopupCallbackAction.CLOSE);
return cmdClose;
}
protected void applyCloseButtonEvent(JButton button, int opt) {
button.addActionListener(e -> {
if (callbackAction == null) {
GlassPanePopup.closePopup(SimpleAlerts.this);
return;
} | package raven.alerts;
public class SimpleAlerts extends GlassPaneChild {
private PanelEffect panelEffect;
private final Component component;
private final int option;
public SimpleAlerts(Component component, AlertsOption alertsOption, int option, PopupCallbackAction callbackAction) {
this.component = component;
this.option = option;
this.callbackAction = callbackAction;
init(alertsOption);
}
private void init(AlertsOption alertsOption) {
setLayout(new MigLayout("wrap,fillx,insets 15 0 15 0", "[fill,400]"));
panelEffect = new PanelEffect(component, alertsOption);
add(panelEffect);
}
@Override
public void popupShow() {
panelEffect.startAnimation();
}
@Override
public int getRoundBorder() {
return 20;
}
protected class PanelEffect extends JPanel {
private AlertsOption alertsOption;
private Effect effects[];
private float animate;
private Animator animator;
private JLabel labelIcon;
private Component component;
private AnimateIcon animateIcon;
private MigLayout layout;
private Component closeButton;
protected void start() {
if (animator == null) {
animator = new Animator(2000, new Animator.TimingTarget() {
@Override
public void timingEvent(float v) {
animate = v;
if (animateIcon != null) {
animateIcon.setAnimate(v);
}
repaint();
}
@Override
public void end() {
if (alertsOption.loopAnimation && isShowing()) {
SwingUtilities.invokeLater(() -> {
startAnimation();
});
}
}
});
animator.setInterpolator(CubicBezierEasing.EASE);
}
if (animator.isRunning()) {
animator.stop();
}
animator.start();
}
private void startAnimation() {
createEffect();
start();
}
private void createEffect() {
if (alertsOption.effectOption != null) {
effects = new Effect[30];
for (int i = 0; i < effects.length; i++) {
effects[i] = new Effect(alertsOption.effectOption.randomEffect);
}
}
}
public PanelEffect(Component component, AlertsOption alertsOption) {
this.component = component;
this.alertsOption = alertsOption;
layout = new MigLayout("fillx,wrap,insets 0", "[fill,center]", "0[]3[]20[]5");
setLayout(layout);
if (alertsOption.icon instanceof AnimateIcon) {
animateIcon = (AnimateIcon) alertsOption.icon;
}
labelIcon = new JLabel(alertsOption.icon);
labelIcon.putClientProperty(FlatClientProperties.STYLE, "" +
"border:25,5,10,5");
boolean ltr = getComponentOrientation().isLeftToRight();
closeButton = createCloseButton();
add(closeButton, "pos " + (ltr ? "100%-pref-25" : "25") + " 2");
add(labelIcon);
add(component);
add(createActionButton(option, alertsOption.baseColor));
}
@Override
public void applyComponentOrientation(ComponentOrientation o) {
super.applyComponentOrientation(o);
boolean ltr = getComponentOrientation().isLeftToRight();
layout.setComponentConstraints(closeButton, "pos " + (ltr ? "100%-pref-25" : "25") + " 2");
}
protected Component createCloseButton() {
JButton cmdClose = new JButton(new FlatSVGIcon("raven/popup/icon/close.svg", 0.8f));
cmdClose.putClientProperty(FlatClientProperties.STYLE, "" +
"arc:999;" +
"borderWidth:0;" +
"focusWidth:0;" +
"innerFocusWidth:0;" +
"background:null");
applyCloseButtonEvent(cmdClose, PopupCallbackAction.CLOSE);
return cmdClose;
}
protected void applyCloseButtonEvent(JButton button, int opt) {
button.addActionListener(e -> {
if (callbackAction == null) {
GlassPanePopup.closePopup(SimpleAlerts.this);
return;
} | PopupController action = createController(); | 3 | 2023-11-08 14:06:16+00:00 | 8k |
CxyJerry/pilipala | src/main/java/com/jerry/pilipala/domain/vod/service/impl/RecommendServiceImpl.java | [
{
"identifier": "PreviewBVodVO",
"path": "src/main/java/com/jerry/pilipala/application/vo/bvod/PreviewBVodVO.java",
"snippet": "@Data\n@Accessors(chain = true)\npublic class PreviewBVodVO {\n private String bvId;\n private String coverUrl;\n private String title;\n private String desc;\n ... | import cn.dev33.satoken.stp.StpUtil;
import com.jerry.pilipala.application.vo.bvod.PreviewBVodVO;
import com.jerry.pilipala.application.vo.user.PreviewUserVO;
import com.jerry.pilipala.application.vo.vod.PreviewVodVO;
import com.jerry.pilipala.application.vo.vod.RecommendVO;
import com.jerry.pilipala.domain.user.entity.mongo.User;
import com.jerry.pilipala.domain.vod.entity.mongo.statitics.VodStatistics;
import com.jerry.pilipala.domain.vod.entity.neo4j.VodInfoEntity;
import com.jerry.pilipala.domain.vod.repository.VodInfoRepository;
import com.jerry.pilipala.domain.vod.service.RecommendService;
import com.jerry.pilipala.domain.vod.service.VodService;
import com.jerry.pilipala.infrastructure.enums.PartitionEnum;
import com.jerry.pilipala.infrastructure.enums.Qn;
import com.jerry.pilipala.infrastructure.utils.Page;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors; | 4,129 | package com.jerry.pilipala.domain.vod.service.impl;
@Service
public class RecommendServiceImpl implements RecommendService {
private final MongoTemplate mongoTemplate;
private final VodService vodService;
private final VodInfoRepository vodInfoRepository;
public RecommendServiceImpl(MongoTemplate mongoTemplate,
RedisTemplate<String, Object> redisTemplate,
VodService vodService,
VodInfoRepository vodInfoRepository) {
this.mongoTemplate = mongoTemplate;
this.vodService = vodService;
this.vodInfoRepository = vodInfoRepository;
}
@Override
public RecommendVO recommend(Integer swiperCount, Integer feedCount) {
String uid = StpUtil.getLoginId("");
List<VodInfoEntity> swiperList = vodInfoRepository
.recommendVideosByContentBasedFiltering(swiperCount);
List<VodInfoEntity> firstList =
vodInfoRepository.recommendVideosByUserId(uid, feedCount);
if (firstList.isEmpty()) {
firstList = vodInfoRepository
.recommendVideosByContentBasedFiltering(swiperCount);
}
RecommendVO recommendVO = new RecommendVO();
recommendVO.setSwiper(buildPreviewBVodList(swiperList))
.setFirst(buildPreviewBVodList(firstList));
return recommendVO;
}
@Override
public Map<String, List<PartitionEnum>> partitions() {
return PartitionEnum.partitions()
.stream()
.collect(Collectors.groupingBy(PartitionEnum::getPartition));
}
@Override | package com.jerry.pilipala.domain.vod.service.impl;
@Service
public class RecommendServiceImpl implements RecommendService {
private final MongoTemplate mongoTemplate;
private final VodService vodService;
private final VodInfoRepository vodInfoRepository;
public RecommendServiceImpl(MongoTemplate mongoTemplate,
RedisTemplate<String, Object> redisTemplate,
VodService vodService,
VodInfoRepository vodInfoRepository) {
this.mongoTemplate = mongoTemplate;
this.vodService = vodService;
this.vodInfoRepository = vodInfoRepository;
}
@Override
public RecommendVO recommend(Integer swiperCount, Integer feedCount) {
String uid = StpUtil.getLoginId("");
List<VodInfoEntity> swiperList = vodInfoRepository
.recommendVideosByContentBasedFiltering(swiperCount);
List<VodInfoEntity> firstList =
vodInfoRepository.recommendVideosByUserId(uid, feedCount);
if (firstList.isEmpty()) {
firstList = vodInfoRepository
.recommendVideosByContentBasedFiltering(swiperCount);
}
RecommendVO recommendVO = new RecommendVO();
recommendVO.setSwiper(buildPreviewBVodList(swiperList))
.setFirst(buildPreviewBVodList(firstList));
return recommendVO;
}
@Override
public Map<String, List<PartitionEnum>> partitions() {
return PartitionEnum.partitions()
.stream()
.collect(Collectors.groupingBy(PartitionEnum::getPartition));
}
@Override | public Page<PreviewBVodVO> recommendPartition(String partition, | 12 | 2023-11-03 10:05:02+00:00 | 8k |
viego1999/xuecheng-plus-project | xuecheng-plus-orders/xuecheng-plus-orders-service/src/main/java/com/xuecheng/orders/service/impl/OrderServiceImpl.java | [
{
"identifier": "XueChengPlusException",
"path": "xuecheng-plus-base/src/main/java/com/xuecheng/base/exception/XueChengPlusException.java",
"snippet": "public class XueChengPlusException extends RuntimeException {\n private static final long serialVersionUID = 5565760508056698922L;\n private Strin... | import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.utils.IdWorkerUtils;
import com.xuecheng.base.utils.QRCodeUtil;
import com.xuecheng.messagesdk.service.MqMessageService;
import com.xuecheng.orders.config.PayNotifyConfig;
import com.xuecheng.orders.mapper.XcOrdersGoodsMapper;
import com.xuecheng.orders.mapper.XcOrdersMapper;
import com.xuecheng.orders.mapper.XcPayRecordMapper;
import com.xuecheng.orders.model.dto.AddOrderDto;
import com.xuecheng.orders.model.dto.PayRecordDto;
import com.xuecheng.orders.model.dto.PayStatusDto;
import com.xuecheng.orders.model.po.XcOrders;
import com.xuecheng.orders.model.po.XcOrdersGoods;
import com.xuecheng.orders.model.po.XcPayRecord;
import com.xuecheng.orders.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List; | 5,656 | package com.xuecheng.orders.service.impl;
/**
* 订单接口实现类
*
* @author Wuxy
* @version 1.0
* @since 2022/10/25 11:42
*/
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
XcOrdersMapper ordersMapper;
@Autowired
XcOrdersGoodsMapper ordersGoodsMapper;
@Autowired
XcPayRecordMapper payRecordMapper;
@Autowired
MqMessageService mqMessageService;
@Value("${pay.alipay.APP_ID}")
String APP_ID;
@Transactional
@Override
public PayRecordDto createOrder(String userId, AddOrderDto addOrderDto) {
// 创建商品订单
XcOrders orders = saveXcOrders(userId, addOrderDto);
// 添加支付记录
XcPayRecord payRecord = createPayRecord(orders);
// 生成支付二维码
String qrCode = null;
try {
// url要可以被模拟器访问到,url为下单接口(稍后定义)
qrCode = new QRCodeUtil().createQRCode("http://192.168.247.1:63030/orders/requestpay?payNo=" + payRecord.getPayNo(), 200, 200);
} catch (IOException e) { | package com.xuecheng.orders.service.impl;
/**
* 订单接口实现类
*
* @author Wuxy
* @version 1.0
* @since 2022/10/25 11:42
*/
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
XcOrdersMapper ordersMapper;
@Autowired
XcOrdersGoodsMapper ordersGoodsMapper;
@Autowired
XcPayRecordMapper payRecordMapper;
@Autowired
MqMessageService mqMessageService;
@Value("${pay.alipay.APP_ID}")
String APP_ID;
@Transactional
@Override
public PayRecordDto createOrder(String userId, AddOrderDto addOrderDto) {
// 创建商品订单
XcOrders orders = saveXcOrders(userId, addOrderDto);
// 添加支付记录
XcPayRecord payRecord = createPayRecord(orders);
// 生成支付二维码
String qrCode = null;
try {
// url要可以被模拟器访问到,url为下单接口(稍后定义)
qrCode = new QRCodeUtil().createQRCode("http://192.168.247.1:63030/orders/requestpay?payNo=" + payRecord.getPayNo(), 200, 200);
} catch (IOException e) { | XueChengPlusException.cast("生成二维码出错"); | 0 | 2023-11-04 07:15:26+00:00 | 8k |
dionp3/xplora | app/src/main/java/org/gnulag/xplora/controllers/Controller.java | [
{
"identifier": "RedBlackTreeMap",
"path": "app/src/main/java/org/gnulag/xplora/models/RedBlackTreeMap.java",
"snippet": "public class RedBlackTreeMap<K extends Comparable<K>, V extends Comparable<V>> {\n private Node<K, V> root;\n private Node<K, V> TNULL;\n\n public RedBlackTreeMap() {\n TNULL =... | import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import javafx.animation.TranslateTransition;
import javafx.concurrent.Worker;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.Button;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.cell.TextFieldListCell;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebView;
import javafx.util.Duration;
import org.gnulag.xplora.models.RedBlackTreeMap;
import org.gnulag.xplora.utils.GameGimmick;
import org.gnulag.xplora.utils.JSONUtil;
import org.gnulag.xplora.utils.PrintsUtil;
import org.gnulag.xplora.utils.RandomGimmick; | 6,127 | package org.gnulag.xplora.controllers;
public class Controller implements Initializable {
@FXML private ListView<String> listView;
@FXML private TextField searchBar;
@FXML private Label searchButton;
@FXML private Label clearListView;
@FXML private AnchorPane slider;
@FXML private VBox textAreaContainer;
@FXML private Label backButton;
@FXML private TextArea description;
private boolean isFullText = false;
private RedBlackTreeMap<String, String> rbTree;
public Controller() {
rbTree = new RedBlackTreeMap<>();
rbTree.insert("acak", null, new RandomGimmick<>());
rbTree.insert("random", null, new RandomGimmick<>());
rbTree.insert("batu", null, new GameGimmick<>());
rbTree.insert("gunting", null, new GameGimmick<>());
rbTree.insert("kertas", null, new GameGimmick<>());
rbTree.insert("rock", null, new GameGimmick<>());
rbTree.insert("paper", null, new GameGimmick<>());
rbTree.insert("scissor", null, new GameGimmick<>());
JSONUtil.loadJsonData(rbTree, "/data.json");
//rbTree.printTree();
}
@Override
public void initialize(URL location, ResourceBundle resources) {
searchButton.setOnMouseClicked(
event -> {
String searchParam = searchBar.getText().toLowerCase();
if (!searchParam.isEmpty()) { | package org.gnulag.xplora.controllers;
public class Controller implements Initializable {
@FXML private ListView<String> listView;
@FXML private TextField searchBar;
@FXML private Label searchButton;
@FXML private Label clearListView;
@FXML private AnchorPane slider;
@FXML private VBox textAreaContainer;
@FXML private Label backButton;
@FXML private TextArea description;
private boolean isFullText = false;
private RedBlackTreeMap<String, String> rbTree;
public Controller() {
rbTree = new RedBlackTreeMap<>();
rbTree.insert("acak", null, new RandomGimmick<>());
rbTree.insert("random", null, new RandomGimmick<>());
rbTree.insert("batu", null, new GameGimmick<>());
rbTree.insert("gunting", null, new GameGimmick<>());
rbTree.insert("kertas", null, new GameGimmick<>());
rbTree.insert("rock", null, new GameGimmick<>());
rbTree.insert("paper", null, new GameGimmick<>());
rbTree.insert("scissor", null, new GameGimmick<>());
JSONUtil.loadJsonData(rbTree, "/data.json");
//rbTree.printTree();
}
@Override
public void initialize(URL location, ResourceBundle resources) {
searchButton.setOnMouseClicked(
event -> {
String searchParam = searchBar.getText().toLowerCase();
if (!searchParam.isEmpty()) { | List<String> results = PrintsUtil.printRedBlackTreeResults(rbTree, searchParam); | 3 | 2023-11-03 13:01:57+00:00 | 8k |
Verusins/CMS-Android-Simulation | app/src/main/java/example/com/cmsandroidsimulation/DashboardStudentFragment.java | [
{
"identifier": "Admin",
"path": "app/src/main/java/example/com/cmsandroidsimulation/apiwrapper/Admin.java",
"snippet": "public class Admin extends User{\n // TODO: implement api calls\n\n public void Logout(){\n\n FirebaseAuth.getInstance().signOut();\n instance = null;\n }\n ... | import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import example.com.cmsandroidsimulation.apiwrapper.Admin;
import example.com.cmsandroidsimulation.databinding.FragmentDashboardStudentBinding;
import example.com.cmsandroidsimulation.datastructures.Announcement;
import example.com.cmsandroidsimulation.datastructures.EventInfo;
import example.com.cmsandroidsimulation.apiwrapper.Student; | 3,649 | package example.com.cmsandroidsimulation;
public class DashboardStudentFragment extends Fragment {
FragmentDashboardStudentBinding binding;
EventAdapter adapter;
AnnouncementAdapter announcementAdapter;
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState
) {
binding = FragmentDashboardStudentBinding.inflate(inflater, container, false);
return binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// RelativeLayout sidebar = binding.sidebarWrapper;
// Disable Sidebar on create
// sidebar.setVisibility(View.GONE);
// List Announcements from database
Log.i("test0", "test0"); | package example.com.cmsandroidsimulation;
public class DashboardStudentFragment extends Fragment {
FragmentDashboardStudentBinding binding;
EventAdapter adapter;
AnnouncementAdapter announcementAdapter;
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState
) {
binding = FragmentDashboardStudentBinding.inflate(inflater, container, false);
return binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// RelativeLayout sidebar = binding.sidebarWrapper;
// Disable Sidebar on create
// sidebar.setVisibility(View.GONE);
// List Announcements from database
Log.i("test0", "test0"); | Student.getInstance().getAnnouncements().thenAccept((ArrayList<Announcement> announcements) -> { | 1 | 2023-11-07 16:52:01+00:00 | 8k |
ProjectBIGWHALE/bigwhale-api | src/main/java/com/whale/web/documents/DocumentsController.java | [
{
"identifier": "CreateCertificateService",
"path": "src/main/java/com/whale/web/documents/certificategenerator/service/CreateCertificateService.java",
"snippet": "@Service\npublic class CreateCertificateService {\n\n\n private final EditSVGFiles createCerificateService;\n\n public CreateCertifica... | import com.whale.web.documents.certificategenerator.dto.CertificateRecordDto;
import com.whale.web.documents.certificategenerator.service.CreateCertificateService;
import com.whale.web.documents.certificategenerator.service.ProcessWorksheetService;
import com.whale.web.documents.compressedfileconverter.CompactConverterService;
import com.whale.web.documents.zipfilegenerator.ZipFileCompressorService;
import com.whale.web.documents.imageconverter.service.ImageConverterService;
import com.whale.web.documents.qrcodegenerator.dto.QRCodeEmailRecordDto;
import com.whale.web.documents.qrcodegenerator.dto.QRCodeLinkRecordDto;
import com.whale.web.documents.qrcodegenerator.dto.QRCodeWhatsappRecordDto;
import com.whale.web.documents.qrcodegenerator.model.QRCodeEmailModel;
import com.whale.web.documents.qrcodegenerator.model.QRCodeLinkModel;
import com.whale.web.documents.qrcodegenerator.model.QRCodeWhatsappModel;
import com.whale.web.documents.qrcodegenerator.service.QRCodeEmailService;
import com.whale.web.documents.qrcodegenerator.service.QRCodeLinkService;
import com.whale.web.documents.qrcodegenerator.service.QRCodeWhatsappService;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.http.*;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import jakarta.validation.Valid;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; | 5,557 | this.qrCodeWhatsappService = qrCodeWhatsappService;
this.qrCodeEmailService = qrCodeEmailService;
this.processWorksheetService = processWorksheetService;
this.createCertificateService = createCertificateService;
}
private static final Logger logger = LoggerFactory.getLogger(DocumentsController.class);
private static final String ATTACHMENT_FILENAME = "attachment; filename=";
@PostMapping(value = "/compactconverter", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@Operation(summary = "Compact Converter", description = "Convert ZIP to other compression formats", method = "POST")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Compression performed successfully", content = {@Content(mediaType = MediaType.APPLICATION_OCTET_STREAM_VALUE)}),
@ApiResponse(responseCode = "400", description = "Error in validating form fields", content = {@Content(mediaType = MediaType.APPLICATION_JSON_VALUE)}),
@ApiResponse(responseCode = "500", description = "Error compressing file", content = {@Content(schema = @Schema())})
})
public ResponseEntity<Object> compactConverter(
@Parameter(description = "Submit one or more zips file here") @RequestPart("files") List<MultipartFile> files,
@Parameter(description = "Enter the compression format. Choose a tar, zip, 7z or tar.gz") @RequestParam("outputFormat") String outputFormat) throws IOException {
List<byte[]> filesConverted = compactConverterService.converterFile(files, outputFormat);
String convertedFileName = StringUtils.stripFilenameExtension(Objects.requireNonNull(files.get(0).getOriginalFilename()))
+ "." + outputFormat.toLowerCase();
byte[] responseBytes;
if (filesConverted.size() == 1) responseBytes = filesConverted.get(0);
else responseBytes = createZipArchive(filesConverted);
logger.info("Compressed file conversion successful");
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.header(HttpHeaders.CONTENT_DISPOSITION, ATTACHMENT_FILENAME + convertedFileName)
.header(CacheControl.noCache().toString())
.body(responseBytes);
}
private byte[] createZipArchive(List<byte[]> files) throws IOException {
ByteArrayOutputStream zipStream = new ByteArrayOutputStream();
try (ZipOutputStream zipOutputStream = new ZipOutputStream(zipStream)) {
for (int i = 0; i < files.size(); i++) {
byte[] fileBytes = files.get(i);
ZipEntry zipEntry = new ZipEntry("file" + (i + 1) + ".zip");
zipOutputStream.putNextEntry(zipEntry);
zipOutputStream.write(fileBytes);
zipOutputStream.closeEntry();
}
}
return zipStream.toByteArray();
}
@PostMapping(value = "/filecompressor", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@Operation(summary = "File Compressor", description = "Compresses one or more files.", method = "POST")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Compression performed successfully", content = {@Content(mediaType = MediaType.APPLICATION_OCTET_STREAM_VALUE)}),
@ApiResponse(responseCode = "400", description = "Error in validating form fields", content = {@Content(mediaType = MediaType.APPLICATION_JSON_VALUE)}),
@ApiResponse(responseCode = "500", description = "Error compressing file", content = {@Content(mediaType = MediaType.TEXT_PLAIN_VALUE)})
})
public ResponseEntity<Object> fileCompressor(
@Parameter(description = "Submit one or more files here.") @RequestPart List<MultipartFile> file) {
try {
byte[] bytes = zipFileCompressorService.compressFiles(file);
logger.info("File compressed successfully");
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.header(HttpHeaders.CONTENT_DISPOSITION, ATTACHMENT_FILENAME + "compressedFile.zip")
.header(CacheControl.noCache().toString())
.body(bytes);
} catch (Exception e) {
logger.error(e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
@PostMapping(value = "/imageconverter", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@Operation(summary = "Image Converter", description = "Convert an image to another format", method = "POST")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Success", content = {@Content(mediaType = "application/octet-stream")}),
@ApiResponse(responseCode = "400", description = "Error in validating form fields", content = {@Content(mediaType = MediaType.APPLICATION_JSON_VALUE)}),
@ApiResponse(responseCode = "500", description = "Error converting image", content = {@Content(mediaType = MediaType.TEXT_PLAIN_VALUE)})
})
public ResponseEntity<Object> imageConverter(
@Parameter(description = "Enter the image format: Please choose a BMP, JPG, JPEG , GIF, PNG or TIFF") @RequestParam("outputFormat") String outputFormat,
@Parameter(description = "Submit an image here. Accepted formats: BMP, JPG, JPEG or GIF file.") @RequestPart MultipartFile image
) {
try {
byte[] bytes = imageConverterService.convertImageFormat(outputFormat, image);
String originalFileNameWithoutExtension = StringUtils.stripFilenameExtension(Objects.requireNonNull(image.getOriginalFilename()));
String convertedFileName = originalFileNameWithoutExtension + "." + outputFormat.toLowerCase();
logger.info("Image converted successfully");
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.header(HttpHeaders.CONTENT_DISPOSITION, ATTACHMENT_FILENAME + convertedFileName)
.header(CacheControl.noCache().toString())
.body(bytes);
} catch (Exception e) {
logger.error(e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
@PostMapping(value = "/qrcodegenerator/link", consumes = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "QRCOde Generator for link", description = "Generates QRCode for Link in the chosen color", method = "POST")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Qrcode generated successfully", content = {@Content(mediaType = "image/png")}),
@ApiResponse(responseCode = "400", description = "Error in validating form fields", content = {@Content(mediaType = MediaType.APPLICATION_JSON_VALUE)}),
@ApiResponse(responseCode = "500", description = "Error generating qrcode", content = {@Content(mediaType = MediaType.TEXT_PLAIN_VALUE)})
})
public ResponseEntity<Object> qrCodeGeneratorLink(@RequestBody @Valid QRCodeLinkRecordDto qrCodeLinkRecordDto) {
try { | package com.whale.web.documents;
@RestController
@RequestMapping(value = "api/v1/documents")
@Tag(name = "API for documents resource palette")
@CrossOrigin(origins = "*")
public class DocumentsController {
private final CompactConverterService compactConverterService;
private final ZipFileCompressorService zipFileCompressorService;
private final ImageConverterService imageConverterService;
private final QRCodeLinkService qrCodeLinkService;
private final QRCodeWhatsappService qrCodeWhatsappService;
private final QRCodeEmailService qrCodeEmailService;
private final ProcessWorksheetService processWorksheetService;
private final CreateCertificateService createCertificateService;
public DocumentsController(CompactConverterService compactConverterService,
ZipFileCompressorService zipFileCompressorService, ImageConverterService imageConverterService,
QRCodeLinkService qrCodeLinkService, QRCodeWhatsappService qrCodeWhatsappService,
QRCodeEmailService qrCodeEmailService, ProcessWorksheetService processWorksheetService,
CreateCertificateService createCertificateService) {
this.compactConverterService = compactConverterService;
this.zipFileCompressorService = zipFileCompressorService;
this.imageConverterService = imageConverterService;
this.qrCodeLinkService = qrCodeLinkService;
this.qrCodeWhatsappService = qrCodeWhatsappService;
this.qrCodeEmailService = qrCodeEmailService;
this.processWorksheetService = processWorksheetService;
this.createCertificateService = createCertificateService;
}
private static final Logger logger = LoggerFactory.getLogger(DocumentsController.class);
private static final String ATTACHMENT_FILENAME = "attachment; filename=";
@PostMapping(value = "/compactconverter", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@Operation(summary = "Compact Converter", description = "Convert ZIP to other compression formats", method = "POST")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Compression performed successfully", content = {@Content(mediaType = MediaType.APPLICATION_OCTET_STREAM_VALUE)}),
@ApiResponse(responseCode = "400", description = "Error in validating form fields", content = {@Content(mediaType = MediaType.APPLICATION_JSON_VALUE)}),
@ApiResponse(responseCode = "500", description = "Error compressing file", content = {@Content(schema = @Schema())})
})
public ResponseEntity<Object> compactConverter(
@Parameter(description = "Submit one or more zips file here") @RequestPart("files") List<MultipartFile> files,
@Parameter(description = "Enter the compression format. Choose a tar, zip, 7z or tar.gz") @RequestParam("outputFormat") String outputFormat) throws IOException {
List<byte[]> filesConverted = compactConverterService.converterFile(files, outputFormat);
String convertedFileName = StringUtils.stripFilenameExtension(Objects.requireNonNull(files.get(0).getOriginalFilename()))
+ "." + outputFormat.toLowerCase();
byte[] responseBytes;
if (filesConverted.size() == 1) responseBytes = filesConverted.get(0);
else responseBytes = createZipArchive(filesConverted);
logger.info("Compressed file conversion successful");
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.header(HttpHeaders.CONTENT_DISPOSITION, ATTACHMENT_FILENAME + convertedFileName)
.header(CacheControl.noCache().toString())
.body(responseBytes);
}
private byte[] createZipArchive(List<byte[]> files) throws IOException {
ByteArrayOutputStream zipStream = new ByteArrayOutputStream();
try (ZipOutputStream zipOutputStream = new ZipOutputStream(zipStream)) {
for (int i = 0; i < files.size(); i++) {
byte[] fileBytes = files.get(i);
ZipEntry zipEntry = new ZipEntry("file" + (i + 1) + ".zip");
zipOutputStream.putNextEntry(zipEntry);
zipOutputStream.write(fileBytes);
zipOutputStream.closeEntry();
}
}
return zipStream.toByteArray();
}
@PostMapping(value = "/filecompressor", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@Operation(summary = "File Compressor", description = "Compresses one or more files.", method = "POST")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Compression performed successfully", content = {@Content(mediaType = MediaType.APPLICATION_OCTET_STREAM_VALUE)}),
@ApiResponse(responseCode = "400", description = "Error in validating form fields", content = {@Content(mediaType = MediaType.APPLICATION_JSON_VALUE)}),
@ApiResponse(responseCode = "500", description = "Error compressing file", content = {@Content(mediaType = MediaType.TEXT_PLAIN_VALUE)})
})
public ResponseEntity<Object> fileCompressor(
@Parameter(description = "Submit one or more files here.") @RequestPart List<MultipartFile> file) {
try {
byte[] bytes = zipFileCompressorService.compressFiles(file);
logger.info("File compressed successfully");
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.header(HttpHeaders.CONTENT_DISPOSITION, ATTACHMENT_FILENAME + "compressedFile.zip")
.header(CacheControl.noCache().toString())
.body(bytes);
} catch (Exception e) {
logger.error(e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
@PostMapping(value = "/imageconverter", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@Operation(summary = "Image Converter", description = "Convert an image to another format", method = "POST")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Success", content = {@Content(mediaType = "application/octet-stream")}),
@ApiResponse(responseCode = "400", description = "Error in validating form fields", content = {@Content(mediaType = MediaType.APPLICATION_JSON_VALUE)}),
@ApiResponse(responseCode = "500", description = "Error converting image", content = {@Content(mediaType = MediaType.TEXT_PLAIN_VALUE)})
})
public ResponseEntity<Object> imageConverter(
@Parameter(description = "Enter the image format: Please choose a BMP, JPG, JPEG , GIF, PNG or TIFF") @RequestParam("outputFormat") String outputFormat,
@Parameter(description = "Submit an image here. Accepted formats: BMP, JPG, JPEG or GIF file.") @RequestPart MultipartFile image
) {
try {
byte[] bytes = imageConverterService.convertImageFormat(outputFormat, image);
String originalFileNameWithoutExtension = StringUtils.stripFilenameExtension(Objects.requireNonNull(image.getOriginalFilename()));
String convertedFileName = originalFileNameWithoutExtension + "." + outputFormat.toLowerCase();
logger.info("Image converted successfully");
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.header(HttpHeaders.CONTENT_DISPOSITION, ATTACHMENT_FILENAME + convertedFileName)
.header(CacheControl.noCache().toString())
.body(bytes);
} catch (Exception e) {
logger.error(e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
@PostMapping(value = "/qrcodegenerator/link", consumes = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "QRCOde Generator for link", description = "Generates QRCode for Link in the chosen color", method = "POST")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Qrcode generated successfully", content = {@Content(mediaType = "image/png")}),
@ApiResponse(responseCode = "400", description = "Error in validating form fields", content = {@Content(mediaType = MediaType.APPLICATION_JSON_VALUE)}),
@ApiResponse(responseCode = "500", description = "Error generating qrcode", content = {@Content(mediaType = MediaType.TEXT_PLAIN_VALUE)})
})
public ResponseEntity<Object> qrCodeGeneratorLink(@RequestBody @Valid QRCodeLinkRecordDto qrCodeLinkRecordDto) {
try { | var qrCodeLinkModel = new QRCodeLinkModel(); | 6 | 2023-11-08 22:41:22+00:00 | 8k |
giteecode/oaSystemPublic | src/main/java/cn/gson/oasys/model/dao/user/UserDao.java | [
{
"identifier": "Dept",
"path": "src/main/java/cn/gson/oasys/model/entity/user/Dept.java",
"snippet": "@Entity\n@Table(name = \"aoa_dept\")\npublic class Dept {\n\t@Id\n\t@Column(name = \"dept_id\")\n\t@GeneratedValue(strategy=GenerationType.IDENTITY)\n\tprivate Long deptId;\t//部门id\n\t\n\t@Column(name ... | import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import cn.gson.oasys.model.entity.user.Dept;
import cn.gson.oasys.model.entity.user.User; | 4,694 | package cn.gson.oasys.model.dao.user;
public interface UserDao extends JpaRepository<User, Long>{
List<User> findByUserId(Long id);
List<User> findByFatherId(Long parentid);
@Query("select u from User u ")
List<User> findAll();
@Query("select u from User u ")
Page<User> findAllPage(Pageable pa);
Page<User> findByFatherId(Long parentid,Pageable pa);
//名字模糊查找
@Query("select u from User u where (u.userName like %?1% or u.realName like %?1%) and u.fatherId=?2 ")
Page<User> findbyFatherId(String name,Long parentid,Pageable pa);
//名字模糊查找
@Query("select u from User u where (u.userName like %?1% or u.realName like %?1%)")
Page<User> findAllUserByName(String name,Pageable pa);
@Query("select u from User u where u.userName=:name")
User findid(@Param("name")String name);
@Query("select tu.pkId from Taskuser tu where tu.taskId.taskId=:taskid and tu.userId.userId=:userid")
Long findpkId(@Param("taskid")Long taskid,@Param("userid")Long userid);
//根据名字找用户
User findByUserName(String title);
//根据用户名模糊查找
@Query("from User u where u.userName like %:name% or u.realName like %:name%")
Page<User> findbyUserNameLike(@Param("name")String name,Pageable pa);
//根据真实姓名模糊查找
Page<User> findByrealNameLike(String title,Pageable pa);
//根据姓名首拼模糊查找,并分页
Page<User> findByPinyinLike(String pinyin,Pageable pa);
//根据姓名首拼+查找关键字查找(部门、姓名、电话号码),并分页
@Query("from User u where (u.userName like ?1 or u.dept.deptName like ?1 or u.userTel like ?1 or u.position.name like ?1) and u.pinyin like ?2")
Page<User> findSelectUsers(String baseKey,String pinyinm,Pageable pa);
//根据姓名首拼+查找关键字查找(部门、姓名、电话号码),并分页
@Query("from User u where u.userName like ?1 or u.dept.deptName like ?1 or u.userTel like ?1 or u.position.name like ?1 or u.pinyin like ?2")
Page<User> findUsers(String baseKey,String baseKey2,Pageable pa);
/**
* 用户管理查询可用用户
* @param isLock
* @param pa
* @return
*/
Page<User> findByIsLock(Integer isLock,Pageable pa);
@Query("from User u where u.dept.deptName like %?1% or u.userName like %?1% or u.realName like %?1% or u.userTel like %?1% or u.role.roleName like %?1%")
Page<User> findnamelike(String name,Pageable pa);
| package cn.gson.oasys.model.dao.user;
public interface UserDao extends JpaRepository<User, Long>{
List<User> findByUserId(Long id);
List<User> findByFatherId(Long parentid);
@Query("select u from User u ")
List<User> findAll();
@Query("select u from User u ")
Page<User> findAllPage(Pageable pa);
Page<User> findByFatherId(Long parentid,Pageable pa);
//名字模糊查找
@Query("select u from User u where (u.userName like %?1% or u.realName like %?1%) and u.fatherId=?2 ")
Page<User> findbyFatherId(String name,Long parentid,Pageable pa);
//名字模糊查找
@Query("select u from User u where (u.userName like %?1% or u.realName like %?1%)")
Page<User> findAllUserByName(String name,Pageable pa);
@Query("select u from User u where u.userName=:name")
User findid(@Param("name")String name);
@Query("select tu.pkId from Taskuser tu where tu.taskId.taskId=:taskid and tu.userId.userId=:userid")
Long findpkId(@Param("taskid")Long taskid,@Param("userid")Long userid);
//根据名字找用户
User findByUserName(String title);
//根据用户名模糊查找
@Query("from User u where u.userName like %:name% or u.realName like %:name%")
Page<User> findbyUserNameLike(@Param("name")String name,Pageable pa);
//根据真实姓名模糊查找
Page<User> findByrealNameLike(String title,Pageable pa);
//根据姓名首拼模糊查找,并分页
Page<User> findByPinyinLike(String pinyin,Pageable pa);
//根据姓名首拼+查找关键字查找(部门、姓名、电话号码),并分页
@Query("from User u where (u.userName like ?1 or u.dept.deptName like ?1 or u.userTel like ?1 or u.position.name like ?1) and u.pinyin like ?2")
Page<User> findSelectUsers(String baseKey,String pinyinm,Pageable pa);
//根据姓名首拼+查找关键字查找(部门、姓名、电话号码),并分页
@Query("from User u where u.userName like ?1 or u.dept.deptName like ?1 or u.userTel like ?1 or u.position.name like ?1 or u.pinyin like ?2")
Page<User> findUsers(String baseKey,String baseKey2,Pageable pa);
/**
* 用户管理查询可用用户
* @param isLock
* @param pa
* @return
*/
Page<User> findByIsLock(Integer isLock,Pageable pa);
@Query("from User u where u.dept.deptName like %?1% or u.userName like %?1% or u.realName like %?1% or u.userTel like %?1% or u.role.roleName like %?1%")
Page<User> findnamelike(String name,Pageable pa);
| List<User> findByDept(Dept dept); | 0 | 2023-11-03 02:29:57+00:00 | 8k |
Mau38/SparePartsFTC | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/drive/opmode/MaxVelocityTuner.java | [
{
"identifier": "DriveConstants",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/drive/DriveConstants.java",
"snippet": "@Config\npublic class DriveConstants {\n\n /*\n * These are motor constants that should be listed online for your motors.\n */\n public static... | import com.acmerobotics.dashboard.FtcDashboard;
import com.acmerobotics.dashboard.config.Config;
import com.acmerobotics.dashboard.telemetry.MultipleTelemetry;
import com.acmerobotics.roadrunner.geometry.Pose2d;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.VoltageSensor;
import com.qualcomm.robotcore.util.ElapsedTime;
import org.firstinspires.ftc.robotcore.external.Telemetry;
import org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants;
import org.firstinspires.ftc.teamcode.roadRunner.drive.SampleMecanumDrive;
import java.util.Objects; | 4,182 | package org.firstinspires.ftc.teamcode.roadRunner.drive.opmode;
/**
* This routine is designed to calculate the maximum velocity your bot can achieve under load. It
* will also calculate the effective kF value for your velocity PID.
* <p>
* Upon pressing start, your bot will run at max power for RUNTIME seconds.
* <p>
* Further fine tuning of kF may be desired.
*/
@Config
@Autonomous(group = "drive")
public class MaxVelocityTuner extends LinearOpMode {
public static double RUNTIME = 2.0;
private ElapsedTime timer;
private double maxVelocity = 0.0;
private VoltageSensor batteryVoltageSensor;
@Override
public void runOpMode() throws InterruptedException { | package org.firstinspires.ftc.teamcode.roadRunner.drive.opmode;
/**
* This routine is designed to calculate the maximum velocity your bot can achieve under load. It
* will also calculate the effective kF value for your velocity PID.
* <p>
* Upon pressing start, your bot will run at max power for RUNTIME seconds.
* <p>
* Further fine tuning of kF may be desired.
*/
@Config
@Autonomous(group = "drive")
public class MaxVelocityTuner extends LinearOpMode {
public static double RUNTIME = 2.0;
private ElapsedTime timer;
private double maxVelocity = 0.0;
private VoltageSensor batteryVoltageSensor;
@Override
public void runOpMode() throws InterruptedException { | SampleMecanumDrive drive = new SampleMecanumDrive(hardwareMap); | 1 | 2023-11-06 21:25:54+00:00 | 8k |
project-BarryBarry/coffeeport | src/main/java/com/barrybarry/coffeeport/Main.java | [
{
"identifier": "Config",
"path": "src/main/java/com/barrybarry/coffeeport/constant/Config.java",
"snippet": "@SuppressWarnings({\"FieldCanBeLocal\", \"unused\"})\npublic class Config {\n public static String veraVersion = \"3,8,6,7\";\n public static int httpPort = 16106;\n public static int h... | import com.barrybarry.coffeeport.constant.Config;
import com.barrybarry.coffeeport.handler.TaskHandler;
import com.barrybarry.coffeeport.router.VeraportRouter;
import com.barrybarry.coffeeport.utils.SecurityUtil;
import com.barrybarry.coffeeport.utils.SystemUtil;
import com.linecorp.armeria.server.Server;
import com.linecorp.armeria.server.ServerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.KeyManagerFactory;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.security.KeyStore; | 5,091 | package com.barrybarry.coffeeport;
public class Main {
private static final Logger logger = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) {
TaskHandler th = new TaskHandler();
try {
ServerBuilder sb = Server.builder();
Server server; | package com.barrybarry.coffeeport;
public class Main {
private static final Logger logger = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) {
TaskHandler th = new TaskHandler();
try {
ServerBuilder sb = Server.builder();
Server server; | InetSocketAddress https = new InetSocketAddress(InetAddress.getByName(Config.host), Config.httpsPort); | 0 | 2023-11-08 01:22:24+00:00 | 8k |
celedev97/asa-server-manager | src/main/java/dev/cele/asa_sm/ui/components/server_tab_accordions/RulesAccordion.java | [
{
"identifier": "SpringApplicationContext",
"path": "src/main/java/dev/cele/asa_sm/config/SpringApplicationContext.java",
"snippet": "@Configuration\npublic class SpringApplicationContext implements ApplicationContextAware {\n private static ApplicationContext context;\n\n @Override\n public vo... | import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import com.intellij.uiDesigner.core.Spacer;
import dev.cele.asa_sm.config.SpringApplicationContext;
import dev.cele.asa_sm.dto.AsaServerConfigDto;
import dev.cele.asa_sm.ui.components.AccordionTopBar;
import dev.cele.asa_sm.ui.components.forms.SliderWithText;
import dev.cele.asa_sm.ui.components.forms.TimeField;
import org.springframework.core.env.Environment;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.util.Arrays; | 4,063 | package dev.cele.asa_sm.ui.components.server_tab_accordions;
public class RulesAccordion {
private JCheckBox enableHardcoreModeCheckBox;
private JCheckBox enablePvPCheckBox;
private JCheckBox enableCreativeModeCheckBox;
public JPanel contentPane;
private JCheckBox disablePvEFriendlyFireCheckBox;
private JCheckBox disablePvPFriendlyFireCheckBox;
private JCheckBox preventBuildingInResourceCheckBox;
private JCheckBox enableSignlePlayerSettingsCheckBox;
private JCheckBox enablePvPCaveBuildingCheckBox;
private JCheckBox disableCustomTributeFoldersCheckBox;
private JCheckBox disablePvPRailgunCheckBox;
private JCheckBox enablePveCryoSicknessCheckBox;
private JCheckBox disableSupllyCratesCheckBox;
private JCheckBox allowCratesSpawnOnCheckBox;
private JCheckBox randomSupplyCratesPointsCheckBox;
private JCheckBox useCorpseLocatorCheckBox;
private JCheckBox preventSpawnAnimationsCheckBox;
private JCheckBox allowUnlimitedRespecsCheckBox;
private JCheckBox allowPlatformSaddleMultiCheckBox;
private JCheckBox enableDifficultyOverrideCheckBox;
private JCheckBox enablePvECaveBuildingCheckBox;
private JCheckBox enableTributeDownloadsCheckBox;
private JCheckBox noSurvivorDownloadsCheckBox;
private JCheckBox noItemDownloadsCheckBox;
private JCheckBox noDinoDownloadsCheckBox;
private JCheckBox allowForeignsDinoDownloadsCheckBox;
private JCheckBox noSurvivorUploadsCheckBox;
private JCheckBox noItemUploadsCheckBox;
private JCheckBox noDinoUploadsCheckBox;
private JCheckBox noTransferFromFilteringCheckBox;
private JCheckBox increasePvPRespawnIntervalCheckBox;
private JCheckBox preventOfflinePvPCheckBox;
private JCheckBox enablePvEScheduleCheckBox;
private JCheckBox useServerTimeCheckBox;
private JCheckBox allowTribeAlliancesCheckBox;
private JCheckBox allowTribeWarfareCheckBox;
private JCheckBox allowCancellingTribeWarfareCheckBox;
private JCheckBox allowCustomRecipesCheckBox;
private AsaServerConfigDto configDto;
public RulesAccordion(AsaServerConfigDto configDto) {
this.configDto = configDto;
SwingUtilities.invokeLater(this::afterInit);
}
| package dev.cele.asa_sm.ui.components.server_tab_accordions;
public class RulesAccordion {
private JCheckBox enableHardcoreModeCheckBox;
private JCheckBox enablePvPCheckBox;
private JCheckBox enableCreativeModeCheckBox;
public JPanel contentPane;
private JCheckBox disablePvEFriendlyFireCheckBox;
private JCheckBox disablePvPFriendlyFireCheckBox;
private JCheckBox preventBuildingInResourceCheckBox;
private JCheckBox enableSignlePlayerSettingsCheckBox;
private JCheckBox enablePvPCaveBuildingCheckBox;
private JCheckBox disableCustomTributeFoldersCheckBox;
private JCheckBox disablePvPRailgunCheckBox;
private JCheckBox enablePveCryoSicknessCheckBox;
private JCheckBox disableSupllyCratesCheckBox;
private JCheckBox allowCratesSpawnOnCheckBox;
private JCheckBox randomSupplyCratesPointsCheckBox;
private JCheckBox useCorpseLocatorCheckBox;
private JCheckBox preventSpawnAnimationsCheckBox;
private JCheckBox allowUnlimitedRespecsCheckBox;
private JCheckBox allowPlatformSaddleMultiCheckBox;
private JCheckBox enableDifficultyOverrideCheckBox;
private JCheckBox enablePvECaveBuildingCheckBox;
private JCheckBox enableTributeDownloadsCheckBox;
private JCheckBox noSurvivorDownloadsCheckBox;
private JCheckBox noItemDownloadsCheckBox;
private JCheckBox noDinoDownloadsCheckBox;
private JCheckBox allowForeignsDinoDownloadsCheckBox;
private JCheckBox noSurvivorUploadsCheckBox;
private JCheckBox noItemUploadsCheckBox;
private JCheckBox noDinoUploadsCheckBox;
private JCheckBox noTransferFromFilteringCheckBox;
private JCheckBox increasePvPRespawnIntervalCheckBox;
private JCheckBox preventOfflinePvPCheckBox;
private JCheckBox enablePvEScheduleCheckBox;
private JCheckBox useServerTimeCheckBox;
private JCheckBox allowTribeAlliancesCheckBox;
private JCheckBox allowTribeWarfareCheckBox;
private JCheckBox allowCancellingTribeWarfareCheckBox;
private JCheckBox allowCustomRecipesCheckBox;
private AsaServerConfigDto configDto;
public RulesAccordion(AsaServerConfigDto configDto) {
this.configDto = configDto;
SwingUtilities.invokeLater(this::afterInit);
}
| Environment environment = SpringApplicationContext.autoWire(Environment.class); | 0 | 2023-11-07 19:36:49+00:00 | 8k |
fredpena/barcamp2023 | src/main/java/dev/fredpena/barcamp/views/MainLayout.java | [
{
"identifier": "TenantContext",
"path": "src/main/java/dev/fredpena/barcamp/config/TenantContext.java",
"snippet": "public final class TenantContext {\n\n private TenantContext() {\n }\n\n private static final ThreadLocal<String> currentTenant = new ThreadLocal<>();\n private static final T... | import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.applayout.AppLayout;
import com.vaadin.flow.component.avatar.Avatar;
import com.vaadin.flow.component.contextmenu.MenuItem;
import com.vaadin.flow.component.html.*;
import com.vaadin.flow.component.icon.Icon;
import com.vaadin.flow.component.menubar.MenuBar;
import com.vaadin.flow.router.BeforeEnterEvent;
import com.vaadin.flow.router.BeforeEnterObserver;
import com.vaadin.flow.router.RouterLink;
import com.vaadin.flow.server.StreamResource;
import com.vaadin.flow.server.auth.AccessAnnotationChecker;
import com.vaadin.flow.theme.lumo.LumoUtility.*;
import dev.fredpena.barcamp.config.TenantContext;
import dev.fredpena.barcamp.data.tenant.entity.User;
import dev.fredpena.barcamp.security.AuthenticatedUser;
import dev.fredpena.barcamp.views.person.PersonView;
import org.springframework.util.StringUtils;
import org.vaadin.lineawesome.LineAwesomeIcon;
import java.io.ByteArrayInputStream;
import java.util.Optional; | 4,731 | package dev.fredpena.barcamp.views;
/**
* The main view is a top-level placeholder for other views.
*/
public class MainLayout extends AppLayout implements BeforeEnterObserver {
/**
* A simple navigation item component, based on ListItem element.
*/
public static class MenuItemInfo extends ListItem {
private final Class<? extends Component> view;
public MenuItemInfo(String menuTitle, Component icon, Class<? extends Component> view) {
this.view = view;
RouterLink link = new RouterLink();
// Use Lumo classnames for various styling
link.addClassNames(Display.FLEX, Gap.XSMALL, Height.MEDIUM, AlignItems.CENTER, Padding.Horizontal.SMALL,
TextColor.BODY);
link.setRoute(view);
Span text = new Span(menuTitle);
// Use Lumo classnames for various styling
text.addClassNames(FontWeight.MEDIUM, FontSize.MEDIUM, Whitespace.NOWRAP);
if (icon != null) {
link.add(icon);
}
link.add(text);
add(link);
}
public Class<?> getView() {
return view;
}
}
private final transient AuthenticatedUser authenticatedUser;
private final transient AccessAnnotationChecker accessChecker;
public MainLayout(AuthenticatedUser authenticatedUser, AccessAnnotationChecker accessChecker) {
this.authenticatedUser = authenticatedUser;
this.accessChecker = accessChecker;
addToNavbar(createHeaderContent());
setDrawerOpened(false);
}
private Component createHeaderContent() {
Header header = new Header();
| package dev.fredpena.barcamp.views;
/**
* The main view is a top-level placeholder for other views.
*/
public class MainLayout extends AppLayout implements BeforeEnterObserver {
/**
* A simple navigation item component, based on ListItem element.
*/
public static class MenuItemInfo extends ListItem {
private final Class<? extends Component> view;
public MenuItemInfo(String menuTitle, Component icon, Class<? extends Component> view) {
this.view = view;
RouterLink link = new RouterLink();
// Use Lumo classnames for various styling
link.addClassNames(Display.FLEX, Gap.XSMALL, Height.MEDIUM, AlignItems.CENTER, Padding.Horizontal.SMALL,
TextColor.BODY);
link.setRoute(view);
Span text = new Span(menuTitle);
// Use Lumo classnames for various styling
text.addClassNames(FontWeight.MEDIUM, FontSize.MEDIUM, Whitespace.NOWRAP);
if (icon != null) {
link.add(icon);
}
link.add(text);
add(link);
}
public Class<?> getView() {
return view;
}
}
private final transient AuthenticatedUser authenticatedUser;
private final transient AccessAnnotationChecker accessChecker;
public MainLayout(AuthenticatedUser authenticatedUser, AccessAnnotationChecker accessChecker) {
this.authenticatedUser = authenticatedUser;
this.accessChecker = accessChecker;
addToNavbar(createHeaderContent());
setDrawerOpened(false);
}
private Component createHeaderContent() {
Header header = new Header();
| if (StringUtils.hasText(TenantContext.getCurrentTenant())) { | 0 | 2023-11-08 18:12:12+00:00 | 8k |
1341191074/aibote4j | sdk-core/src/main/java/net/aibote/sdk/WinBot.java | [
{
"identifier": "OCRResult",
"path": "sdk-core/src/main/java/net/aibote/sdk/dto/OCRResult.java",
"snippet": "public class OCRResult {\n public Point lt;\n public Point rt;\n public Point ld;\n public Point rd;\n public String word;\n public double rate;\n}"
},
{
"identifier": "... | import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.Data;
import lombok.EqualsAndHashCode;
import net.aibote.sdk.dto.OCRResult;
import net.aibote.sdk.dto.Point;
import net.aibote.sdk.options.Mode;
import net.aibote.sdk.options.Region;
import net.aibote.sdk.options.SubColor;
import net.aibote.utils.HttpClientUtils;
import net.aibote.utils.ImageBase64Converter;
import org.apache.commons.lang3.StringUtils;
import java.util.*; | 5,914 | package net.aibote.sdk;
@EqualsAndHashCode(callSuper = true)
@Data
public abstract class WinBot extends Aibote {
/**
* 查找窗口句柄
*
* @param className 窗口类名
* @param windowName 窗口名
* @return String 成功返回窗口句柄,失败返回null
*/
public String findWindow(String className, String windowName) {
return strCmd("findWindow", className, windowName);
}
/**
* 查找窗口句柄数组, 以 “|” 分割
*
* @param className 窗口类名
* @param windowName 窗口名
* @return String 成功返回窗口句柄,失败返回null
*/
public String findWindows(String className, String windowName) {
return strCmd("findWindows", className, windowName);
}
/**
* 查找窗口句柄
*
* @param curHwnd 当前窗口句柄
* @param className 窗口类名
* @param windowName 窗口名
* @return String 成功返回窗口句柄,失败返回null
*/
public String findSubWindow(String curHwnd, String className, String windowName) {
return strCmd("findSubWindow", curHwnd, className, windowName);
}
/**
* 查找父窗口句柄
*
* @param curHwnd 当前窗口句柄
* @return String 成功返回窗口句柄,失败返回null
*/
public String findParentWindow(String curHwnd) {
return strCmd("findParentWindow", curHwnd);
}
/**
* 查找桌面窗口句柄
*
* @return 成功返回窗口句柄,失败返回null
*/
public String findDesktopWindow() {
return strCmd("findDesktopWindow");
}
/**
* 获取窗口名称
*
* @param hwnd 当前窗口句柄
* @return String 成功返回窗口句柄,失败返回null
*/
public String getWindowName(String hwnd) {
return strCmd("getWindowName", hwnd);
}
/**
* 显示/隐藏窗口
*
* @param hwnd 当前窗口句柄
* @param isShow 是否显示
* @return boolean 成功返回true,失败返回false
*/
public boolean showWindow(String hwnd, boolean isShow) {
return boolCmd("showWindow", hwnd, String.valueOf(isShow));
}
/**
* 显示/隐藏窗口
*
* @param hwnd 当前窗口句柄
* @param isTop 是否置顶
* @return boolean 成功返回true,失败返回false
*/
public boolean setWindowTop(String hwnd, boolean isTop) {
return boolCmd("setWindowTop", hwnd, String.valueOf(isTop));
}
/**
* 获取窗口位置。 用“|”分割
*
* @param hwnd 当前窗口句柄
* @return 0|0|0|0
*/
public String getWindowPos(String hwnd) {
return strCmd("getWindowPos", hwnd);
}
/**
* 设置窗口位置
*
* @param hwnd 当前窗口句柄
* @param left 左上角横坐标
* @param top 左上角纵坐标
* @param width width 窗口宽度
* @param height height 窗口高度
* @return boolean 成功返回true 失败返回 false
*/
public boolean setWindowPos(String hwnd, int left, int top, int width, int height) {
return boolCmd("setWindowPos", hwnd, Integer.toString(left), Integer.toString(top), Integer.toString(width), Integer.toString(height));
}
/**
* 移动鼠标 <br />
* 如果mode值为true且目标控件有单独的句柄,则需要通过getElementWindow获得元素句柄,指定elementHwnd的值(极少应用窗口由父窗口响应消息,则无需指定)
*
* @param hwnd 窗口句柄
* @param x 横坐标
* @param y 纵坐标
* @param mode 操作模式,后台 true,前台 false。默认前台操作。
* @param elementHwnd 元素句柄
* @return boolean 总是返回true
*/
public boolean moveMouse(String hwnd, int x, int y, Mode mode, String elementHwnd) {
return boolCmd("moveMouse", hwnd, Integer.toString(x), Integer.toString(y), mode.boolValueStr(), elementHwnd);
}
/**
* 移动鼠标(相对坐标)
*
* @param hwnd 窗口句柄
* @param x 相对横坐标
* @param y 相对纵坐标
* @param mode 操作模式,后台 true,前台 false。默认前台操作
* @return boolean 总是返回true
*/
public boolean moveMouseRelative(String hwnd, int x, int y, Mode mode) {
return boolCmd("moveMouseRelative", hwnd, Integer.toString(x), Integer.toString(y), mode.boolValueStr());
}
/**
* 滚动鼠标
*
* @param hwnd 窗口句柄
* @param x 横坐标
* @param y 纵坐标
* @param dwData 鼠标滚动次数,负数下滚鼠标,正数上滚鼠标
* @param mode 操作模式,后台 true,前台 false。默认前台操作
* @return boolean 总是返回true
*/
public boolean rollMouse(String hwnd, int x, int y, int dwData, Mode mode) {
return boolCmd("rollMouse", hwnd, Integer.toString(x), Integer.toString(y), Integer.toString(dwData), mode.boolValueStr());
}
/**
* 鼠标点击<br />
* 如果mode值为true且目标控件有单独的句柄,则需要通过getElementWindow获得元素句柄,指定elementHwnd的值(极少应用窗口由父窗口响应消息,则无需指定)
*
* @param hwnd 窗口句柄
* @param x 横坐标
* @param y 纵坐标
* @param mouseType 单击左键:1 单击右键:2 按下左键:3 弹起左键:4 按下右键:5 弹起右键:6 双击左键:7 双击右键:8
* @param mode 操作模式,后台 true,前台 false。默认前台操作。
* @param elementHwnd 元素句柄
* @return boolean 总是返回true。
*/
public boolean clickMouse(String hwnd, int x, int y, int mouseType, Mode mode, String elementHwnd) {
return boolCmd("clickMouse", hwnd, Integer.toString(x), Integer.toString(y), Integer.toString(mouseType), mode.boolValueStr(), elementHwnd);
}
/**
* 输入文本
*
* @param txt 输入的文本
* @return boolean 总是返回true
*/
public boolean sendKeys(String txt) {
return boolCmd("sendKeys", txt);
}
/**
* 后台输入文本
*
* @param hwnd 窗口句柄,如果目标控件有单独的句柄,需要通过getElementWindow获得句柄
* @param txt 输入的文本
* @return boolean 总是返回true
*/
public boolean sendKeysByHwnd(String hwnd, String txt) {
return boolCmd("sendKeysByHwnd", hwnd, txt);
}
/**
* 输入虚拟键值(VK)
*
* @param vk VK键值,例如:回车对应 VK键值 13
* @param keyState 按下弹起:1 按下:2 弹起:3
* @return boolean 总是返回true
*/
public boolean sendVk(int vk, int keyState) {
return boolCmd("sendVk", Integer.toString(vk), Integer.toString(keyState));
}
/**
* 后台输入虚拟键值(VK)
*
* @param hwnd 窗口句柄,如果目标控件有单独的句柄,需要通过getElementWindow获得句柄
* @param vk VK键值,例如:回车对应 VK键值 13
* @param keyState 按下弹起:1 按下:2 弹起:3
* @return boolean 总是返回true
*/
public boolean sendVkByHwnd(String hwnd, int vk, int keyState) {
return boolCmd("sendVkByHwnd", hwnd, Integer.toString(vk), Integer.toString(keyState));
}
/**
* 截图保存。threshold默认保存原图。
*
* @param hwnd 窗口句柄
* @param savePath 保存的位置
* @param region 区域
* @param thresholdType hresholdType算法类型。<br />
* 0 THRESH_BINARY算法,当前点值大于阈值thresh时,取最大值maxva,否则设置为0
* 1 THRESH_BINARY_INV算法,当前点值大于阈值thresh时,设置为0,否则设置为最大值maxva
* 2 THRESH_TOZERO算法,当前点值大于阈值thresh时,不改变,否则设置为0
* 3 THRESH_TOZERO_INV算法,当前点值大于阈值thresh时,设置为0,否则不改变
* 4 THRESH_TRUNC算法,当前点值大于阈值thresh时,设置为阈值thresh,否则不改变
* 5 ADAPTIVE_THRESH_MEAN_C算法,自适应阈值
* 6 ADAPTIVE_THRESH_GAUSSIAN_C算法,自适应阈值
* @param thresh 阈值。 thresh和maxval同为255时灰度处理
* @param maxval 最大值。 thresh和maxval同为255时灰度处理
* @return boolean
*/ | package net.aibote.sdk;
@EqualsAndHashCode(callSuper = true)
@Data
public abstract class WinBot extends Aibote {
/**
* 查找窗口句柄
*
* @param className 窗口类名
* @param windowName 窗口名
* @return String 成功返回窗口句柄,失败返回null
*/
public String findWindow(String className, String windowName) {
return strCmd("findWindow", className, windowName);
}
/**
* 查找窗口句柄数组, 以 “|” 分割
*
* @param className 窗口类名
* @param windowName 窗口名
* @return String 成功返回窗口句柄,失败返回null
*/
public String findWindows(String className, String windowName) {
return strCmd("findWindows", className, windowName);
}
/**
* 查找窗口句柄
*
* @param curHwnd 当前窗口句柄
* @param className 窗口类名
* @param windowName 窗口名
* @return String 成功返回窗口句柄,失败返回null
*/
public String findSubWindow(String curHwnd, String className, String windowName) {
return strCmd("findSubWindow", curHwnd, className, windowName);
}
/**
* 查找父窗口句柄
*
* @param curHwnd 当前窗口句柄
* @return String 成功返回窗口句柄,失败返回null
*/
public String findParentWindow(String curHwnd) {
return strCmd("findParentWindow", curHwnd);
}
/**
* 查找桌面窗口句柄
*
* @return 成功返回窗口句柄,失败返回null
*/
public String findDesktopWindow() {
return strCmd("findDesktopWindow");
}
/**
* 获取窗口名称
*
* @param hwnd 当前窗口句柄
* @return String 成功返回窗口句柄,失败返回null
*/
public String getWindowName(String hwnd) {
return strCmd("getWindowName", hwnd);
}
/**
* 显示/隐藏窗口
*
* @param hwnd 当前窗口句柄
* @param isShow 是否显示
* @return boolean 成功返回true,失败返回false
*/
public boolean showWindow(String hwnd, boolean isShow) {
return boolCmd("showWindow", hwnd, String.valueOf(isShow));
}
/**
* 显示/隐藏窗口
*
* @param hwnd 当前窗口句柄
* @param isTop 是否置顶
* @return boolean 成功返回true,失败返回false
*/
public boolean setWindowTop(String hwnd, boolean isTop) {
return boolCmd("setWindowTop", hwnd, String.valueOf(isTop));
}
/**
* 获取窗口位置。 用“|”分割
*
* @param hwnd 当前窗口句柄
* @return 0|0|0|0
*/
public String getWindowPos(String hwnd) {
return strCmd("getWindowPos", hwnd);
}
/**
* 设置窗口位置
*
* @param hwnd 当前窗口句柄
* @param left 左上角横坐标
* @param top 左上角纵坐标
* @param width width 窗口宽度
* @param height height 窗口高度
* @return boolean 成功返回true 失败返回 false
*/
public boolean setWindowPos(String hwnd, int left, int top, int width, int height) {
return boolCmd("setWindowPos", hwnd, Integer.toString(left), Integer.toString(top), Integer.toString(width), Integer.toString(height));
}
/**
* 移动鼠标 <br />
* 如果mode值为true且目标控件有单独的句柄,则需要通过getElementWindow获得元素句柄,指定elementHwnd的值(极少应用窗口由父窗口响应消息,则无需指定)
*
* @param hwnd 窗口句柄
* @param x 横坐标
* @param y 纵坐标
* @param mode 操作模式,后台 true,前台 false。默认前台操作。
* @param elementHwnd 元素句柄
* @return boolean 总是返回true
*/
public boolean moveMouse(String hwnd, int x, int y, Mode mode, String elementHwnd) {
return boolCmd("moveMouse", hwnd, Integer.toString(x), Integer.toString(y), mode.boolValueStr(), elementHwnd);
}
/**
* 移动鼠标(相对坐标)
*
* @param hwnd 窗口句柄
* @param x 相对横坐标
* @param y 相对纵坐标
* @param mode 操作模式,后台 true,前台 false。默认前台操作
* @return boolean 总是返回true
*/
public boolean moveMouseRelative(String hwnd, int x, int y, Mode mode) {
return boolCmd("moveMouseRelative", hwnd, Integer.toString(x), Integer.toString(y), mode.boolValueStr());
}
/**
* 滚动鼠标
*
* @param hwnd 窗口句柄
* @param x 横坐标
* @param y 纵坐标
* @param dwData 鼠标滚动次数,负数下滚鼠标,正数上滚鼠标
* @param mode 操作模式,后台 true,前台 false。默认前台操作
* @return boolean 总是返回true
*/
public boolean rollMouse(String hwnd, int x, int y, int dwData, Mode mode) {
return boolCmd("rollMouse", hwnd, Integer.toString(x), Integer.toString(y), Integer.toString(dwData), mode.boolValueStr());
}
/**
* 鼠标点击<br />
* 如果mode值为true且目标控件有单独的句柄,则需要通过getElementWindow获得元素句柄,指定elementHwnd的值(极少应用窗口由父窗口响应消息,则无需指定)
*
* @param hwnd 窗口句柄
* @param x 横坐标
* @param y 纵坐标
* @param mouseType 单击左键:1 单击右键:2 按下左键:3 弹起左键:4 按下右键:5 弹起右键:6 双击左键:7 双击右键:8
* @param mode 操作模式,后台 true,前台 false。默认前台操作。
* @param elementHwnd 元素句柄
* @return boolean 总是返回true。
*/
public boolean clickMouse(String hwnd, int x, int y, int mouseType, Mode mode, String elementHwnd) {
return boolCmd("clickMouse", hwnd, Integer.toString(x), Integer.toString(y), Integer.toString(mouseType), mode.boolValueStr(), elementHwnd);
}
/**
* 输入文本
*
* @param txt 输入的文本
* @return boolean 总是返回true
*/
public boolean sendKeys(String txt) {
return boolCmd("sendKeys", txt);
}
/**
* 后台输入文本
*
* @param hwnd 窗口句柄,如果目标控件有单独的句柄,需要通过getElementWindow获得句柄
* @param txt 输入的文本
* @return boolean 总是返回true
*/
public boolean sendKeysByHwnd(String hwnd, String txt) {
return boolCmd("sendKeysByHwnd", hwnd, txt);
}
/**
* 输入虚拟键值(VK)
*
* @param vk VK键值,例如:回车对应 VK键值 13
* @param keyState 按下弹起:1 按下:2 弹起:3
* @return boolean 总是返回true
*/
public boolean sendVk(int vk, int keyState) {
return boolCmd("sendVk", Integer.toString(vk), Integer.toString(keyState));
}
/**
* 后台输入虚拟键值(VK)
*
* @param hwnd 窗口句柄,如果目标控件有单独的句柄,需要通过getElementWindow获得句柄
* @param vk VK键值,例如:回车对应 VK键值 13
* @param keyState 按下弹起:1 按下:2 弹起:3
* @return boolean 总是返回true
*/
public boolean sendVkByHwnd(String hwnd, int vk, int keyState) {
return boolCmd("sendVkByHwnd", hwnd, Integer.toString(vk), Integer.toString(keyState));
}
/**
* 截图保存。threshold默认保存原图。
*
* @param hwnd 窗口句柄
* @param savePath 保存的位置
* @param region 区域
* @param thresholdType hresholdType算法类型。<br />
* 0 THRESH_BINARY算法,当前点值大于阈值thresh时,取最大值maxva,否则设置为0
* 1 THRESH_BINARY_INV算法,当前点值大于阈值thresh时,设置为0,否则设置为最大值maxva
* 2 THRESH_TOZERO算法,当前点值大于阈值thresh时,不改变,否则设置为0
* 3 THRESH_TOZERO_INV算法,当前点值大于阈值thresh时,设置为0,否则不改变
* 4 THRESH_TRUNC算法,当前点值大于阈值thresh时,设置为阈值thresh,否则不改变
* 5 ADAPTIVE_THRESH_MEAN_C算法,自适应阈值
* 6 ADAPTIVE_THRESH_GAUSSIAN_C算法,自适应阈值
* @param thresh 阈值。 thresh和maxval同为255时灰度处理
* @param maxval 最大值。 thresh和maxval同为255时灰度处理
* @return boolean
*/ | public boolean saveScreenshot(String hwnd, String savePath, Region region, int thresholdType, int thresh, int maxval) { | 3 | 2023-11-08 14:31:58+00:00 | 8k |
wuyu-wy/mgzm_volunteer | volunteer/src/main/java/com/blbd/volunteer/controller/ChatFriendController.java | [
{
"identifier": "ChatFriendListEntity",
"path": "volunteer/src/main/java/com/blbd/volunteer/dao/entity/ChatFriendListEntity.java",
"snippet": "@Data\npublic class ChatFriendListEntity implements Serializable {\n /**\n * 聊天列表主键\n */\n private Integer listId;\n\n /**\n * 聊天主表id\n ... | import com.blbd.volunteer.dao.entity.ChatFriendListEntity;
import com.blbd.volunteer.dao.entity.ChatLinkEntity;
import com.blbd.volunteer.dao.entity.ChatMsgEntity;
import com.blbd.volunteer.dao.entity.LogEntity;
import com.blbd.volunteer.service.ChatFriendListService;
import com.blbd.volunteer.service.ChatLinkService;
import com.blbd.volunteer.service.ChatMsgService;
import com.blbd.volunteer.utils.HttpResponseEntity;
import com.blbd.volunteer.utils.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List; | 4,057 | package com.blbd.volunteer.controller;
@CrossOrigin("*")
@RestController
@RequestMapping("/ChatFriend")
public class ChatFriendController {
@Autowired
ChatFriendListService chatFriendListService;
@Autowired
ChatLinkService chatLinkService;
/**
* 添加好友
* @param chatFriendListEntity
* @return
*/
@PostMapping(value = "/addFriend", headers = "Accept=application/json")
public HttpResponseEntity addFriend(@RequestBody ChatFriendListEntity chatFriendListEntity){
ChatLinkEntity chatLinkEntity = new ChatLinkEntity();
chatLinkEntity.setSenderId(chatFriendListEntity.getSenderId());
chatLinkEntity.setReceiverId(chatFriendListEntity.getReceiverId()); | package com.blbd.volunteer.controller;
@CrossOrigin("*")
@RestController
@RequestMapping("/ChatFriend")
public class ChatFriendController {
@Autowired
ChatFriendListService chatFriendListService;
@Autowired
ChatLinkService chatLinkService;
/**
* 添加好友
* @param chatFriendListEntity
* @return
*/
@PostMapping(value = "/addFriend", headers = "Accept=application/json")
public HttpResponseEntity addFriend(@RequestBody ChatFriendListEntity chatFriendListEntity){
ChatLinkEntity chatLinkEntity = new ChatLinkEntity();
chatLinkEntity.setSenderId(chatFriendListEntity.getSenderId());
chatLinkEntity.setReceiverId(chatFriendListEntity.getReceiverId()); | chatLinkEntity.setLinkId(UUIDUtil.getOneUUID()); | 8 | 2023-11-02 05:55:45+00:00 | 8k |
SeanPesce/AWS-IoT-Recon | src/main/java/com/seanpesce/aws/iot/AwsIotRecon.java | [
{
"identifier": "AwsIotConstants",
"path": "src/main/java/com/seanpesce/aws/iot/AwsIotConstants.java",
"snippet": "public class AwsIotConstants {\n\n public static final String PROJECT_TITLE = \"[AWS IoT Core Enumeration Tool by Sean Pesce]\";\n\n public static final String ACTION_MQTT_DUMP = \"mq... | import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.security.cert.CertificateException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import com.seanpesce.aws.iot.AwsIotConstants;
import com.seanpesce.http.MtlsHttpClient;
import com.seanpesce.mqtt.MqttScript;
import com.seanpesce.regex.PatternWithNamedGroups;
import com.seanpesce.Util;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import software.amazon.awssdk.crt.auth.credentials.Credentials;
import software.amazon.awssdk.crt.auth.credentials.X509CredentialsProvider;
import software.amazon.awssdk.crt.CRT;
import software.amazon.awssdk.crt.io.ClientTlsContext;
import software.amazon.awssdk.crt.io.TlsContextOptions;
import software.amazon.awssdk.crt.mqtt.MqttClientConnection;
import software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents;
import software.amazon.awssdk.crt.mqtt.MqttMessage;
import software.amazon.awssdk.crt.mqtt.QualityOfService;
import software.amazon.awssdk.crt.mqtt5.Mqtt5Client;
import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder; | 6,748 | // Author: Sean Pesce
//
// References:
// https://aws.github.io/aws-iot-device-sdk-java-v2/
// https://docs.aws.amazon.com/iot/latest/developerguide
// https://github.com/aws/aws-iot-device-sdk-java-v2/blob/main/samples/
// https://explore.skillbuilder.aws/learn/course/external/view/elearning/5667/deep-dive-into-aws-iot-authentication-and-authorization
//
// @TODO:
// - Re-architect this tool to be more object-oriented (e.g., fewer static/global variables)
// - Use CountDownLatch(count) in subscription message handlers for improved reliability
package com.seanpesce.aws.iot;
// import software.amazon.awssdk.services.iotdataplane.IotDataPlaneClient;
public class AwsIotRecon {
// MQTT topics to subscribe to (if empty, defaults to "#" - all topics)
public static ArrayList<String> topicSubcriptions = new ArrayList<String>();
// Regular expressions with named capture groups for harvesting fields from MQTT topics | // Author: Sean Pesce
//
// References:
// https://aws.github.io/aws-iot-device-sdk-java-v2/
// https://docs.aws.amazon.com/iot/latest/developerguide
// https://github.com/aws/aws-iot-device-sdk-java-v2/blob/main/samples/
// https://explore.skillbuilder.aws/learn/course/external/view/elearning/5667/deep-dive-into-aws-iot-authentication-and-authorization
//
// @TODO:
// - Re-architect this tool to be more object-oriented (e.g., fewer static/global variables)
// - Use CountDownLatch(count) in subscription message handlers for improved reliability
package com.seanpesce.aws.iot;
// import software.amazon.awssdk.services.iotdataplane.IotDataPlaneClient;
public class AwsIotRecon {
// MQTT topics to subscribe to (if empty, defaults to "#" - all topics)
public static ArrayList<String> topicSubcriptions = new ArrayList<String>();
// Regular expressions with named capture groups for harvesting fields from MQTT topics | public static ArrayList<PatternWithNamedGroups> topicsRegex = new ArrayList<PatternWithNamedGroups>(Arrays.asList(AwsIotConstants.RESERVED_TOPICS_REGEX)); | 0 | 2023-11-06 23:10:21+00:00 | 8k |
baguchan/BetterWithAquatic | src/main/java/baguchan/better_with_aquatic/entity/render/FrogModel.java | [
{
"identifier": "EntityFrog",
"path": "src/main/java/baguchan/better_with_aquatic/entity/EntityFrog.java",
"snippet": "public class EntityFrog extends EntityAnimal implements IPathGetter, ISwiming {\n\tprivate Entity currentTarget;\n\tpublic boolean swimming;\n\tprivate int frogJumpDelay = 0;\n\n\tpubli... | import baguchan.better_with_aquatic.entity.EntityFrog;
import net.minecraft.core.entity.EntityLiving;
import net.minecraft.core.util.helper.MathHelper;
import useless.dragonfly.helper.AnimationHelper;
import useless.dragonfly.model.entity.BenchEntityModel;
import useless.dragonfly.model.entity.animation.Animation;
import static baguchan.better_with_aquatic.BetterWithAquatic.MOD_ID; | 4,209 | package baguchan.better_with_aquatic.entity.render;
public class FrogModel extends BenchEntityModel {
private static EntityFrog frog;
@Override
public void setLivingAnimations(EntityLiving entityliving, float limbSwing, float limbYaw, float renderPartialTicks) {
super.setLivingAnimations(entityliving, limbSwing, limbYaw, renderPartialTicks);
if (entityliving instanceof EntityFrog) {
frog = (EntityFrog) entityliving;
}
}
@Override
public void setRotationAngles(float limbSwing, float limbYaw, float ticksExisted, float headYaw, float headPitch, float scale) {
this.getIndexBones().forEach((s, benchEntityBones) -> {
benchEntityBones.resetPose();
});
super.setRotationAngles(limbSwing, limbYaw, ticksExisted, headYaw, headPitch, scale); | package baguchan.better_with_aquatic.entity.render;
public class FrogModel extends BenchEntityModel {
private static EntityFrog frog;
@Override
public void setLivingAnimations(EntityLiving entityliving, float limbSwing, float limbYaw, float renderPartialTicks) {
super.setLivingAnimations(entityliving, limbSwing, limbYaw, renderPartialTicks);
if (entityliving instanceof EntityFrog) {
frog = (EntityFrog) entityliving;
}
}
@Override
public void setRotationAngles(float limbSwing, float limbYaw, float ticksExisted, float headYaw, float headPitch, float scale) {
this.getIndexBones().forEach((s, benchEntityBones) -> {
benchEntityBones.resetPose();
});
super.setRotationAngles(limbSwing, limbYaw, ticksExisted, headYaw, headPitch, scale); | Animation testAnimation = AnimationHelper.getOrCreateEntityAnimation(MOD_ID, "frog.animation"); | 1 | 2023-11-08 23:02:14+00:00 | 8k |
By1337/BAuction | Core/src/main/java/org/by1337/bauction/util/Sorting.java | [
{
"identifier": "SellItem",
"path": "BaucApi/src/main/java/org/by1337/bauction/auc/SellItem.java",
"snippet": "public interface SellItem extends Placeholderable, SerializableToByteArray {\n\n /**\n * Get the item available for sale as an ItemStack.\n *\n * @return ItemStack representing t... | import org.by1337.api.util.NameKey;
import org.by1337.bauction.auc.SellItem;
import org.by1337.bauction.db.kernel.CSellItem;
import org.jetbrains.annotations.NotNull;
import java.util.Comparator;
import java.util.Objects; | 5,734 | package org.by1337.bauction.util;
public record Sorting(SortingType type, String value, String selectedName,
String unselectedName, int priority, NameKey nameKey) implements Comparable<Sorting> {
@Override
public int compareTo(@NotNull Sorting o) {
return Integer.compare(priority, o.priority());
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Sorting sorting)) return false;
return priority == sorting.priority && type == sorting.type && Objects.equals(value, sorting.value) && Objects.equals(selectedName, sorting.selectedName) && Objects.equals(unselectedName, sorting.unselectedName) && Objects.equals(nameKey, sorting.nameKey);
}
@Override
public int hashCode() {
return Objects.hash(type, value, selectedName, unselectedName, priority, nameKey);
}
@Override
public String toString() {
return "Sorting{" +
"type=" + type +
", value='" + value + '\'' +
", selectedName='" + selectedName + '\'' +
", unselectedName='" + unselectedName + '\'' +
", priority=" + priority +
'}';
}
| package org.by1337.bauction.util;
public record Sorting(SortingType type, String value, String selectedName,
String unselectedName, int priority, NameKey nameKey) implements Comparable<Sorting> {
@Override
public int compareTo(@NotNull Sorting o) {
return Integer.compare(priority, o.priority());
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Sorting sorting)) return false;
return priority == sorting.priority && type == sorting.type && Objects.equals(value, sorting.value) && Objects.equals(selectedName, sorting.selectedName) && Objects.equals(unselectedName, sorting.unselectedName) && Objects.equals(nameKey, sorting.nameKey);
}
@Override
public int hashCode() {
return Objects.hash(type, value, selectedName, unselectedName, priority, nameKey);
}
@Override
public String toString() {
return "Sorting{" +
"type=" + type +
", value='" + value + '\'' +
", selectedName='" + selectedName + '\'' +
", unselectedName='" + unselectedName + '\'' +
", priority=" + priority +
'}';
}
| public Comparator<SellItem> getComparator(){ | 0 | 2023-11-08 18:25:18+00:00 | 8k |
Svydovets-Bobocode-Java-Ultimate-3-0/Bring | src/test/java/com/bobocode/svydovets/ioc/core/context/ApplicationContextTest.java | [
{
"identifier": "TrimService",
"path": "src/test/java/com/bobocode/svydovets/source/autowire/method/TrimService.java",
"snippet": "public class TrimService {\n private CommonService commonService;\n\n public CommonService getCommonService() {\n return commonService;\n }\n\n @Autowired... | import com.bobocode.svydovets.source.autowire.method.TrimService;
import com.bobocode.svydovets.source.base.CommonService;
import com.bobocode.svydovets.source.base.MessageService;
import com.bobocode.svydovets.source.base.NullService;
import com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface.InjCandidate;
import com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface.InjFirstCandidate;
import com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface.InjFirstPrototypeCandidate;
import com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface.InjPrototypeCandidate;
import com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface.PrototypeCandidate;
import com.bobocode.svydovets.source.beanFactoryTest.throwPrototypeCandidateByInterfaceMoreOnePrimary.InjPrototypeCandidateMoreOnePrimary;
import com.bobocode.svydovets.source.beanFactoryTest.throwPrototypeCandidateByInterfaceWithoutPrimary.InjPrototypeCandidateWithoutPrimary;
import com.bobocode.svydovets.source.config.BasePackageBeansConfig;
import com.bobocode.svydovets.source.config.PrimaryPackageBeansConfig;
import com.bobocode.svydovets.source.config.QualifierPackageBeansConfig;
import com.bobocode.svydovets.source.primary.PrimaryService;
import com.bobocode.svydovets.source.qualifier.valid.GroceryItem;
import com.bobocode.svydovets.source.qualifier.valid.OrderService;
import com.bobocode.svydovets.source.qualifier.valid.StoreItem;
import com.bobocode.svydovets.source.qualifier.withoutPrimary.PaymentService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import svydovets.core.context.AnnotationConfigApplicationContext;
import svydovets.core.context.ApplicationContext;
import svydovets.core.exception.NoSuchBeanDefinitionException;
import svydovets.core.exception.NoUniqueBeanDefinitionException;
import svydovets.core.exception.NoUniqueBeanException;
import java.util.Map;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType;
import static org.junit.jupiter.api.Assertions.*;
import static svydovets.util.ErrorMessageConstants.NO_BEAN_DEFINITION_FOUND_OF_TYPE;
import static svydovets.util.ErrorMessageConstants.NO_UNIQUE_BEAN_DEFINITION_FOUND_OF_TYPE;
import static svydovets.util.ErrorMessageConstants.NO_UNIQUE_BEAN_FOUND_OF_TYPE; | 5,125 | PrimaryService.class.getName())
);
}
@Test
@Order(11)
void shouldReturnBeanByNameAndClassIfTwoPrimaryBeansArePresent() {
ApplicationContext context = new AnnotationConfigApplicationContext(PrimaryPackageBeansConfig.class);
PrimaryService firstPrimaryServiceImpl = context.getBean("firstPrimaryServiceImpl", PrimaryService.class);
assertThat(firstPrimaryServiceImpl).isNotNull();
}
@Test
@Order(12)
void shouldGetAllRegistersBeansWithoutPrototype() {
ApplicationContext context = new AnnotationConfigApplicationContext("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface");
Map<String, Object> beans = context.getBeans();
assertEquals(2, beans.size());
assertTrue(beans.containsKey("injFirstCandidate"));
assertTrue(beans.containsKey("injSecondCandidate"));
}
@Test
@Order(13)
void shouldGetPrimaryCandidateByClasTypeForInterface() {
ApplicationContext context = new AnnotationConfigApplicationContext("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface");
Map<String, Object> beans = context.getBeans();
var bean = context.getBean(InjCandidate.class);
assertEquals(bean, beans.get("injSecondCandidate"));
}
@Test
@Order(14)
void shouldGetPrimaryCandidateByClasTypeAndNameForInterface() {
ApplicationContext context = new AnnotationConfigApplicationContext("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface");
Map<String, Object> beans = context.getBeans();
var bean = context.getBean("injSecondCandidate", InjCandidate.class);
assertEquals(bean, beans.get("injSecondCandidate"));
}
@Test
@Order(15)
void shouldGetPrototypeCandidateByClasType() {
ApplicationContext context = new AnnotationConfigApplicationContext("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface");
var bean1 = context.getBean(PrototypeCandidate.class);
var bean2 = context.getBean(PrototypeCandidate.class);
assertNotEquals(bean1, bean2);
}
@Test
@Order(16)
void shouldGetPrototypeCandidateByClasTypeAndName() {
ApplicationContext context = new AnnotationConfigApplicationContext("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface");
var bean1 = context.getBean("prototypeCandidate", PrototypeCandidate.class);
var bean2 = context.getBean("prototypeCandidate", PrototypeCandidate.class);
assertNotEquals(bean1, bean2);
}
@Test
@Order(17)
void shouldThrowNoSuchBeanDefinitionExceptionGetPrototypeCandidateByClasTypeAndName() {
ApplicationContext context = new AnnotationConfigApplicationContext("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface");
String errorMessageFormat = "No bean definition found of type %s";
String errorMessage = String.format(errorMessageFormat, PrototypeCandidate.class.getName());
var exception = assertThrows(NoSuchBeanDefinitionException.class,
() -> context.getBean("prototypeSecondCandidate", PrototypeCandidate.class));
assertEquals(errorMessage, exception.getMessage());
errorMessageFormat = "No bean definition found of type %s";
errorMessage = String.format(errorMessageFormat, InjFirstCandidate.class.getName());
exception = assertThrows(NoSuchBeanDefinitionException.class,
() -> context.getBean("prototypeSecondCandidate", InjFirstCandidate.class));
assertEquals(errorMessage, exception.getMessage());
}
@Test
@Order(18)
void shouldGetBeansOfTypeByRequiredType() {
ApplicationContext context = new AnnotationConfigApplicationContext("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface");
var expectedBeanMap = context.getBeans();
var actualBeanMap = context.getBeansOfType(InjCandidate.class);
assertEquals(expectedBeanMap.size(), actualBeanMap.size());
assertEquals(expectedBeanMap.get("injFirstCandidate"), actualBeanMap.get("injFirstCandidate"));
assertEquals(expectedBeanMap.get("injSecondCandidate"), actualBeanMap.get("injSecondCandidate"));
}
@Test
@Order(19)
void shouldGetPrototypeBeanOfTypeByRequiredTypeAndName() {
ApplicationContext context = new AnnotationConfigApplicationContext("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface");
var actualBean = context.getBean("injFirstPrototypeCandidate", InjFirstPrototypeCandidate.class);
assertEquals(InjFirstPrototypeCandidate.class, actualBean.getClass());
}
@Test
@Order(20)
void shouldGetPrototypeBeanOfTypeByRequiredTypeAndName1() {
ApplicationContext context = new AnnotationConfigApplicationContext("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface");
var actualBean = context.getBean(InjPrototypeCandidate.class);
assertEquals(InjFirstPrototypeCandidate.class, actualBean.getClass());
}
@Test
@Order(21)
void shouldThrowNoSuchBeanDefinitionExceptionWhenGetPrototypeBeanOfTypeWithoutPrimaryByRequiredType() {
ApplicationContext context = new AnnotationConfigApplicationContext("com.bobocode.svydovets.source.beanFactoryTest.throwPrototypeCandidateByInterfaceWithoutPrimary");
String message = String.format(NO_BEAN_DEFINITION_FOUND_OF_TYPE, InjPrototypeCandidateWithoutPrimary.class.getName());
assertThatExceptionOfType(NoSuchBeanDefinitionException.class)
.isThrownBy(() -> context.getBean(InjPrototypeCandidateWithoutPrimary.class))
.withMessage(message);
}
@Test
@Order(22)
void shouldThrowNoUniqueBeanDefinitionExceptionWhenGetPrototypeBeanOfTypeMoreOnePrimaryByRequiredType() {
ApplicationContext context = new AnnotationConfigApplicationContext("com.bobocode.svydovets.source.beanFactoryTest.throwPrototypeCandidateByInterfaceMoreOnePrimary"); | package com.bobocode.svydovets.ioc.core.context;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class ApplicationContextTest {
@BeforeEach
void setUp() {
}
@Test
@Order(1)
void shouldCreateApplicationContextFromBasePackage() {
ApplicationContext context = new AnnotationConfigApplicationContext("com.bobocode.svydovets.service.base");
assertThat(context).isNotNull();
}
@Test
@Order(2)
void shouldCreateApplicationContextFromConfigClass() {
ApplicationContext context = new AnnotationConfigApplicationContext(BasePackageBeansConfig.class);
assertThat(context).isNotNull();
}
@Test
@Order(3)
void shouldCreateAllRequiredBeansFromBasePackage() {
String basePackage = "com.bobocode.svydovets.source.base";
ApplicationContext context = new AnnotationConfigApplicationContext(basePackage);
assertThat(context.getBean(CommonService.class)).isNotNull();
assertThat(context.getBean(MessageService.class)).isNotNull();
assertThat(context.getBean(NullService.class)).isNotNull();
}
@Test
@Order(4)
void shouldCreatesAllRequiredBeansFromConfigClass() {
ApplicationContext context = new AnnotationConfigApplicationContext(BasePackageBeansConfig.class);
assertThat(context.getBean(BasePackageBeansConfig.class)).isNotNull();
assertThat(context.getBean(CommonService.class)).isNotNull();
assertThat(context.getBean(MessageService.class)).isNotNull();
assertThat(context.getBean(NullService.class)).isNotNull();
}
@Test
@Order(5)
void shouldThrowNoSuchBeanDefinitionExceptionWhenBeanIsNotPresent() {
ApplicationContext context = new AnnotationConfigApplicationContext(BasePackageBeansConfig.class);
assertThatExceptionOfType(NoSuchBeanDefinitionException.class)
.isThrownBy(() -> context.getBean(TrimService.class))
.withMessage(String.format(NO_BEAN_DEFINITION_FOUND_OF_TYPE, TrimService.class.getName()));
}
@Test
@Order(6)
void shouldThrowNoUniqueBeanExceptionWhenUniqueBeanIsNotPresent() {
ApplicationContext context = new AnnotationConfigApplicationContext(QualifierPackageBeansConfig.class);
assertThatExceptionOfType(NoUniqueBeanException.class)
.isThrownBy(() -> context.getBean(PaymentService.class))
.withMessage(String.format(NO_UNIQUE_BEAN_FOUND_OF_TYPE, PaymentService.class.getName()));
}
@Test
@Order(7)
void shouldThrowNoSuchBeanDefinitionExceptionWhenBeanIsNotPresentByName() {
ApplicationContext context = new AnnotationConfigApplicationContext(BasePackageBeansConfig.class);
assertThatExceptionOfType(NoSuchBeanDefinitionException.class)
.isThrownBy(() -> context.getBean("superMessageService", MessageService.class))
.withMessage(String.format(NO_BEAN_DEFINITION_FOUND_OF_TYPE, MessageService.class.getName()));
}
@Test
@Order(8)
void shouldThrowNoSuchBeanExceptionWhenBeanIsPresentByNameButHasDifferentClassType() {
ApplicationContext context = new AnnotationConfigApplicationContext(BasePackageBeansConfig.class);
assertThatExceptionOfType(ClassCastException.class)
.isThrownBy(() -> context.getBean("messageService", CommonService.class))
.withMessage(String.format(
"Cannot cast %s to %s",
MessageService.class.getName(),
CommonService.class.getName())
);
}
@Test
@Order(9)
void shouldReturnBeanByNameAndClassTypeIfBeanIsPresent() {
ApplicationContext context = new AnnotationConfigApplicationContext(BasePackageBeansConfig.class);
MessageService messageService = context.getBean("messageService", MessageService.class);
assertThat(messageService).isNotNull();
}
@Test
@Order(10)
void shouldThrowNoUniqueBeanExceptionByBeanClassIfTwoPrimaryBeansArePresent() {
ApplicationContext context = new AnnotationConfigApplicationContext(PrimaryPackageBeansConfig.class);
assertThatExceptionOfType(NoUniqueBeanException.class)
.isThrownBy(() -> context.getBean(PrimaryService.class))
.withMessage(String.format(
NO_UNIQUE_BEAN_FOUND_OF_TYPE,
PrimaryService.class.getName())
);
}
@Test
@Order(11)
void shouldReturnBeanByNameAndClassIfTwoPrimaryBeansArePresent() {
ApplicationContext context = new AnnotationConfigApplicationContext(PrimaryPackageBeansConfig.class);
PrimaryService firstPrimaryServiceImpl = context.getBean("firstPrimaryServiceImpl", PrimaryService.class);
assertThat(firstPrimaryServiceImpl).isNotNull();
}
@Test
@Order(12)
void shouldGetAllRegistersBeansWithoutPrototype() {
ApplicationContext context = new AnnotationConfigApplicationContext("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface");
Map<String, Object> beans = context.getBeans();
assertEquals(2, beans.size());
assertTrue(beans.containsKey("injFirstCandidate"));
assertTrue(beans.containsKey("injSecondCandidate"));
}
@Test
@Order(13)
void shouldGetPrimaryCandidateByClasTypeForInterface() {
ApplicationContext context = new AnnotationConfigApplicationContext("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface");
Map<String, Object> beans = context.getBeans();
var bean = context.getBean(InjCandidate.class);
assertEquals(bean, beans.get("injSecondCandidate"));
}
@Test
@Order(14)
void shouldGetPrimaryCandidateByClasTypeAndNameForInterface() {
ApplicationContext context = new AnnotationConfigApplicationContext("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface");
Map<String, Object> beans = context.getBeans();
var bean = context.getBean("injSecondCandidate", InjCandidate.class);
assertEquals(bean, beans.get("injSecondCandidate"));
}
@Test
@Order(15)
void shouldGetPrototypeCandidateByClasType() {
ApplicationContext context = new AnnotationConfigApplicationContext("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface");
var bean1 = context.getBean(PrototypeCandidate.class);
var bean2 = context.getBean(PrototypeCandidate.class);
assertNotEquals(bean1, bean2);
}
@Test
@Order(16)
void shouldGetPrototypeCandidateByClasTypeAndName() {
ApplicationContext context = new AnnotationConfigApplicationContext("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface");
var bean1 = context.getBean("prototypeCandidate", PrototypeCandidate.class);
var bean2 = context.getBean("prototypeCandidate", PrototypeCandidate.class);
assertNotEquals(bean1, bean2);
}
@Test
@Order(17)
void shouldThrowNoSuchBeanDefinitionExceptionGetPrototypeCandidateByClasTypeAndName() {
ApplicationContext context = new AnnotationConfigApplicationContext("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface");
String errorMessageFormat = "No bean definition found of type %s";
String errorMessage = String.format(errorMessageFormat, PrototypeCandidate.class.getName());
var exception = assertThrows(NoSuchBeanDefinitionException.class,
() -> context.getBean("prototypeSecondCandidate", PrototypeCandidate.class));
assertEquals(errorMessage, exception.getMessage());
errorMessageFormat = "No bean definition found of type %s";
errorMessage = String.format(errorMessageFormat, InjFirstCandidate.class.getName());
exception = assertThrows(NoSuchBeanDefinitionException.class,
() -> context.getBean("prototypeSecondCandidate", InjFirstCandidate.class));
assertEquals(errorMessage, exception.getMessage());
}
@Test
@Order(18)
void shouldGetBeansOfTypeByRequiredType() {
ApplicationContext context = new AnnotationConfigApplicationContext("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface");
var expectedBeanMap = context.getBeans();
var actualBeanMap = context.getBeansOfType(InjCandidate.class);
assertEquals(expectedBeanMap.size(), actualBeanMap.size());
assertEquals(expectedBeanMap.get("injFirstCandidate"), actualBeanMap.get("injFirstCandidate"));
assertEquals(expectedBeanMap.get("injSecondCandidate"), actualBeanMap.get("injSecondCandidate"));
}
@Test
@Order(19)
void shouldGetPrototypeBeanOfTypeByRequiredTypeAndName() {
ApplicationContext context = new AnnotationConfigApplicationContext("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface");
var actualBean = context.getBean("injFirstPrototypeCandidate", InjFirstPrototypeCandidate.class);
assertEquals(InjFirstPrototypeCandidate.class, actualBean.getClass());
}
@Test
@Order(20)
void shouldGetPrototypeBeanOfTypeByRequiredTypeAndName1() {
ApplicationContext context = new AnnotationConfigApplicationContext("com.bobocode.svydovets.source.beanFactoryTest.foundCandidateByInterface");
var actualBean = context.getBean(InjPrototypeCandidate.class);
assertEquals(InjFirstPrototypeCandidate.class, actualBean.getClass());
}
@Test
@Order(21)
void shouldThrowNoSuchBeanDefinitionExceptionWhenGetPrototypeBeanOfTypeWithoutPrimaryByRequiredType() {
ApplicationContext context = new AnnotationConfigApplicationContext("com.bobocode.svydovets.source.beanFactoryTest.throwPrototypeCandidateByInterfaceWithoutPrimary");
String message = String.format(NO_BEAN_DEFINITION_FOUND_OF_TYPE, InjPrototypeCandidateWithoutPrimary.class.getName());
assertThatExceptionOfType(NoSuchBeanDefinitionException.class)
.isThrownBy(() -> context.getBean(InjPrototypeCandidateWithoutPrimary.class))
.withMessage(message);
}
@Test
@Order(22)
void shouldThrowNoUniqueBeanDefinitionExceptionWhenGetPrototypeBeanOfTypeMoreOnePrimaryByRequiredType() {
ApplicationContext context = new AnnotationConfigApplicationContext("com.bobocode.svydovets.source.beanFactoryTest.throwPrototypeCandidateByInterfaceMoreOnePrimary"); | String message = String.format(NO_UNIQUE_BEAN_DEFINITION_FOUND_OF_TYPE, InjPrototypeCandidateMoreOnePrimary.class.getName()); | 25 | 2023-11-07 06:36:50+00:00 | 8k |
oneqxz/RiseLoader | src/main/java/me/oneqxz/riseloader/rise/run/RunClient.java | [
{
"identifier": "ErrorBox",
"path": "src/main/java/me/oneqxz/riseloader/fxml/components/impl/ErrorBox.java",
"snippet": "public class ErrorBox extends Component {\n @Override\n public Stage show(Object... args) {\n try {\n Stage stage = new Stage();\n FX.showScene(\"Ri... | import javafx.application.Platform;
import javafx.scene.Node;
import me.oneqxz.riseloader.fxml.components.impl.ErrorBox;
import me.oneqxz.riseloader.fxml.components.impl.LaunchDebug;
import me.oneqxz.riseloader.fxml.scenes.MainScene;
import me.oneqxz.riseloader.rise.RiseInfo;
import me.oneqxz.riseloader.settings.Settings;
import me.oneqxz.riseloader.utils.OSUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.*;
import java.net.URL;
import java.util.*; | 4,701 | package me.oneqxz.riseloader.rise.run;
public class RunClient {
private static final Logger log = LogManager.getLogger("ClientLaunch");
public static void run(Node launchNode)
{
String osNatives = OSUtils.getOS() == OSUtils.OS.WINDOWS ? "windows" : "linux";
File rootFolder = OSUtils.getRiseFolder().toFile();
List<URL> urls = new ArrayList<>();
try {
File[] jars = new File(rootFolder, "rise\\" + Settings.getSettings().getString("rise.version", "release")).listFiles(pathname -> pathname.getName().endsWith(".jar"));
for (int i = 0; i < Objects.requireNonNull(jars).length; i++)
urls.add(jars[i].toURI().toURL());
File[] natives = new File(rootFolder, "natives\\" + osNatives).listFiles(pathname -> (pathname.getName().endsWith(OSUtils.getOS() == OSUtils.OS.WINDOWS ? ".dll" : ".so")));
for(int i = 0; i < Objects.requireNonNull(natives).length; i++)
urls.add(natives[i].toURI().toURL());
} catch (Exception x) {
x.printStackTrace();
MainScene.closeSelf();
Platform.runLater(() -> new ErrorBox().show(x, false));
}
try
{
log.info("Version: "+Settings.getSettings().getString("rise.version")+", Client running...");
StringBuilder classpath = new StringBuilder();
classpath.append("\"");
for (URL rl : urls) {
if (classpath.length() > 1 && urls.indexOf(rl) != urls.size())
classpath.append(";");
classpath.append(new File(rl.getPath()).getAbsolutePath());
}
classpath.append("\"");
| package me.oneqxz.riseloader.rise.run;
public class RunClient {
private static final Logger log = LogManager.getLogger("ClientLaunch");
public static void run(Node launchNode)
{
String osNatives = OSUtils.getOS() == OSUtils.OS.WINDOWS ? "windows" : "linux";
File rootFolder = OSUtils.getRiseFolder().toFile();
List<URL> urls = new ArrayList<>();
try {
File[] jars = new File(rootFolder, "rise\\" + Settings.getSettings().getString("rise.version", "release")).listFiles(pathname -> pathname.getName().endsWith(".jar"));
for (int i = 0; i < Objects.requireNonNull(jars).length; i++)
urls.add(jars[i].toURI().toURL());
File[] natives = new File(rootFolder, "natives\\" + osNatives).listFiles(pathname -> (pathname.getName().endsWith(OSUtils.getOS() == OSUtils.OS.WINDOWS ? ".dll" : ".so")));
for(int i = 0; i < Objects.requireNonNull(natives).length; i++)
urls.add(natives[i].toURI().toURL());
} catch (Exception x) {
x.printStackTrace();
MainScene.closeSelf();
Platform.runLater(() -> new ErrorBox().show(x, false));
}
try
{
log.info("Version: "+Settings.getSettings().getString("rise.version")+", Client running...");
StringBuilder classpath = new StringBuilder();
classpath.append("\"");
for (URL rl : urls) {
if (classpath.length() > 1 && urls.indexOf(rl) != urls.size())
classpath.append(";");
classpath.append(new File(rl.getPath()).getAbsolutePath());
}
classpath.append("\"");
| String startCommand = Settings.getSettings().getBoolean("others.javaoptimize", true) ? RiseInfo.getInstance().getOptimizedStartupCommand().getCommand() : RiseInfo.getInstance().getNormalStartupCommand().getCommand(); | 3 | 2023-11-01 01:40:52+00:00 | 8k |
YufiriaMazenta/CrypticLib | nms/src/main/java/crypticlib/nms/entity/EntityFactory.java | [
{
"identifier": "CrypticLib",
"path": "common/src/main/java/crypticlib/CrypticLib.java",
"snippet": "public class CrypticLib {\n\n\n private static final CommandManager commandManager;\n private static final PermissionManager permissionManager;\n private static IPlatform platform;\n private ... | import crypticlib.CrypticLib;
import crypticlib.nms.entity.v1_12_R1.V1_12_R1NbtEntity;
import crypticlib.nms.entity.v1_13_R1.V1_13_R1NbtEntity;
import crypticlib.nms.entity.v1_13_R2.V1_13_R2NbtEntity;
import crypticlib.nms.entity.v1_14_R1.V1_14_R1NbtEntity;
import crypticlib.nms.entity.v1_15_R1.V1_15_R1NbtEntity;
import crypticlib.nms.entity.v1_16_R1.V1_16_R1NbtEntity;
import crypticlib.nms.entity.v1_16_R2.V1_16_R2NbtEntity;
import crypticlib.nms.entity.v1_16_R3.V1_16_R3NbtEntity;
import crypticlib.nms.entity.v1_17_R1.V1_17_R1NbtEntity;
import crypticlib.nms.entity.v1_18_R1.V1_18_R1NbtEntity;
import crypticlib.nms.entity.v1_18_R2.V1_18_R2NbtEntity;
import crypticlib.nms.entity.v1_19_R1.V1_19_R1NbtEntity;
import crypticlib.nms.entity.v1_19_R2.V1_19_R2NbtEntity;
import crypticlib.nms.entity.v1_19_R3.V1_19_R3NbtEntity;
import crypticlib.nms.entity.v1_20_R1.V1_20_R1NbtEntity;
import crypticlib.nms.entity.v1_20_R2.V1_20_R2NbtEntity;
import crypticlib.nms.entity.v1_20_R3.V1_20_R3NbtEntity;
import org.bukkit.entity.Entity;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function; | 5,424 | package crypticlib.nms.entity;
public class EntityFactory {
private static final Map<String, Function<Entity, NbtEntity>> nbtEntityProviderMap;
static {
nbtEntityProviderMap = new ConcurrentHashMap<>();
regNbtEntityProvider("v1_12_R1", V1_12_R1NbtEntity::new);
regNbtEntityProvider("v1_13_R1", V1_13_R1NbtEntity::new);
regNbtEntityProvider("v1_13_R2", V1_13_R2NbtEntity::new);
regNbtEntityProvider("v1_14_R1", V1_14_R1NbtEntity::new);
regNbtEntityProvider("v1_15_R1", V1_15_R1NbtEntity::new);
regNbtEntityProvider("v1_16_R1", V1_16_R1NbtEntity::new);
regNbtEntityProvider("v1_16_R2", V1_16_R2NbtEntity::new);
regNbtEntityProvider("v1_16_R3", V1_16_R3NbtEntity::new);
regNbtEntityProvider("v1_17_R1", V1_17_R1NbtEntity::new); | package crypticlib.nms.entity;
public class EntityFactory {
private static final Map<String, Function<Entity, NbtEntity>> nbtEntityProviderMap;
static {
nbtEntityProviderMap = new ConcurrentHashMap<>();
regNbtEntityProvider("v1_12_R1", V1_12_R1NbtEntity::new);
regNbtEntityProvider("v1_13_R1", V1_13_R1NbtEntity::new);
regNbtEntityProvider("v1_13_R2", V1_13_R2NbtEntity::new);
regNbtEntityProvider("v1_14_R1", V1_14_R1NbtEntity::new);
regNbtEntityProvider("v1_15_R1", V1_15_R1NbtEntity::new);
regNbtEntityProvider("v1_16_R1", V1_16_R1NbtEntity::new);
regNbtEntityProvider("v1_16_R2", V1_16_R2NbtEntity::new);
regNbtEntityProvider("v1_16_R3", V1_16_R3NbtEntity::new);
regNbtEntityProvider("v1_17_R1", V1_17_R1NbtEntity::new); | regNbtEntityProvider("v1_18_R1", V1_18_R1NbtEntity::new); | 10 | 2023-11-07 12:39:20+00:00 | 8k |
Traben-0/resource_explorer | common/src/main/java/traben/resource_explorer/explorer/REExplorer.java | [
{
"identifier": "REConfig",
"path": "common/src/main/java/traben/resource_explorer/REConfig.java",
"snippet": "public class REConfig {\n\n private static REConfig instance;\n public boolean showResourcePackButton = true;\n public boolean logFullFileTree = false;\n public boolean addCauseToRe... | import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.texture.AbstractTexture;
import net.minecraft.client.texture.NativeImage;
import net.minecraft.client.toast.SystemToast;
import net.minecraft.client.toast.ToastManager;
import net.minecraft.resource.Resource;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import org.apache.commons.io.IOUtils;
import traben.resource_explorer.REConfig;
import traben.resource_explorer.ResourceExplorerClient;
import traben.resource_explorer.mixin.TextureManagerAccessor;
import java.io.*;
import java.nio.file.Path;
import java.util.*; | 3,910 | package traben.resource_explorer.explorer;
public class REExplorer {
public static final Identifier ICON_FILE_BUILT = new Identifier("resource_explorer:textures/file_built.png");
public static final Identifier ICON_FOLDER_BUILT = new Identifier("resource_explorer:textures/folder_built.png");
public static final Identifier ICON_FOLDER = new Identifier("resource_explorer:textures/folder.png");
public static final Identifier ICON_FOLDER_OPEN = new Identifier("resource_explorer:textures/folder_open.png");
public static final Identifier ICON_FOLDER_BACK = new Identifier("resource_explorer:textures/folder_back.png");
public static final Identifier ICON_FILE_PNG = new Identifier("resource_explorer:textures/file_png.png");
public static final Identifier ICON_FILE_TEXT = new Identifier("resource_explorer:textures/file_text.png");
public static final Identifier ICON_FILE_PROPERTY = new Identifier("resource_explorer:textures/file_property.png");
public static final Identifier ICON_FILE_OGG = new Identifier("resource_explorer:textures/file_ogg.png");
public static final Identifier ICON_FILE_UNKNOWN = new Identifier("resource_explorer:textures/file_unknown.png");
public static final Identifier ICON_FOLDER_MOJANG = new Identifier("resource_explorer:textures/folder_mojang.png");
public static final Identifier ICON_FOLDER_OPTIFINE = new Identifier("resource_explorer:textures/folder_optifine.png");
public static final Identifier ICON_FOLDER_ETF = new Identifier("resource_explorer:textures/folder_etf.png");
public static final Identifier ICON_FOLDER_EMF = new Identifier("resource_explorer:textures/folder_emf.png");
public static final Identifier ICON_FOLDER_CORNER = new Identifier("resource_explorer:textures/folder_corner.png");
public static final Identifier ICON_FILE_BLANK = new Identifier("resource_explorer:textures/file_blank.png");
public static final Identifier ICON_FILE_JSON = new Identifier("resource_explorer:textures/file_json.png");
public static final Identifier ICON_FOLDER_UP = new Identifier("resource_explorer:textures/folder_up.png");
public static final Identifier ICON_FOLDER_UP_SELECTED = new Identifier("resource_explorer:textures/folder_up_selected.png");
public static final Identifier ICON_FILE_ZIP = new Identifier("resource_explorer:textures/file_zip.png");
public static final Identifier ICON_FILE_JEM = new Identifier("resource_explorer:textures/file_jem.png");
public static final Identifier ICON_HAS_META = new Identifier("resource_explorer:textures/has_meta.png");
public static final Identifier ICON_FOLDER_FABRIC = new Identifier("resource_explorer:textures/folder_fabric.png");
public static final Identifier ICON_FOLDER_PNG = new Identifier("resource_explorer:textures/folder_png.png");
public static final Identifier ICON_FOLDER_OGG = new Identifier("resource_explorer:textures/folder_ogg.png");
public static final Identifier ICON_MOD = new Identifier("resource_explorer:textures/icon.png");
public static LinkedList<REResourceEntry> getResourceFolderRoot() {
try {
ObjectLinkedOpenHashSet<REResourceFile> allFilesList = new ObjectLinkedOpenHashSet<>();
boolean print = REConfig.getInstance().logFullFileTree;
if (print) {
ResourceExplorerClient.log("/START/");
ResourceExplorerClient.log("/START/READ/");
}
//perform vanilla search with placeholder string that will trigger a blanket resource search
try {
Map<Identifier, Resource> resourceMap = MinecraftClient.getInstance().getResourceManager().findResources("resource_explorer$search", (id) -> true);
resourceMap.forEach((k, v) -> allFilesList.add(new REResourceFile(k, v)));
} catch (Exception ignored) {
//the method I use to explore all resources will cause an exception once at the end of the resource list as I need to search for blank file names
}
//fabric mod resources allow direct blank searches so catch those too
Map<Identifier, Resource> resourceMap2 = MinecraftClient.getInstance().getResourceManager().findResources("", (id) -> true);
resourceMap2.forEach((k, v) -> allFilesList.add(new REResourceFile(k, v)));
//search for generated texture assets | package traben.resource_explorer.explorer;
public class REExplorer {
public static final Identifier ICON_FILE_BUILT = new Identifier("resource_explorer:textures/file_built.png");
public static final Identifier ICON_FOLDER_BUILT = new Identifier("resource_explorer:textures/folder_built.png");
public static final Identifier ICON_FOLDER = new Identifier("resource_explorer:textures/folder.png");
public static final Identifier ICON_FOLDER_OPEN = new Identifier("resource_explorer:textures/folder_open.png");
public static final Identifier ICON_FOLDER_BACK = new Identifier("resource_explorer:textures/folder_back.png");
public static final Identifier ICON_FILE_PNG = new Identifier("resource_explorer:textures/file_png.png");
public static final Identifier ICON_FILE_TEXT = new Identifier("resource_explorer:textures/file_text.png");
public static final Identifier ICON_FILE_PROPERTY = new Identifier("resource_explorer:textures/file_property.png");
public static final Identifier ICON_FILE_OGG = new Identifier("resource_explorer:textures/file_ogg.png");
public static final Identifier ICON_FILE_UNKNOWN = new Identifier("resource_explorer:textures/file_unknown.png");
public static final Identifier ICON_FOLDER_MOJANG = new Identifier("resource_explorer:textures/folder_mojang.png");
public static final Identifier ICON_FOLDER_OPTIFINE = new Identifier("resource_explorer:textures/folder_optifine.png");
public static final Identifier ICON_FOLDER_ETF = new Identifier("resource_explorer:textures/folder_etf.png");
public static final Identifier ICON_FOLDER_EMF = new Identifier("resource_explorer:textures/folder_emf.png");
public static final Identifier ICON_FOLDER_CORNER = new Identifier("resource_explorer:textures/folder_corner.png");
public static final Identifier ICON_FILE_BLANK = new Identifier("resource_explorer:textures/file_blank.png");
public static final Identifier ICON_FILE_JSON = new Identifier("resource_explorer:textures/file_json.png");
public static final Identifier ICON_FOLDER_UP = new Identifier("resource_explorer:textures/folder_up.png");
public static final Identifier ICON_FOLDER_UP_SELECTED = new Identifier("resource_explorer:textures/folder_up_selected.png");
public static final Identifier ICON_FILE_ZIP = new Identifier("resource_explorer:textures/file_zip.png");
public static final Identifier ICON_FILE_JEM = new Identifier("resource_explorer:textures/file_jem.png");
public static final Identifier ICON_HAS_META = new Identifier("resource_explorer:textures/has_meta.png");
public static final Identifier ICON_FOLDER_FABRIC = new Identifier("resource_explorer:textures/folder_fabric.png");
public static final Identifier ICON_FOLDER_PNG = new Identifier("resource_explorer:textures/folder_png.png");
public static final Identifier ICON_FOLDER_OGG = new Identifier("resource_explorer:textures/folder_ogg.png");
public static final Identifier ICON_MOD = new Identifier("resource_explorer:textures/icon.png");
public static LinkedList<REResourceEntry> getResourceFolderRoot() {
try {
ObjectLinkedOpenHashSet<REResourceFile> allFilesList = new ObjectLinkedOpenHashSet<>();
boolean print = REConfig.getInstance().logFullFileTree;
if (print) {
ResourceExplorerClient.log("/START/");
ResourceExplorerClient.log("/START/READ/");
}
//perform vanilla search with placeholder string that will trigger a blanket resource search
try {
Map<Identifier, Resource> resourceMap = MinecraftClient.getInstance().getResourceManager().findResources("resource_explorer$search", (id) -> true);
resourceMap.forEach((k, v) -> allFilesList.add(new REResourceFile(k, v)));
} catch (Exception ignored) {
//the method I use to explore all resources will cause an exception once at the end of the resource list as I need to search for blank file names
}
//fabric mod resources allow direct blank searches so catch those too
Map<Identifier, Resource> resourceMap2 = MinecraftClient.getInstance().getResourceManager().findResources("", (id) -> true);
resourceMap2.forEach((k, v) -> allFilesList.add(new REResourceFile(k, v)));
//search for generated texture assets | Map<Identifier, AbstractTexture> textures = ((TextureManagerAccessor) MinecraftClient.getInstance().getTextureManager()).getTextures(); | 2 | 2023-11-05 17:35:39+00:00 | 8k |
cypcodestudio/rbacspring | rbacspring/src/main/java/com/cypcode/rbacspring/controller/UserAccessController.java | [
{
"identifier": "EntityResponse",
"path": "rbacspring/src/main/java/com/cypcode/rbacspring/entity/dto/EntityResponse.java",
"snippet": "public class EntityResponse {\n\tpublic static ResponseEntity<Object> generateResponse(String message, HttpStatus status, Object responseObj) {\n\t\t\n\t\tMap<String, O... | import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.cypcode.rbacspring.entity.dto.EntityResponse;
import com.cypcode.rbacspring.entity.dto.UserRegisterRequestDTO;
import com.cypcode.rbacspring.security.JWTTokenUtil;
import com.cypcode.rbacspring.security.dto.AuthenticationRequest;
import com.cypcode.rbacspring.security.dto.AuthenticationResponse;
import com.cypcode.rbacspring.service.WUserService; | 3,678 | package com.cypcode.rbacspring.controller;
@RestController
@RequestMapping("user")
public class UserAccessController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
WUserService userService;
@Autowired
private JWTTokenUtil jwtTokenUtil;
@Autowired
PasswordEncoder passwordEncoder;
@RequestMapping(value = "/authenticate", method = RequestMethod.POST) | package com.cypcode.rbacspring.controller;
@RestController
@RequestMapping("user")
public class UserAccessController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
WUserService userService;
@Autowired
private JWTTokenUtil jwtTokenUtil;
@Autowired
PasswordEncoder passwordEncoder;
@RequestMapping(value = "/authenticate", method = RequestMethod.POST) | public ResponseEntity<Object> createAuthenticationToken(@RequestBody AuthenticationRequest authenticationRequest) | 3 | 2023-11-05 05:38:31+00:00 | 8k |
ynwynw/oaSystemPublic | src/main/java/cn/gson/oasys/model/dao/user/UserDao.java | [
{
"identifier": "Dept",
"path": "src/main/java/cn/gson/oasys/model/entity/user/Dept.java",
"snippet": "@Entity\n@Table(name = \"aoa_dept\")\npublic class Dept {\n\t@Id\n\t@Column(name = \"dept_id\")\n\t@GeneratedValue(strategy=GenerationType.IDENTITY)\n\tprivate Long deptId;\t//部门id\n\t\n\t@Column(name ... | import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import cn.gson.oasys.model.entity.user.Dept;
import cn.gson.oasys.model.entity.user.User; | 4,694 | package cn.gson.oasys.model.dao.user;
public interface UserDao extends JpaRepository<User, Long>{
List<User> findByUserId(Long id);
List<User> findByFatherId(Long parentid);
@Query("select u from User u ")
List<User> findAll();
@Query("select u from User u ")
Page<User> findAllPage(Pageable pa);
Page<User> findByFatherId(Long parentid,Pageable pa);
//名字模糊查找
@Query("select u from User u where (u.userName like %?1% or u.realName like %?1%) and u.fatherId=?2 ")
Page<User> findbyFatherId(String name,Long parentid,Pageable pa);
//名字模糊查找
@Query("select u from User u where (u.userName like %?1% or u.realName like %?1%)")
Page<User> findAllUserByName(String name,Pageable pa);
@Query("select u from User u where u.userName=:name")
User findid(@Param("name")String name);
@Query("select tu.pkId from Taskuser tu where tu.taskId.taskId=:taskid and tu.userId.userId=:userid")
Long findpkId(@Param("taskid")Long taskid,@Param("userid")Long userid);
//根据名字找用户
User findByUserName(String title);
//根据用户名模糊查找
@Query("from User u where u.userName like %:name% or u.realName like %:name%")
Page<User> findbyUserNameLike(@Param("name")String name,Pageable pa);
//根据真实姓名模糊查找
Page<User> findByrealNameLike(String title,Pageable pa);
//根据姓名首拼模糊查找,并分页
Page<User> findByPinyinLike(String pinyin,Pageable pa);
//根据姓名首拼+查找关键字查找(部门、姓名、电话号码),并分页
@Query("from User u where (u.userName like ?1 or u.dept.deptName like ?1 or u.userTel like ?1 or u.position.name like ?1) and u.pinyin like ?2")
Page<User> findSelectUsers(String baseKey,String pinyinm,Pageable pa);
//根据姓名首拼+查找关键字查找(部门、姓名、电话号码),并分页
@Query("from User u where u.userName like ?1 or u.dept.deptName like ?1 or u.userTel like ?1 or u.position.name like ?1 or u.pinyin like ?2")
Page<User> findUsers(String baseKey,String baseKey2,Pageable pa);
/**
* 用户管理查询可用用户
* @param isLock
* @param pa
* @return
*/
Page<User> findByIsLock(Integer isLock,Pageable pa);
@Query("from User u where u.dept.deptName like %?1% or u.userName like %?1% or u.realName like %?1% or u.userTel like %?1% or u.role.roleName like %?1%")
Page<User> findnamelike(String name,Pageable pa);
| package cn.gson.oasys.model.dao.user;
public interface UserDao extends JpaRepository<User, Long>{
List<User> findByUserId(Long id);
List<User> findByFatherId(Long parentid);
@Query("select u from User u ")
List<User> findAll();
@Query("select u from User u ")
Page<User> findAllPage(Pageable pa);
Page<User> findByFatherId(Long parentid,Pageable pa);
//名字模糊查找
@Query("select u from User u where (u.userName like %?1% or u.realName like %?1%) and u.fatherId=?2 ")
Page<User> findbyFatherId(String name,Long parentid,Pageable pa);
//名字模糊查找
@Query("select u from User u where (u.userName like %?1% or u.realName like %?1%)")
Page<User> findAllUserByName(String name,Pageable pa);
@Query("select u from User u where u.userName=:name")
User findid(@Param("name")String name);
@Query("select tu.pkId from Taskuser tu where tu.taskId.taskId=:taskid and tu.userId.userId=:userid")
Long findpkId(@Param("taskid")Long taskid,@Param("userid")Long userid);
//根据名字找用户
User findByUserName(String title);
//根据用户名模糊查找
@Query("from User u where u.userName like %:name% or u.realName like %:name%")
Page<User> findbyUserNameLike(@Param("name")String name,Pageable pa);
//根据真实姓名模糊查找
Page<User> findByrealNameLike(String title,Pageable pa);
//根据姓名首拼模糊查找,并分页
Page<User> findByPinyinLike(String pinyin,Pageable pa);
//根据姓名首拼+查找关键字查找(部门、姓名、电话号码),并分页
@Query("from User u where (u.userName like ?1 or u.dept.deptName like ?1 or u.userTel like ?1 or u.position.name like ?1) and u.pinyin like ?2")
Page<User> findSelectUsers(String baseKey,String pinyinm,Pageable pa);
//根据姓名首拼+查找关键字查找(部门、姓名、电话号码),并分页
@Query("from User u where u.userName like ?1 or u.dept.deptName like ?1 or u.userTel like ?1 or u.position.name like ?1 or u.pinyin like ?2")
Page<User> findUsers(String baseKey,String baseKey2,Pageable pa);
/**
* 用户管理查询可用用户
* @param isLock
* @param pa
* @return
*/
Page<User> findByIsLock(Integer isLock,Pageable pa);
@Query("from User u where u.dept.deptName like %?1% or u.userName like %?1% or u.realName like %?1% or u.userTel like %?1% or u.role.roleName like %?1%")
Page<User> findnamelike(String name,Pageable pa);
| List<User> findByDept(Dept dept); | 0 | 2023-11-03 02:08:22+00:00 | 8k |
data-harness-cloud/data_harness-be | application-webadmin/src/main/java/supie/webadmin/app/model/StandardQuatity.java | [
{
"identifier": "MyCommonUtil",
"path": "common/common-core/src/main/java/supie/common/core/util/MyCommonUtil.java",
"snippet": "public class MyCommonUtil {\n\n private static final Validator VALIDATOR;\n\n static {\n VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();\n ... | import com.baomidou.mybatisplus.annotation.*;
import supie.common.core.util.MyCommonUtil;
import supie.common.core.annotation.*;
import supie.common.core.base.model.BaseModel;
import supie.common.core.base.mapper.BaseModelMapper;
import supie.webadmin.app.vo.StandardQuatityVo;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.mapstruct.*;
import org.mapstruct.factory.Mappers; | 6,525 | package supie.webadmin.app.model;
/**
* StandardQuatity实体对象。
*
* @author rm -rf .bug
* @date 2020-11-12
*/
@Data
@EqualsAndHashCode(callSuper = true)
@TableName(value = "sdt_standard_quatity")
public class StandardQuatity extends BaseModel {
/**
* 租户号。
*/
@TableId(value = "id")
private Long id;
/**
* 数据所属人。
*/
@UserFilterColumn
private Long dataUserId;
/**
* 数据所属部门。
*/
@DeptFilterColumn
private Long dataDeptId;
/**
* 逻辑删除标记字段(1: 正常 -1: 已删除)。
*/
@TableLogic
private Integer isDelete;
/**
* 质量标准名称。
*/
private String standardQualityName;
/**
* 质量标准编码。
*/
private String standardQualityCode;
/**
* 质量标准分类。
*/
private String staidardQualityType;
/**
* 质量标准父id。
*/
private Long standardQualityParentId;
/**
* 质量校验正则。
*/
private String standardQaulityRe;
/**
* 质量校验长度限制。
*/
private String standardQualityLang;
/**
* 质量校验不为空。
*/
private String standardQualityNotNull;
/**
* 质量校验中心关联规则。
*/
private Long standardQualityQualityCenterId;
/**
* updateTime 范围过滤起始值(>=)。
*/
@TableField(exist = false)
private String updateTimeStart;
/**
* updateTime 范围过滤结束值(<=)。
*/
@TableField(exist = false)
private String updateTimeEnd;
/**
* createTime 范围过滤起始值(>=)。
*/
@TableField(exist = false)
private String createTimeStart;
/**
* createTime 范围过滤结束值(<=)。
*/
@TableField(exist = false)
private String createTimeEnd;
/**
* standard_quality_name / standard_quality_code / staidard_quality_type / standard_qaulity_re / standard_quality_lang / standard_quality_not_null LIKE搜索字符串。
*/
@TableField(exist = false)
private String searchString;
public void setSearchString(String searchString) { | package supie.webadmin.app.model;
/**
* StandardQuatity实体对象。
*
* @author rm -rf .bug
* @date 2020-11-12
*/
@Data
@EqualsAndHashCode(callSuper = true)
@TableName(value = "sdt_standard_quatity")
public class StandardQuatity extends BaseModel {
/**
* 租户号。
*/
@TableId(value = "id")
private Long id;
/**
* 数据所属人。
*/
@UserFilterColumn
private Long dataUserId;
/**
* 数据所属部门。
*/
@DeptFilterColumn
private Long dataDeptId;
/**
* 逻辑删除标记字段(1: 正常 -1: 已删除)。
*/
@TableLogic
private Integer isDelete;
/**
* 质量标准名称。
*/
private String standardQualityName;
/**
* 质量标准编码。
*/
private String standardQualityCode;
/**
* 质量标准分类。
*/
private String staidardQualityType;
/**
* 质量标准父id。
*/
private Long standardQualityParentId;
/**
* 质量校验正则。
*/
private String standardQaulityRe;
/**
* 质量校验长度限制。
*/
private String standardQualityLang;
/**
* 质量校验不为空。
*/
private String standardQualityNotNull;
/**
* 质量校验中心关联规则。
*/
private Long standardQualityQualityCenterId;
/**
* updateTime 范围过滤起始值(>=)。
*/
@TableField(exist = false)
private String updateTimeStart;
/**
* updateTime 范围过滤结束值(<=)。
*/
@TableField(exist = false)
private String updateTimeEnd;
/**
* createTime 范围过滤起始值(>=)。
*/
@TableField(exist = false)
private String createTimeStart;
/**
* createTime 范围过滤结束值(<=)。
*/
@TableField(exist = false)
private String createTimeEnd;
/**
* standard_quality_name / standard_quality_code / staidard_quality_type / standard_qaulity_re / standard_quality_lang / standard_quality_not_null LIKE搜索字符串。
*/
@TableField(exist = false)
private String searchString;
public void setSearchString(String searchString) { | this.searchString = MyCommonUtil.replaceSqlWildcard(searchString); | 0 | 2023-11-04 12:36:44+00:00 | 8k |
FTC-ORBIT/14872-2024-CenterStage | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/robotSubSystems/SubSystemManager.java | [
{
"identifier": "minHeightToOpenFourbar",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/robotData/Constants.java",
"snippet": "public static final float minHeightToOpenFourbar =500;"
},
{
"identifier": "Delay",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/O... | import static org.firstinspires.ftc.teamcode.robotData.Constants.minHeightToOpenFourbar;
import com.qualcomm.robotcore.hardware.Gamepad;
import org.firstinspires.ftc.robotcore.external.Telemetry;
import org.firstinspires.ftc.teamcode.OrbitUtils.Delay;
import org.firstinspires.ftc.teamcode.Sensors.OrbitGyro;
import org.firstinspires.ftc.teamcode.robotData.GlobalData;
import org.firstinspires.ftc.teamcode.robotSubSystems.climb.ClimbState;
import org.firstinspires.ftc.teamcode.robotSubSystems.fourbar.Fourbar;
import org.firstinspires.ftc.teamcode.robotSubSystems.fourbar.FourbarState;
import org.firstinspires.ftc.teamcode.robotSubSystems.outtake.Outtake;
import org.firstinspires.ftc.teamcode.robotSubSystems.outtake.OuttakeState;
import org.firstinspires.ftc.teamcode.robotSubSystems.elevator.Elevator;
import org.firstinspires.ftc.teamcode.robotSubSystems.elevator.ElevatorStates;
import org.firstinspires.ftc.teamcode.robotSubSystems.intake.Intake;
import org.firstinspires.ftc.teamcode.robotSubSystems.intake.IntakeState;
import org.firstinspires.ftc.teamcode.robotSubSystems.plane.Plane;
import org.firstinspires.ftc.teamcode.robotSubSystems.plane.PlaneState; | 4,430 | break;
case HIGH:
break;
case TRAVEL:
break;
case CLIMB:
break;
case DEPLETE:
break;
}
return stateFromDriver;
}
public static void setSubsystemToState(Gamepad gamepad1, Gamepad gamepad2, Telemetry telemetry) {
final RobotState wanted = getStateFromWantedAndCurrent(getState(gamepad1));
if ((wanted.equals(RobotState.TRAVEL)|| wanted.equals(RobotState.INTAKE)) && (lastState.equals(RobotState.LOW) || lastState.equals(RobotState.MID) || lastState.equals(RobotState.HIGH))){
delayElevator.startAction(GlobalData.currentTime);
}
if (wanted.equals(RobotState.INTAKE) && lastState.equals(RobotState.TRAVEL)){
intakeDelay.startAction(GlobalData.currentTime);
}
switch (wanted) {
case TRAVEL:
outtakeState = OuttakeState.CLOSED;
if (intakeDelay.isDelayPassed()) {
intakeState = IntakeState.STOP;
}
fourbarState = FourbarState.REVERSE;
if (delayElevator.isDelayPassed() && !ElevatorToggleButton) {
elevatorState = ElevatorStates.INTAKE;
}
climbState = ClimbState.DOWN;
break;
case INTAKE:
intakeState = IntakeState.COLLECT;
if (delayElevator.isDelayPassed() && !ElevatorToggleButton) {
elevatorState = ElevatorStates.INTAKE;
}
outtakeState = OuttakeState.OPEN;
fourbarState = FourbarState.REVERSE;
climbState = ClimbState.DOWN;
break;
case LOW:
intakeState = IntakeState.STOP;
if (!ElevatorToggleButton) elevatorState = ElevatorStates.LOW;
if (gamepad1.left_bumper) {
outtakeState = OuttakeState.OPEN;
}
if (minHeightToOpenFourbar <=Elevator.getPos()) {
fourbarState = FourbarState.MOVE;
}else {
fourbarState = FourbarState.REVERSE;
}
climbState = ClimbState.DOWN;
break;
case MID:
intakeState = IntakeState.STOP;
if (!ElevatorToggleButton) elevatorState = ElevatorStates.MID;
if (gamepad1.left_bumper){
outtakeState = OuttakeState.OPEN;
}
if (minHeightToOpenFourbar <=Elevator.getPos()) {
fourbarState = FourbarState.MOVE;
}else {
fourbarState = FourbarState.REVERSE;
}
climbState = ClimbState.DOWN;
break;
// case HIGH:
// intakeState = IntakeState.STOP;
// elevatorState = ElevatorStates.HIGH;
// if (gamepad1.left_bumper) {
// outtakeState = OuttakeState.OPEN;
// }
// if (minHeightToOpenFourbar <=Elevator.getPos()) {
// fourbarState = FourbarState.MOVE;
// }else {
// fourbarState = FourbarState.REVERSE;
// }
// climbState = ClimbState.DOWN;
// break;
case CLIMB:
intakeState = IntakeState.STOP;
elevatorState = ElevatorStates.INTAKE;
outtakeState = OuttakeState.CLOSED;
fourbarState = FourbarState.REVERSE;
climbState = ClimbState.UP;
break;
case DEPLETE:
fourbarState = FourbarState.REVERSE;
intakeState = IntakeState.DEPLETE;
if (!ElevatorToggleButton) elevatorState = ElevatorStates.INTAKE;
outtakeState = OuttakeState.CLOSED;
climbState = ClimbState.DOWN;
}
if (gamepad1.dpad_right) Intake.operate(IntakeState.STOP);
if (gamepad1.dpad_up){
if (toggleButton){
outtakeState.equals(OuttakeState.OPEN);
}else {
outtakeState.equals(OuttakeState.CLOSED);
}
Outtake.operate(outtakeState);
toggleButton = !toggleButton;
}
if (gamepad1.right_stick_y != 0 ){
elevatorState = ElevatorStates.OVERRIDE;
ElevatorToggleButton = true;
}
Intake.operate(intakeState);
Outtake.operate(outtakeState);
Elevator.operate(elevatorState, gamepad1, telemetry );
Fourbar.operate(fourbarState,gamepad1,telemetry);
// Climb.operate(climbState, gamepad1);
lastState = wanted;
if (gamepad1.dpad_down) OrbitGyro.resetGyro(); | package org.firstinspires.ftc.teamcode.robotSubSystems;
public class SubSystemManager {
public static RobotState lastState = RobotState.TRAVEL;
private static IntakeState intakeState = IntakeState.STOP;
private static ElevatorStates elevatorState = ElevatorStates.INTAKE;
private static OuttakeState outtakeState = OuttakeState.CLOSED;
private static FourbarState fourbarState = FourbarState.REVERSE;
private static ClimbState climbState = ClimbState.DOWN;
private static Delay delayElevator = new Delay(1.3f);
private static Delay intakeDelay = new Delay(1f);
private static boolean toggleButton = true;
private static boolean ElevatorToggleButton = false;
private static RobotState getState(Gamepad gamepad) {
if (gamepad.b || gamepad.a || gamepad.dpad_left || gamepad.x || gamepad.y || gamepad.right_bumper){
ElevatorToggleButton = false;
}
return gamepad.b ? RobotState.TRAVEL
: gamepad.a ? RobotState.INTAKE
: gamepad.dpad_left ? RobotState.CLIMB :gamepad.x ? RobotState.LOW:gamepad.y ? RobotState.MID: gamepad.right_bumper ? RobotState.DEPLETE: lastState;
}
private static RobotState getStateFromWantedAndCurrent(RobotState stateFromDriver){
switch (stateFromDriver){
case INTAKE:
break;
case LOW:
break;
case MID:
break;
case HIGH:
break;
case TRAVEL:
break;
case CLIMB:
break;
case DEPLETE:
break;
}
return stateFromDriver;
}
public static void setSubsystemToState(Gamepad gamepad1, Gamepad gamepad2, Telemetry telemetry) {
final RobotState wanted = getStateFromWantedAndCurrent(getState(gamepad1));
if ((wanted.equals(RobotState.TRAVEL)|| wanted.equals(RobotState.INTAKE)) && (lastState.equals(RobotState.LOW) || lastState.equals(RobotState.MID) || lastState.equals(RobotState.HIGH))){
delayElevator.startAction(GlobalData.currentTime);
}
if (wanted.equals(RobotState.INTAKE) && lastState.equals(RobotState.TRAVEL)){
intakeDelay.startAction(GlobalData.currentTime);
}
switch (wanted) {
case TRAVEL:
outtakeState = OuttakeState.CLOSED;
if (intakeDelay.isDelayPassed()) {
intakeState = IntakeState.STOP;
}
fourbarState = FourbarState.REVERSE;
if (delayElevator.isDelayPassed() && !ElevatorToggleButton) {
elevatorState = ElevatorStates.INTAKE;
}
climbState = ClimbState.DOWN;
break;
case INTAKE:
intakeState = IntakeState.COLLECT;
if (delayElevator.isDelayPassed() && !ElevatorToggleButton) {
elevatorState = ElevatorStates.INTAKE;
}
outtakeState = OuttakeState.OPEN;
fourbarState = FourbarState.REVERSE;
climbState = ClimbState.DOWN;
break;
case LOW:
intakeState = IntakeState.STOP;
if (!ElevatorToggleButton) elevatorState = ElevatorStates.LOW;
if (gamepad1.left_bumper) {
outtakeState = OuttakeState.OPEN;
}
if (minHeightToOpenFourbar <=Elevator.getPos()) {
fourbarState = FourbarState.MOVE;
}else {
fourbarState = FourbarState.REVERSE;
}
climbState = ClimbState.DOWN;
break;
case MID:
intakeState = IntakeState.STOP;
if (!ElevatorToggleButton) elevatorState = ElevatorStates.MID;
if (gamepad1.left_bumper){
outtakeState = OuttakeState.OPEN;
}
if (minHeightToOpenFourbar <=Elevator.getPos()) {
fourbarState = FourbarState.MOVE;
}else {
fourbarState = FourbarState.REVERSE;
}
climbState = ClimbState.DOWN;
break;
// case HIGH:
// intakeState = IntakeState.STOP;
// elevatorState = ElevatorStates.HIGH;
// if (gamepad1.left_bumper) {
// outtakeState = OuttakeState.OPEN;
// }
// if (minHeightToOpenFourbar <=Elevator.getPos()) {
// fourbarState = FourbarState.MOVE;
// }else {
// fourbarState = FourbarState.REVERSE;
// }
// climbState = ClimbState.DOWN;
// break;
case CLIMB:
intakeState = IntakeState.STOP;
elevatorState = ElevatorStates.INTAKE;
outtakeState = OuttakeState.CLOSED;
fourbarState = FourbarState.REVERSE;
climbState = ClimbState.UP;
break;
case DEPLETE:
fourbarState = FourbarState.REVERSE;
intakeState = IntakeState.DEPLETE;
if (!ElevatorToggleButton) elevatorState = ElevatorStates.INTAKE;
outtakeState = OuttakeState.CLOSED;
climbState = ClimbState.DOWN;
}
if (gamepad1.dpad_right) Intake.operate(IntakeState.STOP);
if (gamepad1.dpad_up){
if (toggleButton){
outtakeState.equals(OuttakeState.OPEN);
}else {
outtakeState.equals(OuttakeState.CLOSED);
}
Outtake.operate(outtakeState);
toggleButton = !toggleButton;
}
if (gamepad1.right_stick_y != 0 ){
elevatorState = ElevatorStates.OVERRIDE;
ElevatorToggleButton = true;
}
Intake.operate(intakeState);
Outtake.operate(outtakeState);
Elevator.operate(elevatorState, gamepad1, telemetry );
Fourbar.operate(fourbarState,gamepad1,telemetry);
// Climb.operate(climbState, gamepad1);
lastState = wanted;
if (gamepad1.dpad_down) OrbitGyro.resetGyro(); | if (gamepad1.options) Plane.operate(PlaneState.THROW); | 13 | 2023-11-03 13:32:48+00:00 | 8k |
momentohq/momento-dynamodb-lock-client | src/test/java/com/amazonaws/services/dynamodbv2/MomentoDynamoDBLockClientTest.java | [
{
"identifier": "MomentoDynamoDBLockClientOptions",
"path": "src/main/java/momento/lock/client/MomentoDynamoDBLockClientOptions.java",
"snippet": "public class MomentoDynamoDBLockClientOptions {\n\n private final String cacheName;\n private final CredentialProvider credentialProvider;\n private... | import com.amazonaws.services.dynamodbv2.model.LockCurrentlyUnavailableException;
import com.amazonaws.services.dynamodbv2.model.LockNotGrantedException;
import momento.lock.client.MomentoDynamoDBLockClientOptions;
import momento.lock.client.MomentoLockClient;
import momento.lock.client.MomentoLockItem;
import momento.sdk.CacheClient;
import momento.sdk.auth.CredentialProvider;
import momento.sdk.config.Configurations;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit; | 5,986 | package com.amazonaws.services.dynamodbv2;
public class MomentoDynamoDBLockClientTest {
private static MomentoDynamoDBLockClient momentoDynamoDBLockClient;
private static MomentoDynamoDBLockClient momentoDynamoDBLockClientWithoutHeartbeat;
private static MomentoLockClient momentoLockClient;
private static MomentoLockClient momentoLockClientNoHeartBeats;
private static CacheClient cacheClient;
private static String LOCK_CACHE_NAME = "lock";
private static String LOCK_CACHE_NAME_NO_HEARTBEATS = "lock_no_heartbeats";
@BeforeAll
public static void setup() {
momentoDynamoDBLockClient = new MomentoDynamoDBLockClient(MomentoDynamoDBLockClientOptions.builder("lock")
.withConfiguration(Configurations.Laptop.latest())
.withCredentialProvider(CredentialProvider.fromEnvVar("MOMENTO_API_KEY"))
.withPartitionKeyName("pkey")
.withOwnerName("lock-client-lib")
.withLeaseDuration(60L)
.withHeartbeatPeriod(3L)
.withCreateHeartbeatBackgroundThread(true)
.withTimeUnit(TimeUnit.SECONDS)
.withTotalNumBackgroundThreadsForHeartbeating(2)
.withTotalNumThreadsForAcquiringLocks(20)
.build());
momentoDynamoDBLockClientWithoutHeartbeat = new MomentoDynamoDBLockClient(MomentoDynamoDBLockClientOptions.builder(LOCK_CACHE_NAME_NO_HEARTBEATS)
.withConfiguration(Configurations.Laptop.latest())
.withCredentialProvider(CredentialProvider.fromEnvVar("MOMENTO_API_KEY"))
.withPartitionKeyName("pkey")
.withOwnerName("lock-client-lib")
.withLeaseDuration(2L)
.withCreateHeartbeatBackgroundThread(false)
.withTimeUnit(TimeUnit.SECONDS)
.build());
// momento client to verify lock assertions
cacheClient = CacheClient.create(CredentialProvider.fromEnvVar("MOMENTO_API_KEY"),
Configurations.Laptop.latest(), Duration.ofSeconds(60));
momentoLockClient = new MomentoLockClient(cacheClient, LOCK_CACHE_NAME);
momentoLockClientNoHeartBeats = new MomentoLockClient(cacheClient, LOCK_CACHE_NAME_NO_HEARTBEATS);
momentoLockClient.createLockCache(LOCK_CACHE_NAME);
momentoLockClient.createLockCache(LOCK_CACHE_NAME_NO_HEARTBEATS);
}
@Test
public void testAcquireLockWithDataAndSessionMonitor_Successful() throws Exception {
String partitionKey = generateUniquePartitionKey();
final LockItem lockItem =
momentoDynamoDBLockClient.acquireLock(AcquireLockOptions.builder(partitionKey)
.withData(ByteBuffer.wrap("data".getBytes()))
.withSessionMonitor(5L,
// empty callback
Optional.of(() -> {}))
.withTimeUnit(TimeUnit.SECONDS)
.build()); | package com.amazonaws.services.dynamodbv2;
public class MomentoDynamoDBLockClientTest {
private static MomentoDynamoDBLockClient momentoDynamoDBLockClient;
private static MomentoDynamoDBLockClient momentoDynamoDBLockClientWithoutHeartbeat;
private static MomentoLockClient momentoLockClient;
private static MomentoLockClient momentoLockClientNoHeartBeats;
private static CacheClient cacheClient;
private static String LOCK_CACHE_NAME = "lock";
private static String LOCK_CACHE_NAME_NO_HEARTBEATS = "lock_no_heartbeats";
@BeforeAll
public static void setup() {
momentoDynamoDBLockClient = new MomentoDynamoDBLockClient(MomentoDynamoDBLockClientOptions.builder("lock")
.withConfiguration(Configurations.Laptop.latest())
.withCredentialProvider(CredentialProvider.fromEnvVar("MOMENTO_API_KEY"))
.withPartitionKeyName("pkey")
.withOwnerName("lock-client-lib")
.withLeaseDuration(60L)
.withHeartbeatPeriod(3L)
.withCreateHeartbeatBackgroundThread(true)
.withTimeUnit(TimeUnit.SECONDS)
.withTotalNumBackgroundThreadsForHeartbeating(2)
.withTotalNumThreadsForAcquiringLocks(20)
.build());
momentoDynamoDBLockClientWithoutHeartbeat = new MomentoDynamoDBLockClient(MomentoDynamoDBLockClientOptions.builder(LOCK_CACHE_NAME_NO_HEARTBEATS)
.withConfiguration(Configurations.Laptop.latest())
.withCredentialProvider(CredentialProvider.fromEnvVar("MOMENTO_API_KEY"))
.withPartitionKeyName("pkey")
.withOwnerName("lock-client-lib")
.withLeaseDuration(2L)
.withCreateHeartbeatBackgroundThread(false)
.withTimeUnit(TimeUnit.SECONDS)
.build());
// momento client to verify lock assertions
cacheClient = CacheClient.create(CredentialProvider.fromEnvVar("MOMENTO_API_KEY"),
Configurations.Laptop.latest(), Duration.ofSeconds(60));
momentoLockClient = new MomentoLockClient(cacheClient, LOCK_CACHE_NAME);
momentoLockClientNoHeartBeats = new MomentoLockClient(cacheClient, LOCK_CACHE_NAME_NO_HEARTBEATS);
momentoLockClient.createLockCache(LOCK_CACHE_NAME);
momentoLockClient.createLockCache(LOCK_CACHE_NAME_NO_HEARTBEATS);
}
@Test
public void testAcquireLockWithDataAndSessionMonitor_Successful() throws Exception {
String partitionKey = generateUniquePartitionKey();
final LockItem lockItem =
momentoDynamoDBLockClient.acquireLock(AcquireLockOptions.builder(partitionKey)
.withData(ByteBuffer.wrap("data".getBytes()))
.withSessionMonitor(5L,
// empty callback
Optional.of(() -> {}))
.withTimeUnit(TimeUnit.SECONDS)
.build()); | Optional<MomentoLockItem> optionalMomentoLockItem = momentoLockClient.getLockFromMomento(partitionKey); | 2 | 2023-11-07 03:56:11+00:00 | 8k |
beminder/BeautyMinder | java/src/main/java/app/beautyminder/service/cosmetic/GPTService.java | [
{
"identifier": "Cosmetic",
"path": "java/src/main/java/app/beautyminder/domain/Cosmetic.java",
"snippet": "@Document(collection = \"cosmetics\") // mongodb\n@AllArgsConstructor\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\n@Getter\n@Builder\npublic class Cosmetic {\n\n @Id\n private String... | import app.beautyminder.domain.Cosmetic;
import app.beautyminder.domain.GPTReview;
import app.beautyminder.domain.Review;
import app.beautyminder.repository.CosmeticRepository;
import app.beautyminder.repository.GPTReviewRepository;
import app.beautyminder.service.review.ReviewService;
import io.github.flashvayne.chatgpt.dto.chat.ChatRole;
import io.github.flashvayne.chatgpt.dto.chat.MultiChatMessage;
import io.github.flashvayne.chatgpt.dto.chat.MultiChatRequest;
import io.github.flashvayne.chatgpt.service.ChatgptService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors; | 4,727 | package app.beautyminder.service.cosmetic;
@Slf4j
@RequiredArgsConstructor
@Service
public class GPTService {
private final ChatgptService chatgptService;
private final CosmeticRepository cosmeticRepository; | package app.beautyminder.service.cosmetic;
@Slf4j
@RequiredArgsConstructor
@Service
public class GPTService {
private final ChatgptService chatgptService;
private final CosmeticRepository cosmeticRepository; | private final ReviewService reviewService; | 5 | 2023-11-01 12:37:16+00:00 | 8k |
Xrayya/java-cli-pbpu | src/main/java/com/App.java | [
{
"identifier": "Auth",
"path": "src/main/java/com/CashierAppUtil/Auth.java",
"snippet": "public class Auth {\n public static Employee authenticate(String username, String password) {\n List<Manager> managers = new Record<Manager>(\"managers\", Manager[].class).readRecordFile();\n for (... | import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.UUID;
import com.CashierAppUtil.Auth;
import com.CashierAppUtil.CashierMachine;
import com.CashierAppUtil.ManagerMachine;
import com.Model.Employee;
import com.Model.EmployeeModel;
import com.Model.FoodCategory;
import com.Model.Manager;
import com.Model.Menu;
import com.Model.MenuOrder;
import com.Model.Order;
import com.RecordUtil.Log; | 5,303 | case "8":
printAllOrderNewOrders();
break;
case "9":
saveOrderToRecord();
break;
case "0":
logout();
keepLoop = false;
break;
case "00":
exit();
break;
default:
if (employee instanceof Manager) {
switch (inputNumber) {
case "10":
printOrderRecord();
break;
case "11":
addMenu();
break;
case "12":
removeMenu();
break;
case "13":
editMenu();
break;
}
} else {
System.out.println("Sorry, your input is not recognized, please input valid number");
}
break;
}
}
}
private static void printMainMenu() {
printBoldSeparator();
System.out.println("Cashier App");
printBoldSeparator();
System.out.println("1. Print All Menu");
System.out.println("2. Take Order");
System.out.println("3. Mark Order Done");
System.out.println("4. Edit Unfinished Order");
System.out.println("5. Cancel Unfinished Order"); // not mvp
System.out.println("6. Print Unfinished Orders"); // not mvp
System.out.println("7. Print New Finished Orders"); // not mvp
System.out.println("8. Print All new Orders");
System.out.println("9. Save Order to Record"); // tiap take order, not mvp
}
private static void printManagerAdditionalMainMenu() {
System.out.println("10. Print Order Record"); // not mvp
System.out.println("11. Add Menu");
System.out.println("12. Remove Menu");
System.out.println("13. Edit Menu");
}
private static void printExitMenus() {
System.out.println("0. Logout"); // buat keluar loop
System.out.println("00. Exit");
}
private static void login() {
while (employee == null) {
System.out.print("Enter username: ");
String username = input.nextLine();
System.out.print("Enter password: ");
String password = input.nextLine();
employee = Auth.authenticate(username, password);
if (employee == null) {
System.out.println("Username or password mismatch");
}
}
cashierMachine = employee.getMachine();
}
private static void logout() {
employee = null;
cashierMachine = null;
}
private static void exit() {
System.exit(0);
}
private static void printAllMenu() {
cashierMachine.printMenu();
}
private static void takeOrder() {
List<MenuOrder> orderedMenuList = new ArrayList<>();
boolean validate = true;
boolean menuExist = false;
printBoldSeparator();
System.out.println("Add Customer Orders");
printBoldSeparator();
cashierMachine.printMenu();
printtThinSeparator();
System.out.print("Input customer name: ");
String customerName = input.nextLine();
System.out.print("Input customer total money: ");
int customerMoney = input.nextInt();
System.out.print("Input customer table: ");
int customerTable = input.nextInt();
input.nextLine();
printtThinSeparator();
do {
System.out.print("Input short menu name: ");
String menuShortName = input.nextLine();
String menuQuantity = "";
while (!menuQuantity.matches("[0-9]+")) {
System.out.print("Input the Quantity: ");
menuQuantity = input.nextLine();
}
| package com;
/**
* Hello world!
*
*/
public class App {
private static final Scanner input = new Scanner(System.in);
private static Employee employee;
private static CashierMachine cashierMachine;
public static void main(String[] args) {
while (true) {
login();
runMainLoop();
}
}
private static void runMainLoop() {
boolean keepLoop = true;
while (keepLoop) {
printMainMenu();
if (employee instanceof Manager) {
printManagerAdditionalMainMenu();
}
printExitMenus();
System.out.print("Enter the number: ");
String inputNumber = input.nextLine();
switch (inputNumber) {
case "1":
printAllMenu();
break;
case "2":
takeOrder();
break;
case "3":
markOrderComplete();
break;
case "4":
editUnfinishedOrder();
break;
case "5":
cancelUnfinishedOrder();
break;
case "6":
printUnfinishedOrders();
break;
case "7":
printNewFinishedOrders();
break;
case "8":
printAllOrderNewOrders();
break;
case "9":
saveOrderToRecord();
break;
case "0":
logout();
keepLoop = false;
break;
case "00":
exit();
break;
default:
if (employee instanceof Manager) {
switch (inputNumber) {
case "10":
printOrderRecord();
break;
case "11":
addMenu();
break;
case "12":
removeMenu();
break;
case "13":
editMenu();
break;
}
} else {
System.out.println("Sorry, your input is not recognized, please input valid number");
}
break;
}
}
}
private static void printMainMenu() {
printBoldSeparator();
System.out.println("Cashier App");
printBoldSeparator();
System.out.println("1. Print All Menu");
System.out.println("2. Take Order");
System.out.println("3. Mark Order Done");
System.out.println("4. Edit Unfinished Order");
System.out.println("5. Cancel Unfinished Order"); // not mvp
System.out.println("6. Print Unfinished Orders"); // not mvp
System.out.println("7. Print New Finished Orders"); // not mvp
System.out.println("8. Print All new Orders");
System.out.println("9. Save Order to Record"); // tiap take order, not mvp
}
private static void printManagerAdditionalMainMenu() {
System.out.println("10. Print Order Record"); // not mvp
System.out.println("11. Add Menu");
System.out.println("12. Remove Menu");
System.out.println("13. Edit Menu");
}
private static void printExitMenus() {
System.out.println("0. Logout"); // buat keluar loop
System.out.println("00. Exit");
}
private static void login() {
while (employee == null) {
System.out.print("Enter username: ");
String username = input.nextLine();
System.out.print("Enter password: ");
String password = input.nextLine();
employee = Auth.authenticate(username, password);
if (employee == null) {
System.out.println("Username or password mismatch");
}
}
cashierMachine = employee.getMachine();
}
private static void logout() {
employee = null;
cashierMachine = null;
}
private static void exit() {
System.exit(0);
}
private static void printAllMenu() {
cashierMachine.printMenu();
}
private static void takeOrder() {
List<MenuOrder> orderedMenuList = new ArrayList<>();
boolean validate = true;
boolean menuExist = false;
printBoldSeparator();
System.out.println("Add Customer Orders");
printBoldSeparator();
cashierMachine.printMenu();
printtThinSeparator();
System.out.print("Input customer name: ");
String customerName = input.nextLine();
System.out.print("Input customer total money: ");
int customerMoney = input.nextInt();
System.out.print("Input customer table: ");
int customerTable = input.nextInt();
input.nextLine();
printtThinSeparator();
do {
System.out.print("Input short menu name: ");
String menuShortName = input.nextLine();
String menuQuantity = "";
while (!menuQuantity.matches("[0-9]+")) {
System.out.print("Input the Quantity: ");
menuQuantity = input.nextLine();
}
| List<Menu> allMenu = cashierMachine.getAllMenu(); | 7 | 2023-11-09 05:26:20+00:00 | 8k |
FallenDeity/GameEngine2DJava | src/main/java/engine/physics2d/components/CircleCollider.java | [
{
"identifier": "DebugDraw",
"path": "src/main/java/engine/renderer/DebugDraw.java",
"snippet": "public class DebugDraw {\n\tpublic final static int MAX_LINES = 100_000;\n\tprivate final static List<Line2D> lines = new ArrayList<>();\n\tprivate final static float[] vertices = new float[MAX_LINES * 6 * 2... | import engine.renderer.DebugDraw;
import engine.ruby.Window;
import org.joml.Vector2f; | 4,121 | package engine.physics2d.components;
public class CircleCollider extends Collider {
private float radius = 1.0f;
private boolean resetFixtures = false;
public float getRadius() {
return radius;
}
public void setRadius(float radius) {
this.radius = radius;
resetFixtures = true;
}
@Override
public void setOffset(Vector2f offset) {
super.setOffset(offset);
resetFixtures = true;
}
@Override
public void editorUpdate(float dt) {
Vector2f center = new Vector2f(gameObject.transform.getPosition()).add(getOffset()); | package engine.physics2d.components;
public class CircleCollider extends Collider {
private float radius = 1.0f;
private boolean resetFixtures = false;
public float getRadius() {
return radius;
}
public void setRadius(float radius) {
this.radius = radius;
resetFixtures = true;
}
@Override
public void setOffset(Vector2f offset) {
super.setOffset(offset);
resetFixtures = true;
}
@Override
public void editorUpdate(float dt) {
Vector2f center = new Vector2f(gameObject.transform.getPosition()).add(getOffset()); | DebugDraw.addCircle(center, radius); | 0 | 2023-11-04 13:19:21+00:00 | 8k |
RezaGooner/University-food-ordering | Frames/Profile/UpdatePassword.java | [
{
"identifier": "StyledButtonUI",
"path": "Classes/Theme/StyledButtonUI.java",
"snippet": "public class StyledButtonUI extends BasicButtonUI {\r\n\r\n @Override\r\n public void installUI (JComponent c) {\r\n super.installUI(c);\r\n AbstractButton button = (AbstractButton) c;\r\n ... | import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import static Classes.Pathes.FilesPath.icon;
import static Classes.Theme.SoundEffect.errorSound;
import static Classes.Theme.SoundEffect.successSound;
import static Classes.Pathes.FilesPath.UserPassPath;
import Classes.Theme.StyledButtonUI;
import Frames.LoginFrame;
| 6,493 | package Frames.Profile;
/*
این کد برای این است که به کاربران اجازه دهد تا رمز عبور خود را تغییر دهند.
این برنامه با ساخت یک پنجره شروع میشود. در این پنجره دو فیلد رمز عبور برای رمز عبور جدید و تایید آن و یک دکمه "تغییر رمز عبور" وجود دارد.
این کلاس یک متد به نام `isValidPassword` نیز تعریف میکند که یک رشته را به عنوان ورودی میگیرد و
بررسی میکند که آیا آن برای یک رمز عبور معتبر کافی است یا نه.
شرایطی که برای یک رمز عبور معتبر تعیین شدهاند این است که رمز عبور حداقل باید 8 کاراکتر باشد،
شامل حداقل یک عدد، یک حرف کوچک، یک حرف بزرگ و یک کاراکتر خاص (مانند !، @، # و غیره) باشد.
این متد در صورتی که رمز عبور تمامی شرایط را برآورده کند، `true` و در غیر این صورت `false` برمیگرداند.
سازندهی کلاس یک رشته به نام `Id` را به عنوان ورودی دریافت میکند که شناسهی کاربر را نشان میدهد.
هنگامی که کاربر روی دکمه "تغییر رمز عبور" کلیک میکند، سازنده مقادیر وارد شده در فیلدهای رمز عبور را دریافت میکند،
با استفاده از متد `isValidPassword` اعتبارسنجی میکند و آنها را با یکدیگر مقایسه میکند تا مطمئن شود که هر دوی آنها یکسان هستند.
اگر مقادیر معتبر و مطابق باشند، سازنده یک فایل حاوی اطلاعات کاربر را خوانده و رمز عبور کاربر با شناسهی وارد شده راتغییر میدهد.
سپس یک پیام برای اطلاع کاربر از موفقیت تغییر رمز عبور نمایش داده میشود و پنجره فعلی بسته میشود. حال کاربر میتواند با رمز عبور جدید وارد شود.
این کد همچنین یک نوار منو با دو آیتم "بازگشت" و "خروج" ایجاد میکند.
با کلیک بر روی آیتم "بازگشت"، کاربر با یک پیام تأییدی تأیید مواجه میشود
تا تأیید کند که آیا میخواهد از پنجرهی فعلی خارج شده و به پنجرهی قبلی بازگردد یا نه.
همچنین با کلیک بر روی آیتم "خروج"، کاربر با یک پیام تأیید مواجه میشود تا تأیید کند که آیا میخواهد از برنامه خارج شود یا نه.
`````````````````````````````````````````````````````
It represents a graphical user interface for updating a user's password. Here is a breakdown of the code:
1. The class imports various classes and libraries for GUI components, event handling, file operations, and sound effects.
2. The class extends the `JFrame` class.
3. The class defines instance variables, including a string variable for storing the user's ID, password fields for entering the new and confirmed passwords, and a regular expression method for validating passwords.
4. The constructor of the class initializes the frame, sets its properties (title, size, icon, etc.), and creates the necessary GUI components (labels, password fields, button, etc.) using Swing.
5. The constructor sets up the menu bar, which contains "Back" and "Exit" items.
6. The constructor adds action listeners to the "Back" and "Exit" items. If the user chooses to go back, a confirmation dialog is shown, and if confirmed, the current frame is disposed, and a new `LoginFrame` is created. If the user chooses to exit, a confirmation dialog is shown, and if confirmed, the current frame is disposed.
7. The constructor adds the GUI components to a panel and sets the panel as the content pane of the frame.
8. The constructor sets the frame as visible and non-resizable.
9. The `actionPerformed` method is implemented from the `ActionListener` interface and is called when the change password button is clicked.
10. The `actionPerformed` method retrieves the values entered in the password fields, validates the input, and performs the necessary operations.
11. If any of the fields are empty, an error sound effect is played, an error message dialog is shown, and the method returns.
12. If the new password does not meet the specified criteria (numbers, lowercase and uppercase letters, special characters, minimum length), an error sound effect is played, an error message dialog is shown, and the method returns.
13. If the new password and the confirmed password do not match, an error sound effect is played, an error message dialog is shown, and the method returns.
14. The method reads the user password file (`UserPassPath`) and searches for a matching user ID.
15. If a match is found, the user's password is updated in the file, a success sound effect is played, a success message dialog is shown, the current frame is disposed, and a new `LoginFrame` is created.
16. If the user ID is not found, an error sound effect is played, an error message dialog is shown, and the method returns.
17. If there is an exception during file operations, an error sound effect is played, an error message dialog is shown, and the method returns.
Overall, this code provides a GUI for updating a user's password, validates user input, searches for a match in a password file, and handles success and error scenarios accordingly.
*/
public class UpdatePassword extends JFrame {
private String id ;
private final JPasswordField newPasswordField;
private final JPasswordField confirmPasswordField;
public static boolean isValidPassword(String str) {
return str.matches("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[-+|!@#%^&*()-_=/.])(?=\\S+$).{8,}$");
}
public UpdatePassword(String Id) {
setTitle("تغییر رمز عبور");
setSize(400, 150);
setIconImage(icon.getImage());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
JLabel newPasswordLabel = new JLabel(": رمز عبورجدید");
newPasswordLabel.setHorizontalAlignment(SwingConstants.CENTER);
newPasswordField = new JPasswordField(10);
JLabel confirmPasswordLabel = new JLabel(": تکرار رمز عبور جدید");
confirmPasswordLabel.setHorizontalAlignment(SwingConstants.CENTER);
confirmPasswordField = new JPasswordField(10);
JButton changePasswordButton = new JButton("تغییر رمز عبور");
changePasswordButton.setUI(new StyledButtonUI());
changePasswordButton.setBackground(ForgotPassword.colorButton);
JPanel panel = new JPanel(new GridLayout(3, 1));
panel.setBackground(ForgotPassword.colorBackground);
panel.add(newPasswordLabel);
panel.add(newPasswordField);
panel.add(confirmPasswordLabel);
panel.add(confirmPasswordField);
panel.add(changePasswordButton);
JMenuBar menuBar = new JMenuBar();
menuBar.setBackground(ForgotPassword.colorButton);
setJMenuBar(menuBar);
JMenuItem backItem = new JMenuItem("بازگشت");
backItem.setBackground(ForgotPassword.colorButton);
menuBar.add(backItem);
backItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Object[] options = {"خیر", "بله"};
int exitResult = JOptionPane.showOptionDialog(null, "آیا از ادامه مراحل انصراف می دهید؟", "بازگشت به صفحه اصلی",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
null, options, options[0]);
if (exitResult == JOptionPane.NO_OPTION) {
dispose();
| package Frames.Profile;
/*
این کد برای این است که به کاربران اجازه دهد تا رمز عبور خود را تغییر دهند.
این برنامه با ساخت یک پنجره شروع میشود. در این پنجره دو فیلد رمز عبور برای رمز عبور جدید و تایید آن و یک دکمه "تغییر رمز عبور" وجود دارد.
این کلاس یک متد به نام `isValidPassword` نیز تعریف میکند که یک رشته را به عنوان ورودی میگیرد و
بررسی میکند که آیا آن برای یک رمز عبور معتبر کافی است یا نه.
شرایطی که برای یک رمز عبور معتبر تعیین شدهاند این است که رمز عبور حداقل باید 8 کاراکتر باشد،
شامل حداقل یک عدد، یک حرف کوچک، یک حرف بزرگ و یک کاراکتر خاص (مانند !، @، # و غیره) باشد.
این متد در صورتی که رمز عبور تمامی شرایط را برآورده کند، `true` و در غیر این صورت `false` برمیگرداند.
سازندهی کلاس یک رشته به نام `Id` را به عنوان ورودی دریافت میکند که شناسهی کاربر را نشان میدهد.
هنگامی که کاربر روی دکمه "تغییر رمز عبور" کلیک میکند، سازنده مقادیر وارد شده در فیلدهای رمز عبور را دریافت میکند،
با استفاده از متد `isValidPassword` اعتبارسنجی میکند و آنها را با یکدیگر مقایسه میکند تا مطمئن شود که هر دوی آنها یکسان هستند.
اگر مقادیر معتبر و مطابق باشند، سازنده یک فایل حاوی اطلاعات کاربر را خوانده و رمز عبور کاربر با شناسهی وارد شده راتغییر میدهد.
سپس یک پیام برای اطلاع کاربر از موفقیت تغییر رمز عبور نمایش داده میشود و پنجره فعلی بسته میشود. حال کاربر میتواند با رمز عبور جدید وارد شود.
این کد همچنین یک نوار منو با دو آیتم "بازگشت" و "خروج" ایجاد میکند.
با کلیک بر روی آیتم "بازگشت"، کاربر با یک پیام تأییدی تأیید مواجه میشود
تا تأیید کند که آیا میخواهد از پنجرهی فعلی خارج شده و به پنجرهی قبلی بازگردد یا نه.
همچنین با کلیک بر روی آیتم "خروج"، کاربر با یک پیام تأیید مواجه میشود تا تأیید کند که آیا میخواهد از برنامه خارج شود یا نه.
`````````````````````````````````````````````````````
It represents a graphical user interface for updating a user's password. Here is a breakdown of the code:
1. The class imports various classes and libraries for GUI components, event handling, file operations, and sound effects.
2. The class extends the `JFrame` class.
3. The class defines instance variables, including a string variable for storing the user's ID, password fields for entering the new and confirmed passwords, and a regular expression method for validating passwords.
4. The constructor of the class initializes the frame, sets its properties (title, size, icon, etc.), and creates the necessary GUI components (labels, password fields, button, etc.) using Swing.
5. The constructor sets up the menu bar, which contains "Back" and "Exit" items.
6. The constructor adds action listeners to the "Back" and "Exit" items. If the user chooses to go back, a confirmation dialog is shown, and if confirmed, the current frame is disposed, and a new `LoginFrame` is created. If the user chooses to exit, a confirmation dialog is shown, and if confirmed, the current frame is disposed.
7. The constructor adds the GUI components to a panel and sets the panel as the content pane of the frame.
8. The constructor sets the frame as visible and non-resizable.
9. The `actionPerformed` method is implemented from the `ActionListener` interface and is called when the change password button is clicked.
10. The `actionPerformed` method retrieves the values entered in the password fields, validates the input, and performs the necessary operations.
11. If any of the fields are empty, an error sound effect is played, an error message dialog is shown, and the method returns.
12. If the new password does not meet the specified criteria (numbers, lowercase and uppercase letters, special characters, minimum length), an error sound effect is played, an error message dialog is shown, and the method returns.
13. If the new password and the confirmed password do not match, an error sound effect is played, an error message dialog is shown, and the method returns.
14. The method reads the user password file (`UserPassPath`) and searches for a matching user ID.
15. If a match is found, the user's password is updated in the file, a success sound effect is played, a success message dialog is shown, the current frame is disposed, and a new `LoginFrame` is created.
16. If the user ID is not found, an error sound effect is played, an error message dialog is shown, and the method returns.
17. If there is an exception during file operations, an error sound effect is played, an error message dialog is shown, and the method returns.
Overall, this code provides a GUI for updating a user's password, validates user input, searches for a match in a password file, and handles success and error scenarios accordingly.
*/
public class UpdatePassword extends JFrame {
private String id ;
private final JPasswordField newPasswordField;
private final JPasswordField confirmPasswordField;
public static boolean isValidPassword(String str) {
return str.matches("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[-+|!@#%^&*()-_=/.])(?=\\S+$).{8,}$");
}
public UpdatePassword(String Id) {
setTitle("تغییر رمز عبور");
setSize(400, 150);
setIconImage(icon.getImage());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
JLabel newPasswordLabel = new JLabel(": رمز عبورجدید");
newPasswordLabel.setHorizontalAlignment(SwingConstants.CENTER);
newPasswordField = new JPasswordField(10);
JLabel confirmPasswordLabel = new JLabel(": تکرار رمز عبور جدید");
confirmPasswordLabel.setHorizontalAlignment(SwingConstants.CENTER);
confirmPasswordField = new JPasswordField(10);
JButton changePasswordButton = new JButton("تغییر رمز عبور");
changePasswordButton.setUI(new StyledButtonUI());
changePasswordButton.setBackground(ForgotPassword.colorButton);
JPanel panel = new JPanel(new GridLayout(3, 1));
panel.setBackground(ForgotPassword.colorBackground);
panel.add(newPasswordLabel);
panel.add(newPasswordField);
panel.add(confirmPasswordLabel);
panel.add(confirmPasswordField);
panel.add(changePasswordButton);
JMenuBar menuBar = new JMenuBar();
menuBar.setBackground(ForgotPassword.colorButton);
setJMenuBar(menuBar);
JMenuItem backItem = new JMenuItem("بازگشت");
backItem.setBackground(ForgotPassword.colorButton);
menuBar.add(backItem);
backItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Object[] options = {"خیر", "بله"};
int exitResult = JOptionPane.showOptionDialog(null, "آیا از ادامه مراحل انصراف می دهید؟", "بازگشت به صفحه اصلی",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
null, options, options[0]);
if (exitResult == JOptionPane.NO_OPTION) {
dispose();
| new LoginFrame();
| 1 | 2023-11-03 08:35:22+00:00 | 8k |
EaindrayFromEarth/Collaborative_Blog_Version_Control_Management-System | java/com/we_write/controller/BlogController.java | [
{
"identifier": "Blog",
"path": "java/com/we_write/entity/Blog.java",
"snippet": "@Entity\r\n@Getter\r\n@Setter\r\n@AllArgsConstructor\r\n@NoArgsConstructor\r\n\r\n\r\n@Table(\r\n name = \"blogs\", uniqueConstraints = {@UniqueConstraint(columnNames = {\"blog_id\"})}\r\n) \r\npublic class Blog {\r... | import java.security.Principal;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
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.RequestAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.we_write.entity.Blog;
import com.we_write.entity.BlogVersion;
import com.we_write.entity.Review;
import com.we_write.entity.ReviewStatus;
import com.we_write.entity.User;
import com.we_write.payload.BlogDto;
import com.we_write.payload.BlogVersionRequest;
import com.we_write.payload.ReviewRequest;
import com.we_write.repository.UserRepository;
import com.we_write.service.BlogService;
import com.we_write.service.ReviewService;
import com.we_write.service.UserService;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
| 5,120 |
package com.we_write.controller;
@RestController
@RequestMapping("/api/blogs")
@Tag(
name = "CRUD REST APIs for Blogs"
)
public class BlogController {
@Autowired
private BlogService blogService;
@Autowired
private ReviewService reviewService;
@Autowired
private UserService userService;
@Autowired
private UserRepository userRepository;
@PostMapping("/{blogId}/versions")
public ResponseEntity<?> createBlogVersion(
@PathVariable Long blogId,
@RequestBody BlogVersionRequest request,
Principal principal
) {
|
package com.we_write.controller;
@RestController
@RequestMapping("/api/blogs")
@Tag(
name = "CRUD REST APIs for Blogs"
)
public class BlogController {
@Autowired
private BlogService blogService;
@Autowired
private ReviewService reviewService;
@Autowired
private UserService userService;
@Autowired
private UserRepository userRepository;
@PostMapping("/{blogId}/versions")
public ResponseEntity<?> createBlogVersion(
@PathVariable Long blogId,
@RequestBody BlogVersionRequest request,
Principal principal
) {
| User user = userRepository.findByUsername(principal.getName()).orElse(null);
| 4 | 2023-11-05 05:44:23+00:00 | 8k |
antoKeinanen/Serverselector | src/main/java/dev/antok/serverselector/Serverselector.java | [
{
"identifier": "JoinCommand",
"path": "src/main/java/dev/antok/serverselector/command/JoinCommand.java",
"snippet": "public class JoinCommand implements CommandExecutor {\n\n final JoinInventory joinInventory;\n final Logger logger;\n final Config.ConfigFile configFile;\n\n public JoinComma... | import dev.antok.serverselector.command.JoinCommand;
import dev.antok.serverselector.config.Config;
import dev.antok.serverselector.inventory.JoinInventory;
import dev.antok.serverselector.config.ConfigManager;
import dev.antok.serverselector.util.SendPlayerToServer;
import dev.antok.serverselector.util.ServerStarter;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.HashMap;
import java.util.logging.Logger; | 4,117 | package dev.antok.serverselector;
public final class Serverselector extends JavaPlugin {
public HashMap<Player, Integer> joiningPlayers = new HashMap<>();
@Override
public void onEnable() {
Logger logger = getLogger();
final Serverselector instance = this;
Config.ConfigFile configFile = new ConfigManager(this).configFile;
MiniMessage mm = MiniMessage.miniMessage();
final ServerStarter serverStarter = new ServerStarter(logger, configFile);
final JoinInventory joinInventory = new JoinInventory(logger, serverStarter, this, configFile);
this.getServer().getPluginManager().registerEvents(joinInventory, this);
this.getCommand("join").setExecutor(new JoinCommand(logger, joinInventory, configFile));
this.getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
Bukkit.getScheduler().scheduleSyncRepeatingTask(this, () -> {
HashMap<Integer, Boolean> statusCache = new HashMap<>();
for (Player player : joiningPlayers.keySet()) {
final Integer serverId = joiningPlayers.get(player);
Config.Item server = configFile.server.stream().filter(item -> item.serverId == serverId).findFirst().orElse(null);
if (server == null) {
player.sendMessage(configFile.messages.noSuchServer);
logger.severe(String.format("No server with id %d found", serverId));
joiningPlayers.remove(player);
continue;
}
if (statusCache.containsKey(serverId)) {
if (statusCache.get(serverId)) {
joiningPlayers.remove(player); | package dev.antok.serverselector;
public final class Serverselector extends JavaPlugin {
public HashMap<Player, Integer> joiningPlayers = new HashMap<>();
@Override
public void onEnable() {
Logger logger = getLogger();
final Serverselector instance = this;
Config.ConfigFile configFile = new ConfigManager(this).configFile;
MiniMessage mm = MiniMessage.miniMessage();
final ServerStarter serverStarter = new ServerStarter(logger, configFile);
final JoinInventory joinInventory = new JoinInventory(logger, serverStarter, this, configFile);
this.getServer().getPluginManager().registerEvents(joinInventory, this);
this.getCommand("join").setExecutor(new JoinCommand(logger, joinInventory, configFile));
this.getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
Bukkit.getScheduler().scheduleSyncRepeatingTask(this, () -> {
HashMap<Integer, Boolean> statusCache = new HashMap<>();
for (Player player : joiningPlayers.keySet()) {
final Integer serverId = joiningPlayers.get(player);
Config.Item server = configFile.server.stream().filter(item -> item.serverId == serverId).findFirst().orElse(null);
if (server == null) {
player.sendMessage(configFile.messages.noSuchServer);
logger.severe(String.format("No server with id %d found", serverId));
joiningPlayers.remove(player);
continue;
}
if (statusCache.containsKey(serverId)) {
if (statusCache.get(serverId)) {
joiningPlayers.remove(player); | SendPlayerToServer.sendPlayerToServer(player, server.serverName, instance); | 4 | 2023-11-09 14:38:55+00:00 | 8k |
schadfield/shogi-explorer | src/main/java/com/chadfield/shogiexplorer/main/AnalysisManager.java | [
{
"identifier": "Analysis",
"path": "src/main/java/com/chadfield/shogiexplorer/objects/Analysis.java",
"snippet": "public class Analysis {\n\n private List<List<Position>> analysisPositionList;\n private List<Object[]> tableRows;\n private List<Integer> scoreList;\n\n /**\n * @return the... | import com.chadfield.shogiexplorer.objects.Analysis;
import com.chadfield.shogiexplorer.objects.AnalysisParameter;
import com.chadfield.shogiexplorer.objects.Game;
import com.chadfield.shogiexplorer.objects.Position;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.security.AnyTypePermission;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.xy.DefaultIntervalXYDataset; | 4,994 | /*
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.main;
public class AnalysisManager {
private AnalysisManager() {
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.main;
public class AnalysisManager {
private AnalysisManager() {
throw new IllegalStateException("Utility class");
}
| public static void save(Analysis analysis, File kifFile) { | 0 | 2023-11-08 09:24:57+00:00 | 8k |
refrainsclub/npcs | src/main/java/nz/blair/npcs/NpcsPlugin.java | [
{
"identifier": "PacketInboundListener",
"path": "src/main/java/nz/blair/npcs/listeners/PacketInboundListener.java",
"snippet": "public class PacketInboundListener {\n private final NpcManager npcManager;\n\n public PacketInboundListener(NpcManager npcManager) {\n this.npcManager = npcManag... | import nz.blair.npcs.listeners.PacketInboundListener;
import nz.blair.npcs.listeners.PlayerListener;
import nz.blair.npcs.npcs.Npc;
import nz.blair.npcs.npcs.NpcFactory;
import nz.blair.npcs.npcs.NpcManager;
import nz.blair.npcs.packets.PacketHandlerInjector;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin; | 6,724 | package nz.blair.npcs;
/**
* The main plugin class.
* This is the entry point of the plugin.
* This class is responsible for creating the API singleton and registering events.
*/
@SuppressWarnings("unused") // This class is used by other plugins
public final class NpcsPlugin extends JavaPlugin {
private static NpcsApi npcsApi;
private NpcManager npcManager;
@Override
public void onEnable() {
npcManager = new NpcManager();
NpcFactory npcFactory = new NpcFactory(this);
npcsApi = new NpcsApi(npcManager, npcFactory);
PacketInboundListener packetInboundListener = new PacketInboundListener(npcManager);
PacketHandlerInjector packetHandlerInjector = new PacketHandlerInjector(packetInboundListener);
PluginManager pluginManager = getServer().getPluginManager(); | package nz.blair.npcs;
/**
* The main plugin class.
* This is the entry point of the plugin.
* This class is responsible for creating the API singleton and registering events.
*/
@SuppressWarnings("unused") // This class is used by other plugins
public final class NpcsPlugin extends JavaPlugin {
private static NpcsApi npcsApi;
private NpcManager npcManager;
@Override
public void onEnable() {
npcManager = new NpcManager();
NpcFactory npcFactory = new NpcFactory(this);
npcsApi = new NpcsApi(npcManager, npcFactory);
PacketInboundListener packetInboundListener = new PacketInboundListener(npcManager);
PacketHandlerInjector packetHandlerInjector = new PacketHandlerInjector(packetInboundListener);
PluginManager pluginManager = getServer().getPluginManager(); | pluginManager.registerEvents(new PlayerListener(packetHandlerInjector, npcManager, this), this); | 1 | 2023-11-01 01:14:41+00:00 | 8k |
cyljx9999/talktime-Java | talktime-framework/talktime-service/src/main/java/com/qingmeng/config/adapt/ChatAdapt.java | [
{
"identifier": "WsGroupInviteVO",
"path": "talktime-framework/talktime-service/src/main/java/com/qingmeng/config/netty/vo/WsGroupInviteVO.java",
"snippet": "@Data\npublic class WsGroupInviteVO {\n\n /**\n * 标题\n */\n private String title;\n\n /**\n * 内容\n */\n private String... | import cn.hutool.core.util.StrUtil;
import com.qingmeng.config.netty.vo.WsGroupInviteVO;
import com.qingmeng.entity.*;
import com.qingmeng.enums.chat.*;
import com.qingmeng.enums.user.CloseOrOpenStatusEnum;
import com.qingmeng.utils.CommonUtils;
import com.qingmeng.vo.chat.GroupDetailInfo;
import com.qingmeng.vo.user.ManagerInfo;
import com.qingmeng.vo.user.SimpleUserInfo;
import java.util.*;
import java.util.stream.Collectors; | 4,883 | package com.qingmeng.config.adapt;
/**
* @author 清梦
* @version 1.0.0
* @Description
* @createTime 2023年12月06日 22:15:00
*/
public class ChatAdapt {
/**
* 建立聊天群房间
*
* @param roomId 房间 ID
* @return {@link ChatGroupRoom }
* @author qingmeng
* @createTime: 2023/12/06 22:19:08
*/
public static ChatGroupRoom buildChatGroupRoom(Long roomId) {
ChatGroupRoom chatGroupRoom = new ChatGroupRoom();
chatGroupRoom.setRoomId(roomId);
chatGroupRoom.setRoomStatus(RoomStatusEnum.NORMAL.getCode());
return chatGroupRoom;
}
/**
* 建立保存聊天群成员列表
*
* @param groupRoomId 组会议室 ID
* @param userIds 用户id集合
* @return {@link List }<{@link ChatGroupMember }>
* @author qingmeng
* @createTime: 2023/12/06 22:22:19
*/
public static List<ChatGroupMember> buildSaveChatGroupMemberList(Long groupRoomId, List<Long> userIds) {
return userIds.stream().map(userId -> {
ChatGroupMember chatGroupMember = new ChatGroupMember();
chatGroupMember.setGroupRoomId(groupRoomId);
chatGroupMember.setUserId(userId);
return chatGroupMember;
}).collect(Collectors.toList());
}
/**
* 建立聊天群管理
*
* @param userId 用户 ID
* @param roomGroupId 会议室组 ID
* @return {@link ChatGroupManager }
* @author qingmeng
* @createTime: 2023/12/06 22:38:35
*/
public static ChatGroupManager buildChatGroupOwner(Long userId, Long roomGroupId) {
ChatGroupManager chatGroupManager = new ChatGroupManager();
chatGroupManager.setRoomGroupId(roomGroupId);
chatGroupManager.setUserId(userId);
chatGroupManager.setRoleType(GroupRoleEnum.GROUP_OWNER.getCode());
return chatGroupManager;
}
/**
* 建立聊天群个人设置保存列表
*
* @param roomGroupId 会议室组 ID
* @param userIds 用户 ID
* @return {@link List }<{@link ChatGroupPersonalSetting }>
* @author qingmeng
* @createTime: 2023/12/06 22:44:31
*/
public static List<ChatGroupPersonalSetting> buildChatGroupPersonalSettingSaveList(Long roomGroupId, List<Long> userIds) {
return userIds.stream().map(userId -> {
ChatGroupPersonalSetting chatGroupPersonalSetting = new ChatGroupPersonalSetting();
chatGroupPersonalSetting.setGroupRoomId(roomGroupId);
chatGroupPersonalSetting.setUserId(userId);
chatGroupPersonalSetting.setTopStatus(MessageTopStatusEnum.NORMAL.getCode());
chatGroupPersonalSetting.setDisplayNameStatus(DisplayNameStatusEnum.DISPLAY.getCode());
chatGroupPersonalSetting.setRemindStatus(RemindStatusEnum.OPEN.getCode());
return chatGroupPersonalSetting;
}).collect(Collectors.toList());
}
/**
* 构建默认聊天组设置
*
* @param groupRoomId 组会议室 ID
* @param sysUser sys 用户
* @param groupRoomQrcode 团体房二维码
* @return {@link ChatGroupSetting }
* @author qingmeng
* @createTime: 2023/12/06 22:51:18
*/
public static ChatGroupSetting buildDefaultChatGroupSetting(Long groupRoomId, SysUser sysUser, String groupRoomQrcode) {
ChatGroupSetting chatGroupSetting = new ChatGroupSetting();
chatGroupSetting.setGroupRoomId(groupRoomId);
chatGroupSetting.setGroupRoomName("由" + sysUser.getUserName() + "发起的群聊");
chatGroupSetting.setGroupRoomAvatar(sysUser.getUserAvatar());
chatGroupSetting.setGroupRoomQrcode(groupRoomQrcode);
chatGroupSetting.setInvitationConfirmation(CloseOrOpenStatusEnum.CLOSE.getCode());
return chatGroupSetting;
}
/**
* 建立邀请组列表
*
* @param ids IDS
* @param chatGroupSetting 聊天组设置
* @param userName 用户名
* @return {@link List }<{@link WsGroupInviteVO }>
* @author qingmeng
* @createTime: 2023/12/07 09:20:58
*/
public static List<WsGroupInviteVO> buildInviteGroupList(List<Long> ids, ChatGroupSetting chatGroupSetting, String userName) {
// todo
return new ArrayList<>();
}
/**
* 建立保存聊天组成员
*
* @param userId 用户 ID
* @param groupRoomId 组会议室 ID
* @return {@link ChatGroupMember }
* @author qingmeng
* @createTime: 2023/12/08 08:51:00
*/
public static ChatGroupMember buildSaveChatGroupMember(Long userId, Long groupRoomId) {
return buildSaveChatGroupMemberList(userId, Collections.singletonList(groupRoomId)).get(0);
}
/**
* 建立聊天组设置
*
* @param userId 用户 ID
* @param groupRoomId 组会议室 ID
* @return {@link ChatGroupPersonalSetting }
* @author qingmeng
* @createTime: 2023/12/08 08:50:58
*/
public static ChatGroupPersonalSetting buildChatGroupSetting(Long userId, Long groupRoomId) {
return buildChatGroupPersonalSettingSaveList(userId, Collections.singletonList(groupRoomId)).get(0);
}
/**
* 建立聊天群管理列表
*
* @param groupRoomId 组会议室 ID
* @param ids IDS
* @return {@link List }<{@link ChatGroupManager }>
* @author qingmeng
* @createTime: 2023/12/08 11:32:59
*/
public static List<ChatGroupManager> buildChatGroupManagementList(Long groupRoomId, List<Long> ids) {
return ids.stream().map(id -> {
ChatGroupManager chatGroupManager = new ChatGroupManager();
chatGroupManager.setRoomGroupId(groupRoomId);
chatGroupManager.setUserId(id);
chatGroupManager.setRoleType(GroupRoleEnum.GROUP_MANAGEMENT.getCode());
return chatGroupManager;
}).collect(Collectors.toList());
}
/**
* 构造 群聊详细信息
*
* @param userId 用户 ID
* @param memberIds 会员 ID
* @param friendIds 好友ID
* @param chatGroupSetting 聊天组设置
* @param chatGroupPersonalSetting 聊天组个人设置
* @param friendSettingList 好友设置列表
* @param userMap 用户集合
* @param chatGroupPersonalSettingMap 聊天群个人设置集合
* @return {@link GroupDetailInfo }
* @author qingmeng
* @createTime: 2023/12/09 14:55:20
*/
public static GroupDetailInfo buildGroupDetailInfo(Long userId,
List<Long> memberIds,
List<Long> friendIds,
ChatGroupSetting chatGroupSetting,
ChatGroupPersonalSetting chatGroupPersonalSetting,
List<SysUserFriendSetting> friendSettingList,
Map<Long, SysUser> userMap,
Map<String, ChatGroupPersonalSetting> chatGroupPersonalSettingMap,
List<ChatGroupManager> managerAllList) {
GroupDetailInfo groupDetailInfo = new GroupDetailInfo();
groupDetailInfo.setGroupRoomName(chatGroupSetting.getGroupRoomName());
groupDetailInfo.setGroupRoomAvatar(chatGroupSetting.getGroupRoomAvatar());
groupDetailInfo.setGroupNotice(chatGroupSetting.getGroupNotice());
groupDetailInfo.setInvitationConfirmation(chatGroupSetting.getInvitationConfirmation());
groupDetailInfo.setGroupRoomQrCode(chatGroupSetting.getGroupRoomQrcode());
groupDetailInfo.setTopStatus(chatGroupPersonalSetting.getTopStatus());
groupDetailInfo.setDisplayNameStatus(chatGroupPersonalSetting.getDisplayNameStatus());
groupDetailInfo.setNickName(chatGroupPersonalSetting.getNickName());
groupDetailInfo.setRemindStatus(chatGroupPersonalSetting.getRemindStatus());
Map<String, List<?>> map = getMemberListAndManagerList(userId, memberIds, friendIds, friendSettingList, userMap, chatGroupPersonalSettingMap, managerAllList);
groupDetailInfo.setMemberList((List<SimpleUserInfo>) map.get("memberList"));
groupDetailInfo.setManagerList((List<ManagerInfo>) map.get("managerInfoList"));
return groupDetailInfo;
}
/**
* 获取成员列表
*
* @param userId 用户 ID
* @param memberIds 会员 ID
* @param friendIds 好友ID
* @param friendSettingList 好友设置列表
* @param userMap 用户集合
* @param chatGroupPersonalSettingMap 聊天群个人设置集合
* @param managerAllList 管理员 列表
* @return {@link Map }<{@link String }, {@link List }<{@link ? }>>
* @author qingmeng
* @createTime: 2023/12/11 11:06:48
*/
private static Map<String, List<?>> getMemberListAndManagerList(Long userId,
List<Long> memberIds,
List<Long> friendIds,
List<SysUserFriendSetting> friendSettingList,
Map<Long, SysUser> userMap,
Map<String, ChatGroupPersonalSetting> chatGroupPersonalSettingMap,
List<ChatGroupManager> managerAllList) {
Map<String, List<?>> map = new HashMap<>(2);
List<SimpleUserInfo> memberList = new ArrayList<>();
List<ManagerInfo> managerInfoList = new ArrayList<>();
memberIds.forEach(id -> {
SimpleUserInfo userInfo = new SimpleUserInfo();
boolean isFriend = friendIds.contains(id);
if (isFriend) {
// 获取 当前用户 对 对方 的设置数据,判断是否进行备注
SysUserFriendSetting friendSetting = friendSettingList.stream()
.filter(setting -> {
// 通过tagKey和userId定位数据 tagKey:1-2 userId:1 表示用户1对用户2的设置 | package com.qingmeng.config.adapt;
/**
* @author 清梦
* @version 1.0.0
* @Description
* @createTime 2023年12月06日 22:15:00
*/
public class ChatAdapt {
/**
* 建立聊天群房间
*
* @param roomId 房间 ID
* @return {@link ChatGroupRoom }
* @author qingmeng
* @createTime: 2023/12/06 22:19:08
*/
public static ChatGroupRoom buildChatGroupRoom(Long roomId) {
ChatGroupRoom chatGroupRoom = new ChatGroupRoom();
chatGroupRoom.setRoomId(roomId);
chatGroupRoom.setRoomStatus(RoomStatusEnum.NORMAL.getCode());
return chatGroupRoom;
}
/**
* 建立保存聊天群成员列表
*
* @param groupRoomId 组会议室 ID
* @param userIds 用户id集合
* @return {@link List }<{@link ChatGroupMember }>
* @author qingmeng
* @createTime: 2023/12/06 22:22:19
*/
public static List<ChatGroupMember> buildSaveChatGroupMemberList(Long groupRoomId, List<Long> userIds) {
return userIds.stream().map(userId -> {
ChatGroupMember chatGroupMember = new ChatGroupMember();
chatGroupMember.setGroupRoomId(groupRoomId);
chatGroupMember.setUserId(userId);
return chatGroupMember;
}).collect(Collectors.toList());
}
/**
* 建立聊天群管理
*
* @param userId 用户 ID
* @param roomGroupId 会议室组 ID
* @return {@link ChatGroupManager }
* @author qingmeng
* @createTime: 2023/12/06 22:38:35
*/
public static ChatGroupManager buildChatGroupOwner(Long userId, Long roomGroupId) {
ChatGroupManager chatGroupManager = new ChatGroupManager();
chatGroupManager.setRoomGroupId(roomGroupId);
chatGroupManager.setUserId(userId);
chatGroupManager.setRoleType(GroupRoleEnum.GROUP_OWNER.getCode());
return chatGroupManager;
}
/**
* 建立聊天群个人设置保存列表
*
* @param roomGroupId 会议室组 ID
* @param userIds 用户 ID
* @return {@link List }<{@link ChatGroupPersonalSetting }>
* @author qingmeng
* @createTime: 2023/12/06 22:44:31
*/
public static List<ChatGroupPersonalSetting> buildChatGroupPersonalSettingSaveList(Long roomGroupId, List<Long> userIds) {
return userIds.stream().map(userId -> {
ChatGroupPersonalSetting chatGroupPersonalSetting = new ChatGroupPersonalSetting();
chatGroupPersonalSetting.setGroupRoomId(roomGroupId);
chatGroupPersonalSetting.setUserId(userId);
chatGroupPersonalSetting.setTopStatus(MessageTopStatusEnum.NORMAL.getCode());
chatGroupPersonalSetting.setDisplayNameStatus(DisplayNameStatusEnum.DISPLAY.getCode());
chatGroupPersonalSetting.setRemindStatus(RemindStatusEnum.OPEN.getCode());
return chatGroupPersonalSetting;
}).collect(Collectors.toList());
}
/**
* 构建默认聊天组设置
*
* @param groupRoomId 组会议室 ID
* @param sysUser sys 用户
* @param groupRoomQrcode 团体房二维码
* @return {@link ChatGroupSetting }
* @author qingmeng
* @createTime: 2023/12/06 22:51:18
*/
public static ChatGroupSetting buildDefaultChatGroupSetting(Long groupRoomId, SysUser sysUser, String groupRoomQrcode) {
ChatGroupSetting chatGroupSetting = new ChatGroupSetting();
chatGroupSetting.setGroupRoomId(groupRoomId);
chatGroupSetting.setGroupRoomName("由" + sysUser.getUserName() + "发起的群聊");
chatGroupSetting.setGroupRoomAvatar(sysUser.getUserAvatar());
chatGroupSetting.setGroupRoomQrcode(groupRoomQrcode);
chatGroupSetting.setInvitationConfirmation(CloseOrOpenStatusEnum.CLOSE.getCode());
return chatGroupSetting;
}
/**
* 建立邀请组列表
*
* @param ids IDS
* @param chatGroupSetting 聊天组设置
* @param userName 用户名
* @return {@link List }<{@link WsGroupInviteVO }>
* @author qingmeng
* @createTime: 2023/12/07 09:20:58
*/
public static List<WsGroupInviteVO> buildInviteGroupList(List<Long> ids, ChatGroupSetting chatGroupSetting, String userName) {
// todo
return new ArrayList<>();
}
/**
* 建立保存聊天组成员
*
* @param userId 用户 ID
* @param groupRoomId 组会议室 ID
* @return {@link ChatGroupMember }
* @author qingmeng
* @createTime: 2023/12/08 08:51:00
*/
public static ChatGroupMember buildSaveChatGroupMember(Long userId, Long groupRoomId) {
return buildSaveChatGroupMemberList(userId, Collections.singletonList(groupRoomId)).get(0);
}
/**
* 建立聊天组设置
*
* @param userId 用户 ID
* @param groupRoomId 组会议室 ID
* @return {@link ChatGroupPersonalSetting }
* @author qingmeng
* @createTime: 2023/12/08 08:50:58
*/
public static ChatGroupPersonalSetting buildChatGroupSetting(Long userId, Long groupRoomId) {
return buildChatGroupPersonalSettingSaveList(userId, Collections.singletonList(groupRoomId)).get(0);
}
/**
* 建立聊天群管理列表
*
* @param groupRoomId 组会议室 ID
* @param ids IDS
* @return {@link List }<{@link ChatGroupManager }>
* @author qingmeng
* @createTime: 2023/12/08 11:32:59
*/
public static List<ChatGroupManager> buildChatGroupManagementList(Long groupRoomId, List<Long> ids) {
return ids.stream().map(id -> {
ChatGroupManager chatGroupManager = new ChatGroupManager();
chatGroupManager.setRoomGroupId(groupRoomId);
chatGroupManager.setUserId(id);
chatGroupManager.setRoleType(GroupRoleEnum.GROUP_MANAGEMENT.getCode());
return chatGroupManager;
}).collect(Collectors.toList());
}
/**
* 构造 群聊详细信息
*
* @param userId 用户 ID
* @param memberIds 会员 ID
* @param friendIds 好友ID
* @param chatGroupSetting 聊天组设置
* @param chatGroupPersonalSetting 聊天组个人设置
* @param friendSettingList 好友设置列表
* @param userMap 用户集合
* @param chatGroupPersonalSettingMap 聊天群个人设置集合
* @return {@link GroupDetailInfo }
* @author qingmeng
* @createTime: 2023/12/09 14:55:20
*/
public static GroupDetailInfo buildGroupDetailInfo(Long userId,
List<Long> memberIds,
List<Long> friendIds,
ChatGroupSetting chatGroupSetting,
ChatGroupPersonalSetting chatGroupPersonalSetting,
List<SysUserFriendSetting> friendSettingList,
Map<Long, SysUser> userMap,
Map<String, ChatGroupPersonalSetting> chatGroupPersonalSettingMap,
List<ChatGroupManager> managerAllList) {
GroupDetailInfo groupDetailInfo = new GroupDetailInfo();
groupDetailInfo.setGroupRoomName(chatGroupSetting.getGroupRoomName());
groupDetailInfo.setGroupRoomAvatar(chatGroupSetting.getGroupRoomAvatar());
groupDetailInfo.setGroupNotice(chatGroupSetting.getGroupNotice());
groupDetailInfo.setInvitationConfirmation(chatGroupSetting.getInvitationConfirmation());
groupDetailInfo.setGroupRoomQrCode(chatGroupSetting.getGroupRoomQrcode());
groupDetailInfo.setTopStatus(chatGroupPersonalSetting.getTopStatus());
groupDetailInfo.setDisplayNameStatus(chatGroupPersonalSetting.getDisplayNameStatus());
groupDetailInfo.setNickName(chatGroupPersonalSetting.getNickName());
groupDetailInfo.setRemindStatus(chatGroupPersonalSetting.getRemindStatus());
Map<String, List<?>> map = getMemberListAndManagerList(userId, memberIds, friendIds, friendSettingList, userMap, chatGroupPersonalSettingMap, managerAllList);
groupDetailInfo.setMemberList((List<SimpleUserInfo>) map.get("memberList"));
groupDetailInfo.setManagerList((List<ManagerInfo>) map.get("managerInfoList"));
return groupDetailInfo;
}
/**
* 获取成员列表
*
* @param userId 用户 ID
* @param memberIds 会员 ID
* @param friendIds 好友ID
* @param friendSettingList 好友设置列表
* @param userMap 用户集合
* @param chatGroupPersonalSettingMap 聊天群个人设置集合
* @param managerAllList 管理员 列表
* @return {@link Map }<{@link String }, {@link List }<{@link ? }>>
* @author qingmeng
* @createTime: 2023/12/11 11:06:48
*/
private static Map<String, List<?>> getMemberListAndManagerList(Long userId,
List<Long> memberIds,
List<Long> friendIds,
List<SysUserFriendSetting> friendSettingList,
Map<Long, SysUser> userMap,
Map<String, ChatGroupPersonalSetting> chatGroupPersonalSettingMap,
List<ChatGroupManager> managerAllList) {
Map<String, List<?>> map = new HashMap<>(2);
List<SimpleUserInfo> memberList = new ArrayList<>();
List<ManagerInfo> managerInfoList = new ArrayList<>();
memberIds.forEach(id -> {
SimpleUserInfo userInfo = new SimpleUserInfo();
boolean isFriend = friendIds.contains(id);
if (isFriend) {
// 获取 当前用户 对 对方 的设置数据,判断是否进行备注
SysUserFriendSetting friendSetting = friendSettingList.stream()
.filter(setting -> {
// 通过tagKey和userId定位数据 tagKey:1-2 userId:1 表示用户1对用户2的设置 | boolean flagA = setting.getTagKey().equals(CommonUtils.getKeyBySort(Arrays.asList(userId, id))); | 2 | 2023-11-07 16:04:55+00:00 | 8k |
TianqiCS/AIChatLib-Fabric | src/main/java/com/citrusmc/aichatlib/client/ChatBotClient.java | [
{
"identifier": "ChatGPTUtil",
"path": "src/main/java/com/citrusmc/aichatlib/ChatGPTUtil.java",
"snippet": "public class ChatGPTUtil {\n private static final Logger LOGGER = LoggerFactory.getLogger(\"ChatBot-ChatGPTUtil\");\n private static final OkHttpClient httpClient = HttpClientFactory.createC... | import com.citrusmc.aichatlib.ChatGPTUtil;
import com.citrusmc.aichatlib.ChatHistory;
import com.citrusmc.aichatlib.StreamChatGPT;
import com.citrusmc.aichatlib.configs.ClientConfig;
import com.citrusmc.aichatlib.configs.Config;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager;
import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback;
import net.fabricmc.fabric.api.client.message.v1.ClientReceiveMessageEvents;
import net.fabricmc.fabric.api.client.message.v1.ClientSendMessageEvents;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.ClientPlayerEntity;
import net.minecraft.text.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.function.Consumer;
import static com.mojang.brigadier.arguments.StringArgumentType.getString;
import static com.mojang.brigadier.arguments.StringArgumentType.greedyString;
import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.argument; | 6,222 | package com.citrusmc.aichatlib.client;
/**
* The client mod initializer
*/
public class ChatBotClient implements ClientModInitializer {
private static final Logger LOGGER = LoggerFactory.getLogger("ChatBot-Client");
private static Config CONFIG = null;
private static TextParser PARSER = null;
private final Semaphore semaphore = new Semaphore(1);
private volatile ChatHistoryManager chatHistoryManager = ChatHistoryManager.getInstance();
private boolean inFreeChat = false;
private String currentFreeChat;
/**
* Initialize the client mod
*/
@Override
public void onInitializeClient() { | package com.citrusmc.aichatlib.client;
/**
* The client mod initializer
*/
public class ChatBotClient implements ClientModInitializer {
private static final Logger LOGGER = LoggerFactory.getLogger("ChatBot-Client");
private static Config CONFIG = null;
private static TextParser PARSER = null;
private final Semaphore semaphore = new Semaphore(1);
private volatile ChatHistoryManager chatHistoryManager = ChatHistoryManager.getInstance();
private boolean inFreeChat = false;
private String currentFreeChat;
/**
* Initialize the client mod
*/
@Override
public void onInitializeClient() { | CONFIG = ClientConfig.getInstance(); | 3 | 2023-11-06 00:04:54+00:00 | 8k |
Griefed/AddEmAll | buildSrc/src/main/java/de/griefed/generation/generator/CodeGenerator.java | [
{
"identifier": "BlockDefinition",
"path": "buildSrc/src/main/java/de/griefed/generation/blocks/BlockDefinition.java",
"snippet": "public class BlockDefinition {\n\n public BlockDefinition(String id,\n String translation,\n String material,\n ... | import com.fasterxml.jackson.databind.ObjectMapper;
import de.griefed.generation.blocks.BlockDefinition;
import de.griefed.generation.blocks.BlockDefinitionParser;
import de.griefed.generation.blocks.TextureScaler;
import org.gradle.api.Project;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.regex.Pattern; | 3,719 |
public String readFromFile(File file) throws IOException {
StringBuilder sb = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
}
return sb.toString();
}
/**
* Create all translations required for our blocks and items to work.
*
* @throws IOException when the file could not be created or edited.
*/
protected void updateTranslations() throws IOException {
if (!translationsFile.exists() && translationsFile.getParentFile().mkdirs() && translationsFile.createNewFile()) {
writeToFile(
translationsFile,
TRANSLATION_CONTENT_TEMPLATE.replace("GENERATED_TRANSLATION_CODE", buildTranslationText())
);
} else {
String translations = readFromFile(getTranslationsFile());
//translations file from our generation
translations = LANG_REPLACE
.matcher(translations)
.replaceAll("\"DO.NOT.EDIT.MANUALLY.BEGIN\": \"BEGIN\"," +
buildTranslationText() +
" \"DO.NOT.EDIT.MANUALLY.END\": \"END\"");
writeToFile(this.translationsFile, translations);
}
}
private StringBuilder buildTranslationText() {
StringBuilder translations = new StringBuilder();
for (BlockDefinition block : blockDefinitionParser.getBlocks()) {
//add item
//key
translations.append("\n \"").append(String.format(ITEM_TRANSLATION_KEY_TEMPLATE, id, block.getMaterial().toLowerCase(), block.getId())).append("\":");
//value
translations.append(" \"").append(block.getTranslation()).append("\",");
//add block
//key
translations.append("\n \"").append(String.format(BLOCK_TRANSLATION_KEY_TEMPLATE, id, block.getMaterial().toLowerCase(), block.getId())).append("\":");
//value
translations.append(" \"").append(block.getTranslation()).append("\",\n");
if (block.generateSlab()) {
//add item
//key
translations.append("\n \"").append(String.format(ITEM_SLAB_TRANSLATION_KEY_TEMPLATE, id, block.getMaterial().toLowerCase(), block.getId())).append("\":");
//value
translations.append(" \"").append(block.getTranslation()).append(" Slab").append("\",");
//add block
//key
translations.append("\n \"").append(String.format(BLOCK_SLAB_TRANSLATION_KEY_TEMPLATE, id, block.getMaterial().toLowerCase(), block.getId())).append("\":");
//value
translations.append(" \"").append(block.getTranslation()).append(" Slab").append("\",\n");
}
if (block.generateStair()) {
//add item
//key
translations.append("\n \"").append(String.format(ITEM_STAIRS_TRANSLATION_KEY_TEMPLATE, id, block.getMaterial().toLowerCase(), block.getId())).append("\":");
//value
translations.append(" \"").append(block.getTranslation()).append(" Stairs").append("\",");
//add block
//key
translations.append("\n \"").append(String.format(BLOCK_STAIRS_TRANSLATION_KEY_TEMPLATE, id, block.getMaterial().toLowerCase(), block.getId())).append("\":");
//value
translations.append(" \"").append(block.getTranslation()).append(" Stairs").append("\",\n");
}
}
return translations;
}
/**
* Create all files required for the added blocks to work.<br>
*
* @throws IOException when the file could not be created or edited.
*/
@SuppressWarnings("ResultOfMethodCallIgnored")
public void createBlockFiles() throws IOException {
File blockstatesDir = new File(assetsDirectory, "blockstates");
File blockModelsDir = new File(assetsDirectory, "models/block");
File itemModelsDir = new File(assetsDirectory, "models/item");
File itemTexturesDir = new File(assetsDirectory, "textures/item");
File blockTexturesDir = new File(assetsDirectory, "textures/block");
File blockstate;
File blockModel;
File itemBlockModel;
File blockTexture;
File textureSource;
File textureMCMeta;
BufferedImage texture;
for (BlockDefinition block : blockDefinitionParser.getBlocks()) {
//blockstate
blockstate = new File(blockstatesDir, String.format(BLOCKSTATES_FILETEMPLATE, block.getMaterial().toLowerCase(), block.getId()));
blockstate.getParentFile().mkdirs();
writeToFile(blockstate, String.format(BLOCKSTATE_CONTENT_TEMPLATE, id, block.getMaterial().toLowerCase(), block.getId()));
//block model
blockModel = new File(blockModelsDir, String.format(BLOCK_MODEL_FILETEMPLATE, block.getMaterial().toLowerCase(), block.getId()));
blockModel.getParentFile().mkdirs();
writeToFile(blockModel, String.format(BLOCK_MODELS_CONTENT_TEMPLATE, id, block.getMaterial().toLowerCase(), block.getId()));
//item block model
itemBlockModel = new File(itemModelsDir, String.format(ITEM_BLOCK_MODEL_FILETEMPLATE, block.getMaterial().toLowerCase(), block.getId()));
itemBlockModel.getParentFile().mkdirs();
writeToFile(itemBlockModel, String.format(BLOCK_MODELS_ITEM_CONTENT_TEMPLATE, id, block.getMaterial().toLowerCase(), block.getId()));
//block texture
blockTexture = new File(blockTexturesDir, String.format(BLOCK_TEXTURE_FILETEMPLATE, block.getMaterial().toLowerCase(), block.getId()));
blockTexture.getParentFile().mkdirs();
textureSource = new File(blockDefinitionParser.getAssetsDirectory(), block.getId() + ".png");
texture = ImageIO.read(textureSource);
if (texture.getWidth() > 16 && texture.getHeight() > 16) { | package de.griefed.generation.generator;
@SuppressWarnings("unused")
public abstract class CodeGenerator {
public static final Pattern GENERATED_CODE_PATTERN = Pattern.compile("/\\*###GENERATED CODE - DO NOT EDIT - MANUALLY EDITED CODE WILL BE LOST###\\*/.*/\\*###GENERATED CODE - DO NOT EDIT - MANUALLY EDITED CODE WILL BE LOST###\\*/", Pattern.DOTALL);
public static final Pattern LANG_REPLACE = Pattern.compile("\"DO\\.NOT\\.EDIT\\.MANUALLY\\.BEGIN\": \"BEGIN\".*\"DO\\.NOT\\.EDIT\\.MANUALLY\\.END\": \"END\"", Pattern.DOTALL);
public static final String BLOCKSTATES_FILETEMPLATE = "generated/%s/%s_block.json";
public static final String BLOCKSTATES_SLAB_FILETEMPLATE = "generated/%s/%s_slab.json";
public static final String BLOCKSTATES_STAIRS_FILETEMPLATE = "generated/%s/%s_stairs.json";
public static final String BLOCK_MODEL_FILETEMPLATE = "generated/%s/%s_block.json";
public static final String BLOCK_MODEL_SLAB_FILETEMPLATE = "generated/%s/%s_slab.json";
public static final String BLOCK_MODEL_SLAB_TOP_FILETEMPLATE = "generated/%s/%s_slab_top.json";
public static final String BLOCK_MODEL_STAIRS_FILETEMPLATE = "generated/%s/%s_stairs.json";
public static final String BLOCK_MODEL_STAIRS_INNER_FILETEMPLATE = "generated/%s/%s_stairs_inner.json";
public static final String BLOCK_MODEL_STAIRS_OUTER_FILETEMPLATE = "generated/%s/%s_stairs_outer.json";
public static final String ITEM_BLOCK_MODEL_FILETEMPLATE = "generated/%s/%s.json";
public static final String ITEM_BLOCK_MODEL_SLAB_FILETEMPLATE = "generated/%s/%s_slab.json";
public static final String ITEM_BLOCK_MODEL_STAIRS_FILETEMPLATE = "generated/%s/%s_stairs.json";
public static final String BLOCK_TEXTURE_FILETEMPLATE = "generated/%s/%s_block.png";
public static final String ITEM_TRANSLATION_KEY_TEMPLATE = "item.%s.generated.%s.%s_block";
public static final String ITEM_SLAB_TRANSLATION_KEY_TEMPLATE = "item.%s.generated.%s.%s_slab";
public static final String ITEM_STAIRS_TRANSLATION_KEY_TEMPLATE = "item.%s.generated.%s.%s_stairs";
public static final String BLOCK_TRANSLATION_KEY_TEMPLATE = "block.%s.generated.%s.%s_block";
public static final String BLOCK_SLAB_TRANSLATION_KEY_TEMPLATE = "block.%s.generated.%s.%s_slab";
public static final String BLOCK_STAIRS_TRANSLATION_KEY_TEMPLATE = "block.%s.generated.%s.%s_stairs";
public static final String ANIMATION_CONTENT_TEMPLATE = """
{
"animation": {}
}
""";
private static final String BLOCKSTATE_CONTENT_TEMPLATE = """
{
"variants": {
"": { "model": "%s:block/generated/%s/%s_block" }
}
}
""";
private static final String BLOCKSTATE_SLAB_CONTENT_TEMPLATE = """
{
"variants": {
"type=bottom": {
"model": "%s:block/generated/%s/%s_slab"
},
"type=double": {
"model": "%s:block/generated/%s/%s_block"
},
"type=top": {
"model": "%s:block/generated/%s/%s_slab_top"
}
}
}
""";
private static final String BLOCKSTATE_STAIRS_CONTENT_TEMPLATE = """
{
"variants": {
"facing=east,half=bottom,shape=inner_left": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner",
"y": 270,
"uvlock": true
},
"facing=east,half=bottom,shape=inner_right": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner"
},
"facing=east,half=bottom,shape=outer_left": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer",
"y": 270,
"uvlock": true
},
"facing=east,half=bottom,shape=outer_right": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer"
},
"facing=east,half=bottom,shape=straight": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs"
},
"facing=east,half=top,shape=inner_left": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner",
"x": 180,
"uvlock": true
},
"facing=east,half=top,shape=inner_right": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner",
"x": 180,
"y": 90,
"uvlock": true
},
"facing=east,half=top,shape=outer_left": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer",
"x": 180,
"uvlock": true
},
"facing=east,half=top,shape=outer_right": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer",
"x": 180,
"y": 90,
"uvlock": true
},
"facing=east,half=top,shape=straight": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs",
"x": 180,
"uvlock": true
},
"facing=north,half=bottom,shape=inner_left": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner",
"y": 180,
"uvlock": true
},
"facing=north,half=bottom,shape=inner_right": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner",
"y": 270,
"uvlock": true
},
"facing=north,half=bottom,shape=outer_left": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer",
"y": 180,
"uvlock": true
},
"facing=north,half=bottom,shape=outer_right": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer",
"y": 270,
"uvlock": true
},
"facing=north,half=bottom,shape=straight": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs",
"y": 270,
"uvlock": true
},
"facing=north,half=top,shape=inner_left": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner",
"x": 180,
"y": 270,
"uvlock": true
},
"facing=north,half=top,shape=inner_right": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner",
"x": 180,
"uvlock": true
},
"facing=north,half=top,shape=outer_left": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer",
"x": 180,
"y": 270,
"uvlock": true
},
"facing=north,half=top,shape=outer_right": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer",
"x": 180,
"uvlock": true
},
"facing=north,half=top,shape=straight": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs",
"x": 180,
"y": 270,
"uvlock": true
},
"facing=south,half=bottom,shape=inner_left": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner"
},
"facing=south,half=bottom,shape=inner_right": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner",
"y": 90,
"uvlock": true
},
"facing=south,half=bottom,shape=outer_left": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer"
},
"facing=south,half=bottom,shape=outer_right": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer",
"y": 90,
"uvlock": true
},
"facing=south,half=bottom,shape=straight": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs",
"y": 90,
"uvlock": true
},
"facing=south,half=top,shape=inner_left": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner",
"x": 180,
"y": 90,
"uvlock": true
},
"facing=south,half=top,shape=inner_right": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner",
"x": 180,
"y": 180,
"uvlock": true
},
"facing=south,half=top,shape=outer_left": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer",
"x": 180,
"y": 90,
"uvlock": true
},
"facing=south,half=top,shape=outer_right": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer",
"x": 180,
"y": 180,
"uvlock": true
},
"facing=south,half=top,shape=straight": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs",
"x": 180,
"y": 90,
"uvlock": true
},
"facing=west,half=bottom,shape=inner_left": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner",
"y": 90,
"uvlock": true
},
"facing=west,half=bottom,shape=inner_right": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner",
"y": 180,
"uvlock": true
},
"facing=west,half=bottom,shape=outer_left": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer",
"y": 90,
"uvlock": true
},
"facing=west,half=bottom,shape=outer_right": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer",
"y": 180,
"uvlock": true
},
"facing=west,half=bottom,shape=straight": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs",
"y": 180,
"uvlock": true
},
"facing=west,half=top,shape=inner_left": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner",
"x": 180,
"y": 180,
"uvlock": true
},
"facing=west,half=top,shape=inner_right": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner",
"x": 180,
"y": 270,
"uvlock": true
},
"facing=west,half=top,shape=outer_left": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer",
"x": 180,
"y": 180,
"uvlock": true
},
"facing=west,half=top,shape=outer_right": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer",
"x": 180,
"y": 270,
"uvlock": true
},
"facing=west,half=top,shape=straight": {
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs",
"x": 180,
"y": 180,
"uvlock": true
}
}
}
""";
private static final String BLOCK_MODELS_CONTENT_TEMPLATE = """
{
"parent": "block/cube_all",
"textures": {
"all": "%s:block/generated/%s/%s_block"
}
}
""";
private static final String BLOCK_MODELS_SLAB_CONTENT_TEMPLATE = """
{
"parent": "minecraft:block/slab",
"textures": {
"bottom": "%s:block/generated/%s/%s_block",
"top": "%s:block/generated/%s/%s_block",
"side": "%s:block/generated/%s/%s_block"
}
}
""";
private static final String BLOCK_MODELS_STAIRS_TEMPLATE = """
{
"parent": "minecraft:block/stairs",
"textures": {
"bottom": "%s:block/generated/%s/%s_block",
"top": "%s:block/generated/%s/%s_block",
"side": "%s:block/generated/%s/%s_block"
}
}
""";
private static final String BLOCK_MODELS_STAIRS_INNER_TEMPLATE = """
{
"parent": "minecraft:block/inner_stairs",
"textures": {
"bottom": "%s:block/generated/%s/%s_block",
"top": "%s:block/generated/%s/%s_block",
"side": "%s:block/generated/%s/%s_block"
}
}
""";
private static final String BLOCK_MODELS_STAIRS_OUTER_TEMPLATE = """
{
"parent": "minecraft:block/outer_stairs",
"textures": {
"bottom": "%s:block/generated/%s/%s_block",
"top": "%s:block/generated/%s/%s_block",
"side": "%s:block/generated/%s/%s_block"
}
}
""";
private static final String BLOCK_MODELS_SLAB_TOP_CONTENT_TEMPLATE = """
{
"parent": "minecraft:block/slab_top",
"textures": {
"bottom": "%s:block/generated/%s/%s_block",
"top": "%s:block/generated/%s/%s_block",
"side": "%s:block/generated/%s/%s_block"
}
}
""";
private static final String BLOCK_MODELS_ITEM_CONTENT_TEMPLATE = """
{
"parent": "%s:block/generated/%s/%s_block"
}
""";
private static final String BLOCK_MODELS_SLAB_ITEM_CONTENT_TEMPLATE = """
{
"parent": "%s:block/generated/%s/%s_slab"
}
""";
private static final String BLOCK_MODELS_STAIRS_ITEM_CONTENT_TEMPLATE = """
{
"parent": "%s:block/generated/%s/%s_stairs"
}
""";
private static final String TRANSLATION_CONTENT_TEMPLATE = """
{
"DO.NOT.EDIT.MANUALLY.BEGIN": "BEGIN",
GENERATED_TRANSLATION_CODE
"DO.NOT.EDIT.MANUALLY.END": "END"
}
""";
private final Project project;
private final String modName;
private final String subName;
private final BlockDefinitionParser blockDefinitionParser;
private final ObjectMapper objectMapper;
private final String group;
private final File groupDirectory;
private final String modloader;
private final String id;
private final File modBlocksClass;
private final File modItemsClass;
private final File blocksGroup;
private final File itemGroup;
private final File modloaderClass;
private final File assetsDirectory;
private final File translationsFile;
protected CodeGenerator(Project project, String modName, BlockDefinitionParser parser, ObjectMapper objectMapper) {
this.project = project;
this.blockDefinitionParser = parser;
this.modName = modName;
this.subName = modName + project.getName().substring(0, 1).toUpperCase() + project.getName().substring(1);
this.objectMapper = objectMapper;
this.group = project.getGroup().toString();
this.groupDirectory = new File(project.getProjectDir(), "src/main/java/" + group.replace(".", "/"));
this.modloader = project.getName();
this.id = group.substring(group.lastIndexOf(".") + 1);
this.blocksGroup = new File(groupDirectory, "block");
this.modBlocksClass = new File(blocksGroup, "GeneratedModBlocks.java");
this.itemGroup = new File(groupDirectory, "item");
this.modItemsClass = new File(itemGroup, "GeneratedModItems.java");
if (project.getName().equalsIgnoreCase("common")) {
this.modloaderClass = new File(groupDirectory, "CommonClass.java");
} else {
this.modloaderClass = new File(groupDirectory, subName + ".java");
}
this.assetsDirectory = new File(project.getProjectDir(), "src/main/resources/assets/" + id);
this.translationsFile = new File(assetsDirectory, "lang/en_us.json");
}
/**
* Create the <code>your.group.modid.block</code>-package
*/
protected void createModBlockPackage() {
if (!blocksGroup.exists() && blocksGroup.mkdirs()) {
System.out.println("Group-directory created " + blocksGroup.getAbsolutePath());
}
}
/**
* Create the <code>your.group.modid.item</code>-package
*/
protected void createItemPackage() {
if (!itemGroup.exists() && itemGroup.mkdirs()) {
System.out.println("Item-directory created: " + itemGroup.getAbsolutePath());
}
}
public void writeToFile(File file, String text) throws IOException {
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
try (FileWriter fileWriter = new FileWriter(file)) {
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(text);
bufferedWriter.close();
}
}
public String readFromFile(File file) throws IOException {
StringBuilder sb = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
}
return sb.toString();
}
/**
* Create all translations required for our blocks and items to work.
*
* @throws IOException when the file could not be created or edited.
*/
protected void updateTranslations() throws IOException {
if (!translationsFile.exists() && translationsFile.getParentFile().mkdirs() && translationsFile.createNewFile()) {
writeToFile(
translationsFile,
TRANSLATION_CONTENT_TEMPLATE.replace("GENERATED_TRANSLATION_CODE", buildTranslationText())
);
} else {
String translations = readFromFile(getTranslationsFile());
//translations file from our generation
translations = LANG_REPLACE
.matcher(translations)
.replaceAll("\"DO.NOT.EDIT.MANUALLY.BEGIN\": \"BEGIN\"," +
buildTranslationText() +
" \"DO.NOT.EDIT.MANUALLY.END\": \"END\"");
writeToFile(this.translationsFile, translations);
}
}
private StringBuilder buildTranslationText() {
StringBuilder translations = new StringBuilder();
for (BlockDefinition block : blockDefinitionParser.getBlocks()) {
//add item
//key
translations.append("\n \"").append(String.format(ITEM_TRANSLATION_KEY_TEMPLATE, id, block.getMaterial().toLowerCase(), block.getId())).append("\":");
//value
translations.append(" \"").append(block.getTranslation()).append("\",");
//add block
//key
translations.append("\n \"").append(String.format(BLOCK_TRANSLATION_KEY_TEMPLATE, id, block.getMaterial().toLowerCase(), block.getId())).append("\":");
//value
translations.append(" \"").append(block.getTranslation()).append("\",\n");
if (block.generateSlab()) {
//add item
//key
translations.append("\n \"").append(String.format(ITEM_SLAB_TRANSLATION_KEY_TEMPLATE, id, block.getMaterial().toLowerCase(), block.getId())).append("\":");
//value
translations.append(" \"").append(block.getTranslation()).append(" Slab").append("\",");
//add block
//key
translations.append("\n \"").append(String.format(BLOCK_SLAB_TRANSLATION_KEY_TEMPLATE, id, block.getMaterial().toLowerCase(), block.getId())).append("\":");
//value
translations.append(" \"").append(block.getTranslation()).append(" Slab").append("\",\n");
}
if (block.generateStair()) {
//add item
//key
translations.append("\n \"").append(String.format(ITEM_STAIRS_TRANSLATION_KEY_TEMPLATE, id, block.getMaterial().toLowerCase(), block.getId())).append("\":");
//value
translations.append(" \"").append(block.getTranslation()).append(" Stairs").append("\",");
//add block
//key
translations.append("\n \"").append(String.format(BLOCK_STAIRS_TRANSLATION_KEY_TEMPLATE, id, block.getMaterial().toLowerCase(), block.getId())).append("\":");
//value
translations.append(" \"").append(block.getTranslation()).append(" Stairs").append("\",\n");
}
}
return translations;
}
/**
* Create all files required for the added blocks to work.<br>
*
* @throws IOException when the file could not be created or edited.
*/
@SuppressWarnings("ResultOfMethodCallIgnored")
public void createBlockFiles() throws IOException {
File blockstatesDir = new File(assetsDirectory, "blockstates");
File blockModelsDir = new File(assetsDirectory, "models/block");
File itemModelsDir = new File(assetsDirectory, "models/item");
File itemTexturesDir = new File(assetsDirectory, "textures/item");
File blockTexturesDir = new File(assetsDirectory, "textures/block");
File blockstate;
File blockModel;
File itemBlockModel;
File blockTexture;
File textureSource;
File textureMCMeta;
BufferedImage texture;
for (BlockDefinition block : blockDefinitionParser.getBlocks()) {
//blockstate
blockstate = new File(blockstatesDir, String.format(BLOCKSTATES_FILETEMPLATE, block.getMaterial().toLowerCase(), block.getId()));
blockstate.getParentFile().mkdirs();
writeToFile(blockstate, String.format(BLOCKSTATE_CONTENT_TEMPLATE, id, block.getMaterial().toLowerCase(), block.getId()));
//block model
blockModel = new File(blockModelsDir, String.format(BLOCK_MODEL_FILETEMPLATE, block.getMaterial().toLowerCase(), block.getId()));
blockModel.getParentFile().mkdirs();
writeToFile(blockModel, String.format(BLOCK_MODELS_CONTENT_TEMPLATE, id, block.getMaterial().toLowerCase(), block.getId()));
//item block model
itemBlockModel = new File(itemModelsDir, String.format(ITEM_BLOCK_MODEL_FILETEMPLATE, block.getMaterial().toLowerCase(), block.getId()));
itemBlockModel.getParentFile().mkdirs();
writeToFile(itemBlockModel, String.format(BLOCK_MODELS_ITEM_CONTENT_TEMPLATE, id, block.getMaterial().toLowerCase(), block.getId()));
//block texture
blockTexture = new File(blockTexturesDir, String.format(BLOCK_TEXTURE_FILETEMPLATE, block.getMaterial().toLowerCase(), block.getId()));
blockTexture.getParentFile().mkdirs();
textureSource = new File(blockDefinitionParser.getAssetsDirectory(), block.getId() + ".png");
texture = ImageIO.read(textureSource);
if (texture.getWidth() > 16 && texture.getHeight() > 16) { | texture = TextureScaler.getScaledInstance(texture); | 2 | 2023-11-06 12:50:10+00:00 | 8k |
arunk140/ollm.chat | app/src/main/java/com/arunk140/ollmchat/ui/home/HomeFragment.java | [
{
"identifier": "Chat",
"path": "app/src/main/java/com/arunk140/ollmchat/Adapter/Chat.java",
"snippet": "public class Chat extends\n RecyclerView.Adapter<Chat.ViewHolder>{\n ArrayList<Message> msgs;\n\n public Chat(ArrayList<Message> msgList) {\n msgs = msgList;\n }\n\n @NonNul... | import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.arunk140.ollmchat.Adapter.Chat;
import com.arunk140.ollmchat.Config.Settings;
import com.arunk140.ollmchat.DB.Manager;
import com.arunk140.ollmchat.LLM.ChatCompletionChunk;
import com.arunk140.ollmchat.LLM.ChatCompletionRequest;
import com.arunk140.ollmchat.LLM.GPTViewModel;
import com.arunk140.ollmchat.LLM.Message;
import com.arunk140.ollmchat.MainActivity;
import com.arunk140.ollmchat.R;
import com.arunk140.ollmchat.SettingsActivity;
import com.arunk140.ollmchat.databinding.FragmentHomeBinding;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Objects; | 5,016 | package com.arunk140.ollmchat.ui.home;
public class HomeFragment extends Fragment {
private FragmentHomeBinding binding;
EditText msgText;
TextView noMessages;
boolean disableSending;
ProgressBar waitingForLLM;
ImageButton settingsBtn;
ImageButton refreshBtn;
ImageButton drawerBtn;
ImageButton actionBtn;
Button regenBtn;
RecyclerView chatListView;
LinearLayoutManager linearLayoutManager;
ArrayList<Message> messages;
Chat chatAdapter;
private Handler mainHandler;
private GPTViewModel viewModel;
Manager manager;
Settings settings;
Thread currentInvocation;
Runnable currentRunnable;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
binding = FragmentHomeBinding.inflate(inflater, container, false);
View root = binding.getRoot();
disableSending = false;
messages = new ArrayList<>();
chatAdapter = new Chat(messages);
waitingForLLM = binding.waitingForLLM;
chatListView = binding.chatList;
msgText = binding.editTextText;
settingsBtn = binding.settingsBtn;
refreshBtn = binding.refreshBtn;
drawerBtn = binding.drawerBtn;
noMessages = binding.noMessages;
actionBtn = binding.stopBtn;
regenBtn = binding.regenBtn;
manager = new Manager(getContext());
manager.open();
settings = manager.getSettings();
manager.close();
settingsBtn.setOnClickListener(v -> {
Intent myIntent = new Intent(requireActivity(), SettingsActivity.class);
requireActivity().startActivity(myIntent);
});
drawerBtn.setOnClickListener(v -> {
MainActivity x = (MainActivity)getActivity();
x.toggleDrawer();
});
refreshBtn.setOnClickListener(v -> {
restart();
});
DividerItemDecoration dId = new DividerItemDecoration(requireActivity(), DividerItemDecoration.VERTICAL);
dId.setDrawable(Objects.requireNonNull(ContextCompat.getDrawable(requireActivity(), R.drawable.spacer)));
chatListView.addItemDecoration(dId);
chatListView.setAdapter(chatAdapter);
linearLayoutManager = new LinearLayoutManager(requireActivity(), LinearLayoutManager.VERTICAL, true);
chatListView.setLayoutManager(linearLayoutManager);
mainHandler = new Handler(Looper.getMainLooper());
viewModel = new ViewModelProvider(this).get(GPTViewModel.class);
viewModel.dataLiveData.observe(requireActivity(), this::updateTextView);
viewModel.loadingLiveData.observe(requireActivity(), this::setLoaderState);
viewModel.errorLiveData.observe(requireActivity(), this::checkErrors);
actionBtn.setOnClickListener(v -> {
if (currentInvocation != null) {
currentInvocation.interrupt(); // Interrupt the thread
}
});
regenBtn.setOnClickListener(v -> {
regenBtn.setVisibility(View.GONE);
if (messages.size() > 1) {
messages.remove(0);
chatAdapter.notifyItemRemoved(0);
sendToLLM(messages.get(0).getContent(), false);
}
});
msgText.setOnKeyListener((v, keyCode, event) -> {
if (disableSending) {
return true;
}
if (messages.size() > 0) {
noMessages.setVisibility(View.GONE);
} else {
noMessages.setVisibility(View.VISIBLE);
}
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
String inputMsg = msgText.getText().toString().trim();
sendToLLM(inputMsg, true);
}
return true;
});
// final TextView textView = binding.textHome;
// homeViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);
return root;
}
private void sendToLLM(String inputMsg, boolean addNewMessage) {
if (inputMsg.equals("")) {
return;
}
if (inputMsg.equals("clear")) {
restart();
return;
}
if (addNewMessage) {
if (messages.size() == 0 && settings.systemPrompt.length() > 0) {
messages.add(0, new Message("user", inputMsg));
messages.add(1, new Message("system", settings.systemPrompt));
chatAdapter.notifyItemRangeInserted(0,2);
} else {
messages.add(0, new Message("user", inputMsg));
chatAdapter.notifyItemInserted(0);
}
}
msgText.setText("");
currentRunnable = () -> {
if (Thread.interrupted()) {
return;
} | package com.arunk140.ollmchat.ui.home;
public class HomeFragment extends Fragment {
private FragmentHomeBinding binding;
EditText msgText;
TextView noMessages;
boolean disableSending;
ProgressBar waitingForLLM;
ImageButton settingsBtn;
ImageButton refreshBtn;
ImageButton drawerBtn;
ImageButton actionBtn;
Button regenBtn;
RecyclerView chatListView;
LinearLayoutManager linearLayoutManager;
ArrayList<Message> messages;
Chat chatAdapter;
private Handler mainHandler;
private GPTViewModel viewModel;
Manager manager;
Settings settings;
Thread currentInvocation;
Runnable currentRunnable;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
binding = FragmentHomeBinding.inflate(inflater, container, false);
View root = binding.getRoot();
disableSending = false;
messages = new ArrayList<>();
chatAdapter = new Chat(messages);
waitingForLLM = binding.waitingForLLM;
chatListView = binding.chatList;
msgText = binding.editTextText;
settingsBtn = binding.settingsBtn;
refreshBtn = binding.refreshBtn;
drawerBtn = binding.drawerBtn;
noMessages = binding.noMessages;
actionBtn = binding.stopBtn;
regenBtn = binding.regenBtn;
manager = new Manager(getContext());
manager.open();
settings = manager.getSettings();
manager.close();
settingsBtn.setOnClickListener(v -> {
Intent myIntent = new Intent(requireActivity(), SettingsActivity.class);
requireActivity().startActivity(myIntent);
});
drawerBtn.setOnClickListener(v -> {
MainActivity x = (MainActivity)getActivity();
x.toggleDrawer();
});
refreshBtn.setOnClickListener(v -> {
restart();
});
DividerItemDecoration dId = new DividerItemDecoration(requireActivity(), DividerItemDecoration.VERTICAL);
dId.setDrawable(Objects.requireNonNull(ContextCompat.getDrawable(requireActivity(), R.drawable.spacer)));
chatListView.addItemDecoration(dId);
chatListView.setAdapter(chatAdapter);
linearLayoutManager = new LinearLayoutManager(requireActivity(), LinearLayoutManager.VERTICAL, true);
chatListView.setLayoutManager(linearLayoutManager);
mainHandler = new Handler(Looper.getMainLooper());
viewModel = new ViewModelProvider(this).get(GPTViewModel.class);
viewModel.dataLiveData.observe(requireActivity(), this::updateTextView);
viewModel.loadingLiveData.observe(requireActivity(), this::setLoaderState);
viewModel.errorLiveData.observe(requireActivity(), this::checkErrors);
actionBtn.setOnClickListener(v -> {
if (currentInvocation != null) {
currentInvocation.interrupt(); // Interrupt the thread
}
});
regenBtn.setOnClickListener(v -> {
regenBtn.setVisibility(View.GONE);
if (messages.size() > 1) {
messages.remove(0);
chatAdapter.notifyItemRemoved(0);
sendToLLM(messages.get(0).getContent(), false);
}
});
msgText.setOnKeyListener((v, keyCode, event) -> {
if (disableSending) {
return true;
}
if (messages.size() > 0) {
noMessages.setVisibility(View.GONE);
} else {
noMessages.setVisibility(View.VISIBLE);
}
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
String inputMsg = msgText.getText().toString().trim();
sendToLLM(inputMsg, true);
}
return true;
});
// final TextView textView = binding.textHome;
// homeViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);
return root;
}
private void sendToLLM(String inputMsg, boolean addNewMessage) {
if (inputMsg.equals("")) {
return;
}
if (inputMsg.equals("clear")) {
restart();
return;
}
if (addNewMessage) {
if (messages.size() == 0 && settings.systemPrompt.length() > 0) {
messages.add(0, new Message("user", inputMsg));
messages.add(1, new Message("system", settings.systemPrompt));
chatAdapter.notifyItemRangeInserted(0,2);
} else {
messages.add(0, new Message("user", inputMsg));
chatAdapter.notifyItemInserted(0);
}
}
msgText.setText("");
currentRunnable = () -> {
if (Thread.interrupted()) {
return;
} | ChatCompletionRequest request = new ChatCompletionRequest(reorderMessages(messages), settings, true); | 4 | 2023-11-01 00:44:14+00:00 | 8k |
MonstrousSoftware/Tut3D | core/src/main/java/com/monstrous/tut3d/inputs/PlayerController.java | [
{
"identifier": "GameObject",
"path": "core/src/main/java/com/monstrous/tut3d/GameObject.java",
"snippet": "public class GameObject implements Disposable {\n\n public final GameObjectType type;\n public final Scene scene;\n public final PhysicsBody body;\n public final Vector3 direction;\n ... | import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.IntIntMap;
import com.monstrous.tut3d.GameObject;
import com.monstrous.tut3d.Settings;
import com.monstrous.tut3d.World;
import com.monstrous.tut3d.physics.PhysicsRayCaster; | 4,833 | package com.monstrous.tut3d.inputs;
public class PlayerController extends InputAdapter {
public int forwardKey = Input.Keys.W;
public int backwardKey = Input.Keys.S;
public int strafeLeftKey = Input.Keys.A;
public int strafeRightKey = Input.Keys.D;
public int turnLeftKey = Input.Keys.Q;
public int turnRightKey = Input.Keys.E;
public int jumpKey = Input.Keys.SPACE;
public int runShiftKey = Input.Keys.SHIFT_LEFT;
public int switchWeaponKey = Input.Keys.TAB;
private final World world;
private final IntIntMap keys = new IntIntMap();
public final Vector3 linearForce;
private final Vector3 forwardDirection; // direction player is facing, move direction, in XZ plane
private final Vector3 viewingDirection; // look direction, is forwardDirection plus Y component
private float mouseDeltaX;
private float mouseDeltaY;
private final Vector3 groundNormal = new Vector3();
private final Vector3 tmp = new Vector3();
private final Vector3 tmp2 = new Vector3();
private final Vector3 tmp3 = new Vector3(); | package com.monstrous.tut3d.inputs;
public class PlayerController extends InputAdapter {
public int forwardKey = Input.Keys.W;
public int backwardKey = Input.Keys.S;
public int strafeLeftKey = Input.Keys.A;
public int strafeRightKey = Input.Keys.D;
public int turnLeftKey = Input.Keys.Q;
public int turnRightKey = Input.Keys.E;
public int jumpKey = Input.Keys.SPACE;
public int runShiftKey = Input.Keys.SHIFT_LEFT;
public int switchWeaponKey = Input.Keys.TAB;
private final World world;
private final IntIntMap keys = new IntIntMap();
public final Vector3 linearForce;
private final Vector3 forwardDirection; // direction player is facing, move direction, in XZ plane
private final Vector3 viewingDirection; // look direction, is forwardDirection plus Y component
private float mouseDeltaX;
private float mouseDeltaY;
private final Vector3 groundNormal = new Vector3();
private final Vector3 tmp = new Vector3();
private final Vector3 tmp2 = new Vector3();
private final Vector3 tmp3 = new Vector3(); | private final PhysicsRayCaster.HitPoint hitPoint = new PhysicsRayCaster.HitPoint(); | 3 | 2023-11-04 13:15:48+00:00 | 8k |
Einzieg/EinziegCloud | src/main/java/com/cloud/service/impl/EmailServiceImpl.java | [
{
"identifier": "IEmailService",
"path": "src/main/java/com/cloud/service/IEmailService.java",
"snippet": "public interface IEmailService {\n\n\tMsg<?> sendMailToRegistration(String email);\n}"
},
{
"identifier": "IUserService",
"path": "src/main/java/com/cloud/service/IUserService.java",
... | import com.cloud.service.IEmailService;
import com.cloud.service.IUserService;
import com.cloud.util.RedisUtil;
import com.cloud.util.mail.MailTemplate;
import com.cloud.util.mail.MailUtil;
import com.cloud.util.msg.Msg;
import com.cloud.util.msg.ResultCode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map; | 6,665 | package com.cloud.service.impl;
@Slf4j
@Service
@RequiredArgsConstructor
public class EmailServiceImpl implements IEmailService {
private final MailUtil mailUtil;
private final RedisUtil redisUtil; | package com.cloud.service.impl;
@Slf4j
@Service
@RequiredArgsConstructor
public class EmailServiceImpl implements IEmailService {
private final MailUtil mailUtil;
private final RedisUtil redisUtil; | private final IUserService userService; | 1 | 2023-11-07 07:27:53+00:00 | 8k |
AbarcaJ/VisibilityToggle | src/dev/cleusgamer201/visibilitytoggle/database/Cache.java | [
{
"identifier": "Main",
"path": "src/dev/cleusgamer201/visibilitytoggle/Main.java",
"snippet": "public class Main extends JavaPlugin implements Listener {\n\n private static Main instance;\n public static Main getInstance() {\n return instance;\n }\n\n private static String prefix;\n ... | import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import dev.cleusgamer201.visibilitytoggle.Main;
import dev.cleusgamer201.visibilitytoggle.Utils;
import dev.cleusgamer201.visibilitytoggle.api.Visibility; | 5,821 | package dev.cleusgamer201.visibilitytoggle.database;
public class Cache {
private final Player player;
private double lastUse = 0;
private Visibility state = Visibility.SHOW_ALL;
private boolean loaded = false;
public Cache(Player player) {
this.player = player;
final String uuid = getUuid().toString();
final String name = getName(); | package dev.cleusgamer201.visibilitytoggle.database;
public class Cache {
private final Player player;
private double lastUse = 0;
private Visibility state = Visibility.SHOW_ALL;
private boolean loaded = false;
public Cache(Player player) {
this.player = player;
final String uuid = getUuid().toString();
final String name = getName(); | Bukkit.getScheduler().runTaskLaterAsynchronously(Main.getInstance(), () -> { | 0 | 2023-11-02 15:00:52+00:00 | 8k |
1711680493/SPay | app/src/main/java/shendi/pay/service/NotifyPayService.java | [
{
"identifier": "Application",
"path": "app/src/main/java/shendi/pay/Application.java",
"snippet": "public class Application extends android.app.Application {\n\n /** 唯一实例 */\n private static Application instance;\n\n private static SLog log = SLog.getLogger(Application.class.getName());\n\n ... | import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import androidx.core.app.NotificationCompat;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import java.math.BigDecimal;
import java.util.Set;
import shendi.pay.Application;
import shendi.pay.R;
import shendi.pay.SLog;
import shendi.pay.util.ApiUtil; | 4,037 | package shendi.pay.service;
/**
* 通知支付服务.
* 创建时间:2023/11/8
* @author Shendi
*/
public class NotifyPayService extends NotificationListenerService {
private static SLog log = SLog.getLogger(NotifyPayService.class.getName());
private static final String NOTIFY_TITLE_DISPOSE_ERR = "监听处理失败";
@Override
public void onCreate() {
super.onCreate();
// 适配8.0及以上,创建渠道
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.createNotificationChannel(new NotificationChannel(Application.NOTIFY_CHANNEL_ID_PAY, Application.NOTIFY_CHANNEL_ID_PAY, NotificationManager.IMPORTANCE_MIN));
}
// 前台服务
startForeground(1, new NotificationCompat.Builder(this, Application.NOTIFY_CHANNEL_ID_PAY)
.setSmallIcon(R.drawable.logo)
.setContentTitle("SPay服务")
.setContentText("安稳运行中...")
.setWhen(System.currentTimeMillis())
.build());
log.i("监听通知服务启动");
}
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
String packName = sbn.getPackageName();
Bundle extras = sbn.getNotification().extras;
Object titleObj = extras.get(Notification.EXTRA_TITLE),
contentObj = extras.get(Notification.EXTRA_TEXT);
if (titleObj == null && contentObj == null) return;
String title = titleObj == null ? "" : titleObj.toString(),
content = contentObj == null ? "" : contentObj.toString();
StringBuilder notifyStr = new StringBuilder();
notifyStr.append("[").append(packName).append("]")
.append(title).append(" : ")
.append(content);
log.i(notifyStr.toString());
// 如果正在测试通知,那么将此通知广播至对应Activity
if (Application.getInstance().isTestNotify) {
// 发送广播
Intent intent = new Intent(Application.RECEIVE_TEST);
intent.putExtra("info", notifyStr.toString());
sendBroadcast(intent);
}
// 如果是本APP的错误通知,那么不做处理,避免死循环
if (getPackageName().equals(packName) && NOTIFY_TITLE_DISPOSE_ERR.equals(title)) {
return;
}
// 检验是否为支付通知
JSONObject info = Application.getInstance().getBasicInfo();
String priKey = Application.getInstance().getBasicPriKey(null);
if (info == null || priKey == null) {
// 如果标题是当前标题,那么就不发送通知,否则会导致死循环
Application.getInstance().sendNotify(NOTIFY_TITLE_DISPOSE_ERR, "没有配置基础信息或密钥,无法处理通知");
return;
}
try {
JSONObject result = getNotifyPayStr(packName, title, content, info);
if (result == null) return;
int amount = result.getIntValue("amount");
String type = result.getString("type");
long time = System.currentTimeMillis();
// 加入数据库
SQLiteDatabase db = Application.spaySql.openWriteLink();
ContentValues sqlValues = new ContentValues();
sqlValues.put("title", title);
sqlValues.put("content", content);
sqlValues.put("type", type);
sqlValues.put("amount", amount);
sqlValues.put("time", time);
long insertId = db.insert("notify_pay", null, sqlValues);
// 调用支付回调接口
if (result.getBooleanValue("isUp")) { | package shendi.pay.service;
/**
* 通知支付服务.
* 创建时间:2023/11/8
* @author Shendi
*/
public class NotifyPayService extends NotificationListenerService {
private static SLog log = SLog.getLogger(NotifyPayService.class.getName());
private static final String NOTIFY_TITLE_DISPOSE_ERR = "监听处理失败";
@Override
public void onCreate() {
super.onCreate();
// 适配8.0及以上,创建渠道
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.createNotificationChannel(new NotificationChannel(Application.NOTIFY_CHANNEL_ID_PAY, Application.NOTIFY_CHANNEL_ID_PAY, NotificationManager.IMPORTANCE_MIN));
}
// 前台服务
startForeground(1, new NotificationCompat.Builder(this, Application.NOTIFY_CHANNEL_ID_PAY)
.setSmallIcon(R.drawable.logo)
.setContentTitle("SPay服务")
.setContentText("安稳运行中...")
.setWhen(System.currentTimeMillis())
.build());
log.i("监听通知服务启动");
}
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
String packName = sbn.getPackageName();
Bundle extras = sbn.getNotification().extras;
Object titleObj = extras.get(Notification.EXTRA_TITLE),
contentObj = extras.get(Notification.EXTRA_TEXT);
if (titleObj == null && contentObj == null) return;
String title = titleObj == null ? "" : titleObj.toString(),
content = contentObj == null ? "" : contentObj.toString();
StringBuilder notifyStr = new StringBuilder();
notifyStr.append("[").append(packName).append("]")
.append(title).append(" : ")
.append(content);
log.i(notifyStr.toString());
// 如果正在测试通知,那么将此通知广播至对应Activity
if (Application.getInstance().isTestNotify) {
// 发送广播
Intent intent = new Intent(Application.RECEIVE_TEST);
intent.putExtra("info", notifyStr.toString());
sendBroadcast(intent);
}
// 如果是本APP的错误通知,那么不做处理,避免死循环
if (getPackageName().equals(packName) && NOTIFY_TITLE_DISPOSE_ERR.equals(title)) {
return;
}
// 检验是否为支付通知
JSONObject info = Application.getInstance().getBasicInfo();
String priKey = Application.getInstance().getBasicPriKey(null);
if (info == null || priKey == null) {
// 如果标题是当前标题,那么就不发送通知,否则会导致死循环
Application.getInstance().sendNotify(NOTIFY_TITLE_DISPOSE_ERR, "没有配置基础信息或密钥,无法处理通知");
return;
}
try {
JSONObject result = getNotifyPayStr(packName, title, content, info);
if (result == null) return;
int amount = result.getIntValue("amount");
String type = result.getString("type");
long time = System.currentTimeMillis();
// 加入数据库
SQLiteDatabase db = Application.spaySql.openWriteLink();
ContentValues sqlValues = new ContentValues();
sqlValues.put("title", title);
sqlValues.put("content", content);
sqlValues.put("type", type);
sqlValues.put("amount", amount);
sqlValues.put("time", time);
long insertId = db.insert("notify_pay", null, sqlValues);
// 调用支付回调接口
if (result.getBooleanValue("isUp")) { | ApiUtil.pay(result.getString("purl"), priKey, amount, type, time, (res) -> { | 2 | 2023-11-09 14:00:45+00:00 | 8k |
Bergerk1/Big-Data-Analytics | src/main/java/de/ddm/actors/profiling/DependencyMiner.java | [
{
"identifier": "LargeMessageProxy",
"path": "src/main/java/de/ddm/actors/patterns/LargeMessageProxy.java",
"snippet": "public class LargeMessageProxy extends AbstractBehavior<LargeMessageProxy.Message> {\n\n\t////////////////////\n\t// Actor Messages //\n\t////////////////////\n\n\tpublic interface Lar... | import akka.actor.typed.ActorRef;
import akka.actor.typed.Behavior;
import akka.actor.typed.Terminated;
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 akka.actor.typed.receptionist.Receptionist;
import akka.actor.typed.receptionist.ServiceKey;
import de.ddm.actors.patterns.LargeMessageProxy;
import de.ddm.serialization.AkkaSerializable;
import de.ddm.singletons.InputConfigurationSingleton;
import de.ddm.singletons.SystemConfigurationSingleton;
import de.ddm.structures.InclusionDependency;
import de.ddm.structures.Task;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.io.File;
import java.lang.reflect.Array;
import java.util.*; | 3,922 | public static final String DEFAULT_NAME = "dependencyMiner";
public static final ServiceKey<DependencyMiner.Message> dependencyMinerService = ServiceKey.create(DependencyMiner.Message.class, DEFAULT_NAME + "Service");
public static Behavior<Message> create() {
return Behaviors.setup(DependencyMiner::new);
}
private DependencyMiner(ActorContext<Message> context) {
super(context);
this.discoverNaryDependencies = SystemConfigurationSingleton.get().isHardMode();
this.inputFiles = InputConfigurationSingleton.get().getInputFiles();
this.headerLines = new String[this.inputFiles.length][];
this.filesRead = new boolean[this.inputFiles.length];
this.headersRead = new boolean[this.inputFiles.length];
this.inputReaders = new ArrayList<>(inputFiles.length);
for (int id = 0; id < this.inputFiles.length; id++)
this.inputReaders.add(context.spawn(InputReader.create(id, this.inputFiles[id]), InputReader.DEFAULT_NAME + "_" + id));
this.resultCollector = context.spawn(ResultCollector.create(), ResultCollector.DEFAULT_NAME);
this.largeMessageProxy = this.getContext().spawn(LargeMessageProxy.create(this.getContext().getSelf().unsafeUpcast()), LargeMessageProxy.DEFAULT_NAME);
this.dependencyWorkers = new ArrayList<>();
context.getSystem().receptionist().tell(Receptionist.register(dependencyMinerService, context.getSelf()));
}
/////////////////
// Actor State //
/////////////////
private long startTime;
private final HashMap<ActorRef<DependencyWorker.Message>,ActorRef<LargeMessageProxy.Message>> workerLMPs = new HashMap<>();
private final boolean discoverNaryDependencies;
private final File[] inputFiles;
private final String[][] headerLines;
private final HashMap<String, Set<String>> columnMap = new HashMap<>();
private final boolean[] filesRead;
private final boolean[] headersRead;
private final List<ActorRef<InputReader.Message>> inputReaders;
private final ActorRef<ResultCollector.Message> resultCollector;
private final ActorRef<LargeMessageProxy.Message> largeMessageProxy;
private Stack<Task> tasks;
private final Map<ActorRef<DependencyWorker.Message>, Task> currentTasks = new HashMap<ActorRef<DependencyWorker.Message>, Task>();
private int totalTasks = -1;
private int tasksDone = 0;
private long dataReadingTime;
private final List<ActorRef<DependencyWorker.Message>> dependencyWorkers;
////////////////////
// Actor Behavior //
////////////////////
@Override
public Receive<Message> createReceive() {
return newReceiveBuilder()
.onMessage(StartMessage.class, this::handle)
.onMessage(BatchMessage.class, this::handle)
.onMessage(HeaderMessage.class, this::handle)
.onMessage(RegistrationMessage.class, this::handle)
.onMessage(CompletionMessage.class, this::handle)
.onSignal(Terminated.class, this::handle)
.build();
}
private Behavior<Message> handle(StartMessage message) {
for (ActorRef<InputReader.Message> inputReader : this.inputReaders)
inputReader.tell(new InputReader.ReadHeaderMessage(this.getContext().getSelf()));
for (ActorRef<InputReader.Message> inputReader : this.inputReaders)
inputReader.tell(new InputReader.ReadBatchMessage(this.getContext().getSelf()));
this.startTime = System.currentTimeMillis();
return this;
}
private Behavior<Message> handle(HeaderMessage message) {
this.headerLines[message.getId()] = message.getHeader();
this.headersRead[message.getId()] = true;
this.advanceIfReady();
return this;
}
private Behavior<Message> handle(BatchMessage message) {
// Ignoring batch content for now ... but I could do so much with it.
if (message.getBatch().size() != 0){
int id = message.getId();
System.out.println("Got Batch of File : " + inputFiles[id].toString());
String filename = inputFiles[id].toString();
for (int column = 0; column < Array.getLength(headerLines[id]); column++){
String key = filename.substring(10) + "_" + headerLines[id][column];
if(!columnMap.containsKey(key))
columnMap.put(key,new HashSet<>());
for (int row = 0; row < message.getBatch().size() ; row++) {
columnMap.get(key).add(message.getBatch().get(row)[column]);
}
}
this.inputReaders.get(message.getId()).tell(new InputReader.ReadBatchMessage(this.getContext().getSelf()));
}else{
this.filesRead[message.getId()] =true;
this.advanceIfReady();
}
return this;
}
private Behavior<Message> handle(RegistrationMessage message) {
ActorRef<DependencyWorker.Message> dependencyWorker = message.getDependencyWorker();
if (!this.dependencyWorkers.contains(dependencyWorker)) {
this.dependencyWorkers.add(dependencyWorker);
this.getContext().watch(dependencyWorker);
workerLMPs.put(message.getDependencyWorker(), message.getWorkerLMP());
if(readyCheck())
sendNextTask(dependencyWorker);
if(tasksDone == totalTasks) end();
}
return this;
}
private Behavior<Message> handle(CompletionMessage message) {
ActorRef<DependencyWorker.Message> dependencyWorker = message.getDependencyWorker();
tasksDone += 1;
if (message.result) { | package de.ddm.actors.profiling;
public class DependencyMiner extends AbstractBehavior<DependencyMiner.Message> {
////////////////////
// Actor Messages //
////////////////////
public interface Message extends AkkaSerializable, LargeMessageProxy.LargeMessage {
}
@NoArgsConstructor
public static class StartMessage implements Message {
private static final long serialVersionUID = -1963913294517850454L;
}
@Getter
@NoArgsConstructor
@AllArgsConstructor
public static class HeaderMessage implements Message {
private static final long serialVersionUID = -5322425954432915838L;
int id;
String[] header;
}
@Getter
@NoArgsConstructor
@AllArgsConstructor
public static class BatchMessage implements Message {
private static final long serialVersionUID = 4591192372652568030L;
int id;
List<String[]> batch;
}
@Getter
@NoArgsConstructor
@AllArgsConstructor
public static class RegistrationMessage implements Message {
private static final long serialVersionUID = -4025238529984914107L;
ActorRef<DependencyWorker.Message> dependencyWorker;
private ActorRef<LargeMessageProxy.Message> workerLMP;
}
@Getter
@NoArgsConstructor
@AllArgsConstructor
public static class CompletionMessage implements Message {
private static final long serialVersionUID = -7642425159675583598L;
ActorRef<DependencyWorker.Message> dependencyWorker;
String referencedAttribute;
String dependentAttribute;
boolean result;
}
////////////////////////
// Actor Construction //
////////////////////////
public static final String DEFAULT_NAME = "dependencyMiner";
public static final ServiceKey<DependencyMiner.Message> dependencyMinerService = ServiceKey.create(DependencyMiner.Message.class, DEFAULT_NAME + "Service");
public static Behavior<Message> create() {
return Behaviors.setup(DependencyMiner::new);
}
private DependencyMiner(ActorContext<Message> context) {
super(context);
this.discoverNaryDependencies = SystemConfigurationSingleton.get().isHardMode();
this.inputFiles = InputConfigurationSingleton.get().getInputFiles();
this.headerLines = new String[this.inputFiles.length][];
this.filesRead = new boolean[this.inputFiles.length];
this.headersRead = new boolean[this.inputFiles.length];
this.inputReaders = new ArrayList<>(inputFiles.length);
for (int id = 0; id < this.inputFiles.length; id++)
this.inputReaders.add(context.spawn(InputReader.create(id, this.inputFiles[id]), InputReader.DEFAULT_NAME + "_" + id));
this.resultCollector = context.spawn(ResultCollector.create(), ResultCollector.DEFAULT_NAME);
this.largeMessageProxy = this.getContext().spawn(LargeMessageProxy.create(this.getContext().getSelf().unsafeUpcast()), LargeMessageProxy.DEFAULT_NAME);
this.dependencyWorkers = new ArrayList<>();
context.getSystem().receptionist().tell(Receptionist.register(dependencyMinerService, context.getSelf()));
}
/////////////////
// Actor State //
/////////////////
private long startTime;
private final HashMap<ActorRef<DependencyWorker.Message>,ActorRef<LargeMessageProxy.Message>> workerLMPs = new HashMap<>();
private final boolean discoverNaryDependencies;
private final File[] inputFiles;
private final String[][] headerLines;
private final HashMap<String, Set<String>> columnMap = new HashMap<>();
private final boolean[] filesRead;
private final boolean[] headersRead;
private final List<ActorRef<InputReader.Message>> inputReaders;
private final ActorRef<ResultCollector.Message> resultCollector;
private final ActorRef<LargeMessageProxy.Message> largeMessageProxy;
private Stack<Task> tasks;
private final Map<ActorRef<DependencyWorker.Message>, Task> currentTasks = new HashMap<ActorRef<DependencyWorker.Message>, Task>();
private int totalTasks = -1;
private int tasksDone = 0;
private long dataReadingTime;
private final List<ActorRef<DependencyWorker.Message>> dependencyWorkers;
////////////////////
// Actor Behavior //
////////////////////
@Override
public Receive<Message> createReceive() {
return newReceiveBuilder()
.onMessage(StartMessage.class, this::handle)
.onMessage(BatchMessage.class, this::handle)
.onMessage(HeaderMessage.class, this::handle)
.onMessage(RegistrationMessage.class, this::handle)
.onMessage(CompletionMessage.class, this::handle)
.onSignal(Terminated.class, this::handle)
.build();
}
private Behavior<Message> handle(StartMessage message) {
for (ActorRef<InputReader.Message> inputReader : this.inputReaders)
inputReader.tell(new InputReader.ReadHeaderMessage(this.getContext().getSelf()));
for (ActorRef<InputReader.Message> inputReader : this.inputReaders)
inputReader.tell(new InputReader.ReadBatchMessage(this.getContext().getSelf()));
this.startTime = System.currentTimeMillis();
return this;
}
private Behavior<Message> handle(HeaderMessage message) {
this.headerLines[message.getId()] = message.getHeader();
this.headersRead[message.getId()] = true;
this.advanceIfReady();
return this;
}
private Behavior<Message> handle(BatchMessage message) {
// Ignoring batch content for now ... but I could do so much with it.
if (message.getBatch().size() != 0){
int id = message.getId();
System.out.println("Got Batch of File : " + inputFiles[id].toString());
String filename = inputFiles[id].toString();
for (int column = 0; column < Array.getLength(headerLines[id]); column++){
String key = filename.substring(10) + "_" + headerLines[id][column];
if(!columnMap.containsKey(key))
columnMap.put(key,new HashSet<>());
for (int row = 0; row < message.getBatch().size() ; row++) {
columnMap.get(key).add(message.getBatch().get(row)[column]);
}
}
this.inputReaders.get(message.getId()).tell(new InputReader.ReadBatchMessage(this.getContext().getSelf()));
}else{
this.filesRead[message.getId()] =true;
this.advanceIfReady();
}
return this;
}
private Behavior<Message> handle(RegistrationMessage message) {
ActorRef<DependencyWorker.Message> dependencyWorker = message.getDependencyWorker();
if (!this.dependencyWorkers.contains(dependencyWorker)) {
this.dependencyWorkers.add(dependencyWorker);
this.getContext().watch(dependencyWorker);
workerLMPs.put(message.getDependencyWorker(), message.getWorkerLMP());
if(readyCheck())
sendNextTask(dependencyWorker);
if(tasksDone == totalTasks) end();
}
return this;
}
private Behavior<Message> handle(CompletionMessage message) {
ActorRef<DependencyWorker.Message> dependencyWorker = message.getDependencyWorker();
tasksDone += 1;
if (message.result) { | List<InclusionDependency> inds = new ArrayList<>(1); | 4 | 2023-11-01 11:57:53+00:00 | 8k |
hlysine/create_power_loader | src/main/java/com/hlysine/create_power_loader/content/trains/CarriageChunkLoader.java | [
{
"identifier": "CPLBlocks",
"path": "src/main/java/com/hlysine/create_power_loader/CPLBlocks.java",
"snippet": "public class CPLBlocks {\n private static final CreateRegistrate REGISTRATE = CreatePowerLoader.getRegistrate();\n\n public static final BlockEntry<EmptyChunkLoaderBlock> EMPTY_ANDESITE... | import com.hlysine.create_power_loader.CPLBlocks;
import com.hlysine.create_power_loader.config.CPLConfigs;
import com.hlysine.create_power_loader.content.ChunkLoadManager;
import com.hlysine.create_power_loader.content.ChunkLoader;
import com.hlysine.create_power_loader.content.LoaderMode;
import com.hlysine.create_power_loader.content.LoaderType;
import com.simibubi.create.content.contraptions.Contraption;
import com.simibubi.create.content.contraptions.behaviour.MovementContext;
import com.simibubi.create.content.trains.entity.Carriage;
import com.simibubi.create.content.trains.entity.CarriageContraptionEntity;
import com.simibubi.create.content.trains.entity.TravellingPoint;
import com.simibubi.create.foundation.utility.Pair;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate;
import org.apache.commons.lang3.tuple.MutablePair;
import org.jetbrains.annotations.NotNull;
import java.util.HashSet;
import java.util.Set;
import static com.hlysine.create_power_loader.content.ChunkLoadManager.LoadedChunkPos; | 6,003 | package com.hlysine.create_power_loader.content.trains;
public class CarriageChunkLoader implements ChunkLoader {
public final Carriage carriage;
public boolean known;
public boolean andesite;
public boolean brass;
public final Set<LoadedChunkPos> forcedChunks = new HashSet<>();
public CarriageChunkLoader(Carriage carriage, boolean known, boolean andesite, boolean brass) {
this.carriage = carriage;
this.known = known;
this.andesite = andesite;
this.brass = brass;
}
@Override
public @NotNull Set<LoadedChunkPos> getForcedChunks() {
return forcedChunks;
}
@Override
public LoaderMode getLoaderMode() {
return LoaderMode.TRAIN;
}
@Override
public LoaderType getLoaderType() {
return brass ? LoaderType.BRASS : LoaderType.ANDESITE;
}
@Override
public Pair<ResourceLocation, BlockPos> getLocation() {
if (carriage.train.graph == null) return null;
return Pair.of(
carriage.leadingBogey().trailing().node1.getLocation().getDimension().location(),
BlockPos.containing(carriage.leadingBogey().trailing().getPosition(carriage.train.graph))
);
}
public void tick(Level level) {
if (!known) updateCarriage();
if (!known) return;
if (!canLoadChunks()) {
if (!forcedChunks.isEmpty())
ChunkLoadManager.unforceAllChunks(level.getServer(), carriage.train.id, forcedChunks);
return;
}
Set<LoadedChunkPos> loadTargets = new HashSet<>();
addLoadTargets(loadTargets, carriage.leadingBogey().trailing());
addLoadTargets(loadTargets, carriage.trailingBogey().leading());
ChunkLoadManager.updateForcedChunks(level.getServer(), loadTargets, carriage.train.id, 2, forcedChunks);
}
public void onRemove() {
ChunkLoadManager.enqueueUnforceAll(carriage.train.id, forcedChunks);
}
private void addLoadTargets(Set<LoadedChunkPos> loadTargets, TravellingPoint point) {
if (point.edge.isInterDimensional()) {
loadTargets.add(new LoadedChunkPos(
point.node1.getLocation().getDimension().location(),
new ChunkPos(BlockPos.containing(point.node1.getLocation().getLocation()))
));
loadTargets.add(new LoadedChunkPos(
point.node2.getLocation().getDimension().location(),
new ChunkPos(BlockPos.containing(point.node2.getLocation().getLocation()))
));
} else {
loadTargets.add(new LoadedChunkPos(
point.node1.getLocation().getDimension().location(),
new ChunkPos(BlockPos.containing(point.getPosition(carriage.train.graph)))
));
}
}
private void updateCarriage() {
CarriageContraptionEntity entity = carriage.anyAvailableEntity();
known = entity != null;
if (!known) return;
Contraption contraption = entity.getContraption();
andesite = !contraption.isActorTypeDisabled(ItemStack.EMPTY) && !contraption.isActorTypeDisabled(CPLBlocks.ANDESITE_CHUNK_LOADER.asStack());
brass = !contraption.isActorTypeDisabled(ItemStack.EMPTY) && !contraption.isActorTypeDisabled(CPLBlocks.BRASS_CHUNK_LOADER.asStack());
if (!andesite && !brass) return;
boolean hasAndesite = false, hasBrass = false;
for (MutablePair<StructureTemplate.StructureBlockInfo, MovementContext> actor : entity.getContraption().getActors()) {
if (!hasAndesite && actor.left.state().is(CPLBlocks.ANDESITE_CHUNK_LOADER.get())) {
hasAndesite = true;
}
if (!hasBrass && actor.left.state().is(CPLBlocks.BRASS_CHUNK_LOADER.get())) {
hasBrass = true;
}
if (hasAndesite && hasBrass) break;
}
andesite = hasAndesite;
brass = hasBrass;
}
private boolean canLoadChunks() {
if (carriage.train.graph == null) return false; | package com.hlysine.create_power_loader.content.trains;
public class CarriageChunkLoader implements ChunkLoader {
public final Carriage carriage;
public boolean known;
public boolean andesite;
public boolean brass;
public final Set<LoadedChunkPos> forcedChunks = new HashSet<>();
public CarriageChunkLoader(Carriage carriage, boolean known, boolean andesite, boolean brass) {
this.carriage = carriage;
this.known = known;
this.andesite = andesite;
this.brass = brass;
}
@Override
public @NotNull Set<LoadedChunkPos> getForcedChunks() {
return forcedChunks;
}
@Override
public LoaderMode getLoaderMode() {
return LoaderMode.TRAIN;
}
@Override
public LoaderType getLoaderType() {
return brass ? LoaderType.BRASS : LoaderType.ANDESITE;
}
@Override
public Pair<ResourceLocation, BlockPos> getLocation() {
if (carriage.train.graph == null) return null;
return Pair.of(
carriage.leadingBogey().trailing().node1.getLocation().getDimension().location(),
BlockPos.containing(carriage.leadingBogey().trailing().getPosition(carriage.train.graph))
);
}
public void tick(Level level) {
if (!known) updateCarriage();
if (!known) return;
if (!canLoadChunks()) {
if (!forcedChunks.isEmpty())
ChunkLoadManager.unforceAllChunks(level.getServer(), carriage.train.id, forcedChunks);
return;
}
Set<LoadedChunkPos> loadTargets = new HashSet<>();
addLoadTargets(loadTargets, carriage.leadingBogey().trailing());
addLoadTargets(loadTargets, carriage.trailingBogey().leading());
ChunkLoadManager.updateForcedChunks(level.getServer(), loadTargets, carriage.train.id, 2, forcedChunks);
}
public void onRemove() {
ChunkLoadManager.enqueueUnforceAll(carriage.train.id, forcedChunks);
}
private void addLoadTargets(Set<LoadedChunkPos> loadTargets, TravellingPoint point) {
if (point.edge.isInterDimensional()) {
loadTargets.add(new LoadedChunkPos(
point.node1.getLocation().getDimension().location(),
new ChunkPos(BlockPos.containing(point.node1.getLocation().getLocation()))
));
loadTargets.add(new LoadedChunkPos(
point.node2.getLocation().getDimension().location(),
new ChunkPos(BlockPos.containing(point.node2.getLocation().getLocation()))
));
} else {
loadTargets.add(new LoadedChunkPos(
point.node1.getLocation().getDimension().location(),
new ChunkPos(BlockPos.containing(point.getPosition(carriage.train.graph)))
));
}
}
private void updateCarriage() {
CarriageContraptionEntity entity = carriage.anyAvailableEntity();
known = entity != null;
if (!known) return;
Contraption contraption = entity.getContraption();
andesite = !contraption.isActorTypeDisabled(ItemStack.EMPTY) && !contraption.isActorTypeDisabled(CPLBlocks.ANDESITE_CHUNK_LOADER.asStack());
brass = !contraption.isActorTypeDisabled(ItemStack.EMPTY) && !contraption.isActorTypeDisabled(CPLBlocks.BRASS_CHUNK_LOADER.asStack());
if (!andesite && !brass) return;
boolean hasAndesite = false, hasBrass = false;
for (MutablePair<StructureTemplate.StructureBlockInfo, MovementContext> actor : entity.getContraption().getActors()) {
if (!hasAndesite && actor.left.state().is(CPLBlocks.ANDESITE_CHUNK_LOADER.get())) {
hasAndesite = true;
}
if (!hasBrass && actor.left.state().is(CPLBlocks.BRASS_CHUNK_LOADER.get())) {
hasBrass = true;
}
if (hasAndesite && hasBrass) break;
}
andesite = hasAndesite;
brass = hasBrass;
}
private boolean canLoadChunks() {
if (carriage.train.graph == null) return false; | return andesite && CPLConfigs.server().andesiteOnContraption.get() || brass && CPLConfigs.server().brassOnContraption.get(); | 1 | 2023-11-09 04:29:33+00:00 | 8k |
dingodb/dingo-expr | runtime/src/main/java/io/dingodb/expr/runtime/op/cast/LongCastCheckOp.java | [
{
"identifier": "CastingException",
"path": "runtime/src/main/java/io/dingodb/expr/runtime/exception/CastingException.java",
"snippet": "public class CastingException extends ExprEvaluatingException {\n private static final long serialVersionUID = 7400509568348847209L;\n\n public CastingException(... | import io.dingodb.expr.annotations.Operators;
import io.dingodb.expr.runtime.exception.CastingException;
import io.dingodb.expr.runtime.type.Type;
import io.dingodb.expr.runtime.type.Types;
import io.dingodb.expr.runtime.utils.ExceptionUtils;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.math.BigDecimal;
import java.math.RoundingMode; | 4,248 | /*
* 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.cast;
@Operators
abstract class LongCastCheckOp extends CastOp {
private static final long serialVersionUID = -4999428444641603223L;
static long longCast(int value) {
return value;
}
static long longCast(long value) {
return value;
}
static long longCast(float value) {
long r = Math.round((double) value);
if (2 * Math.abs((float) r - value) <= 1.0f) {
return r;
} | /*
* 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.cast;
@Operators
abstract class LongCastCheckOp extends CastOp {
private static final long serialVersionUID = -4999428444641603223L;
static long longCast(int value) {
return value;
}
static long longCast(long value) {
return value;
}
static long longCast(float value) {
long r = Math.round((double) value);
if (2 * Math.abs((float) r - value) <= 1.0f) {
return r;
} | throw new CastingException(Types.LONG, Types.FLOAT, ExceptionUtils.exceedsLongRange()); | 2 | 2023-11-04 08:43:49+00:00 | 8k |
sesamecare/stripe-mock | src/main/java/com/sesame/oss/stripemock/entities/AbstractEntityManager.java | [
{
"identifier": "StripeMock",
"path": "src/main/java/com/sesame/oss/stripemock/StripeMock.java",
"snippet": "public class StripeMock {\n /**\n * When switching from using a normal stripe integration during testing, there might be \"known\" values, for example customers with a known\n * set of... | import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.sesame.oss.stripemock.StripeMock;
import com.sesame.oss.stripemock.http.QueryParameters;
import com.sesame.oss.stripemock.http.ResponseCodeException;
import com.sesame.oss.stripemock.util.Utilities;
import com.stripe.model.HasId;
import com.stripe.net.ApiResource;
import java.time.Clock;
import java.time.Instant;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate; | 4,262 | package com.sesame.oss.stripemock.entities;
abstract class AbstractEntityManager<T extends ApiResource & HasId> implements EntityManager<T> {
/**
* This is a special operation that is used when an entity is updated.
*/
protected static final String MAGIC_UPDATE_OPERATION = "__update";
protected final Map<String, T> entities = new HashMap<>();
protected final Clock clock;
private final Class<T> entityClass;
private final String idPrefix;
private final int idLength;
protected AbstractEntityManager(Clock clock, Class<T> entityClass, String idPrefix, int idLength) {
this.clock = clock;
this.entityClass = entityClass;
this.idPrefix = idPrefix;
this.idLength = idLength;
}
@Override
public T add(Map<String, Object> formData, String parentEntityType, String parentEntityId) throws ResponseCodeException {
// Most entities do not support related sub-entities, so this is a reasonable default
throw new UnsupportedOperationException("Entity does not support sub-entities");
}
@Override
public T add(Map<String, Object> formData) throws ResponseCodeException {
// They give us form data, so this is a ghetto way to turn it back into an object.
// We're the only ones that are allowed to specify what the id should be
String id = Utilities.randomIdWithPrefix(idPrefix, idLength);
// metadata must always be a map, even if it's empty. It should never be null.
// So we can kill two birds with one stone, here
Map<String, Object> metadata = (Map<String, Object>) formData.computeIfAbsent("metadata", ignored -> new HashMap<>());
String idOverride = (String) metadata.remove(StripeMock.OVERRIDE_ID_FOR_TESTING);
if (idOverride != null) {
id = idOverride;
}
formData.put("id", id);
formData.put("livemode", false);
formData.put("created",
Instant.now(clock)
.getEpochSecond());
ensureFormDataSpecifiesObjectType(formData);
T entity = initialize(parse(formData), formData);
validate(entity);
T existing = entities.putIfAbsent(id, entity);
if (existing != null) {
// This shouldn't happen unless people start overriding ids, but we should still check
throw new ResponseCodeException(400, String.format("Overridden %s with id %s already exists", entityClass.getSimpleName(), id));
}
return entity;
}
@Override
public final Optional<T> perform(String id, String operation, Map<String, Object> formData) throws ResponseCodeException {
T existingEntity = entities.get(id);
if (existingEntity == null) {
return Optional.empty();
}
JsonObject root = Utilities.PRODUCER_GSON.toJsonTree(existingEntity)
.getAsJsonObject();
merge(root, formData);
T newEntity = ApiResource.GSON.fromJson(root, entityClass);
T postOperationEntity = perform(existingEntity, newEntity, operation, formData);
validate(postOperationEntity);
entities.put(id, postOperationEntity);
// For now, there's nothing to do here. In reality we'd do stuff like trigger webhooks etc.
return Optional.of(newEntity);
}
@Override
public Optional<T> update(String id, Map<String, Object> formData) throws ResponseCodeException {
return perform(id, MAGIC_UPDATE_OPERATION, formData);
}
@Override
public Optional<T> get(String id) throws ResponseCodeException {
return Optional.ofNullable(entities.get(id));
}
@Override | package com.sesame.oss.stripemock.entities;
abstract class AbstractEntityManager<T extends ApiResource & HasId> implements EntityManager<T> {
/**
* This is a special operation that is used when an entity is updated.
*/
protected static final String MAGIC_UPDATE_OPERATION = "__update";
protected final Map<String, T> entities = new HashMap<>();
protected final Clock clock;
private final Class<T> entityClass;
private final String idPrefix;
private final int idLength;
protected AbstractEntityManager(Clock clock, Class<T> entityClass, String idPrefix, int idLength) {
this.clock = clock;
this.entityClass = entityClass;
this.idPrefix = idPrefix;
this.idLength = idLength;
}
@Override
public T add(Map<String, Object> formData, String parentEntityType, String parentEntityId) throws ResponseCodeException {
// Most entities do not support related sub-entities, so this is a reasonable default
throw new UnsupportedOperationException("Entity does not support sub-entities");
}
@Override
public T add(Map<String, Object> formData) throws ResponseCodeException {
// They give us form data, so this is a ghetto way to turn it back into an object.
// We're the only ones that are allowed to specify what the id should be
String id = Utilities.randomIdWithPrefix(idPrefix, idLength);
// metadata must always be a map, even if it's empty. It should never be null.
// So we can kill two birds with one stone, here
Map<String, Object> metadata = (Map<String, Object>) formData.computeIfAbsent("metadata", ignored -> new HashMap<>());
String idOverride = (String) metadata.remove(StripeMock.OVERRIDE_ID_FOR_TESTING);
if (idOverride != null) {
id = idOverride;
}
formData.put("id", id);
formData.put("livemode", false);
formData.put("created",
Instant.now(clock)
.getEpochSecond());
ensureFormDataSpecifiesObjectType(formData);
T entity = initialize(parse(formData), formData);
validate(entity);
T existing = entities.putIfAbsent(id, entity);
if (existing != null) {
// This shouldn't happen unless people start overriding ids, but we should still check
throw new ResponseCodeException(400, String.format("Overridden %s with id %s already exists", entityClass.getSimpleName(), id));
}
return entity;
}
@Override
public final Optional<T> perform(String id, String operation, Map<String, Object> formData) throws ResponseCodeException {
T existingEntity = entities.get(id);
if (existingEntity == null) {
return Optional.empty();
}
JsonObject root = Utilities.PRODUCER_GSON.toJsonTree(existingEntity)
.getAsJsonObject();
merge(root, formData);
T newEntity = ApiResource.GSON.fromJson(root, entityClass);
T postOperationEntity = perform(existingEntity, newEntity, operation, formData);
validate(postOperationEntity);
entities.put(id, postOperationEntity);
// For now, there's nothing to do here. In reality we'd do stuff like trigger webhooks etc.
return Optional.of(newEntity);
}
@Override
public Optional<T> update(String id, Map<String, Object> formData) throws ResponseCodeException {
return perform(id, MAGIC_UPDATE_OPERATION, formData);
}
@Override
public Optional<T> get(String id) throws ResponseCodeException {
return Optional.ofNullable(entities.get(id));
}
@Override | public List<T> list(QueryParameters query) { | 1 | 2023-11-03 08:51:13+00:00 | 8k |
Arborsm/ArborCore | src/main/java/org/arbor/gtnn/init/AddonProxy.java | [
{
"identifier": "NeutronActivatorCondition",
"path": "src/main/java/org/arbor/gtnn/api/recipe/NeutronActivatorCondition.java",
"snippet": "@Getter\npublic class NeutronActivatorCondition extends RecipeCondition {\n public static final NeutronActivatorCondition INSTANCE = new NeutronActivatorCondition... | import com.gregtechceu.gtceu.api.registry.GTRegistries;
import com.lowdragmc.lowdraglib.Platform;
import org.arbor.gtnn.api.recipe.NeutronActivatorCondition;
import org.arbor.gtnn.api.recipe.PlantCasingCondition;
import org.arbor.gtnn.api.registry.GTNNRegistries;
import org.arbor.gtnn.data.GTNNBlocks;
import org.arbor.gtnn.data.GTNNItems;
import org.arbor.gtnn.data.GTNNMachines; | 4,832 | package org.arbor.gtnn.init;
public class AddonProxy {
public static void init(){
GTNNItems.init(); | package org.arbor.gtnn.init;
public class AddonProxy {
public static void init(){
GTNNItems.init(); | GTNNBlocks.init(); | 3 | 2023-11-04 07:59:02+00:00 | 8k |
WebNetMC/WebNetBedwars | src/main/java/dev/foxikle/webnetbedwars/WebNetBedWars.java | [
{
"identifier": "DebugCommand",
"path": "src/main/java/dev/foxikle/webnetbedwars/commands/DebugCommand.java",
"snippet": "public class DebugCommand implements CommandExecutor, TabCompleter {\n private final WebNetBedWars plugin;\n\n public DebugCommand(WebNetBedWars plugin) {\n this.plugin ... | import dev.foxikle.customnpcs.api.NPCApi;
import dev.foxikle.webnetbedwars.commands.DebugCommand;
import dev.foxikle.webnetbedwars.commands.ItemCommand;
import dev.foxikle.webnetbedwars.listeners.*;
import dev.foxikle.webnetbedwars.managers.GameManager;
import me.flame.menus.menu.Menus;
import net.minecraft.world.level.block.Blocks;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.util.Arrays;
import java.util.List; | 5,784 | package dev.foxikle.webnetbedwars;
public final class WebNetBedWars extends JavaPlugin {
private GameManager gameManager;
public static WebNetBedWars INSTANCE;
private ItemAbilityDispatcher itemAbilityDispatcher;
@Override
public void onEnable() {
INSTANCE = this;
File file = new File("plugins/WebNetBedWars/config.yml");
if(!file.exists())
this.saveResource("config.yml", false);
gameManager = new GameManager(this);
registerCommands();
registerListeners();
gameManager.setup();
NPCApi.initialize();
changeBlastResistence();
itemAbilityDispatcher = new ItemAbilityDispatcher(this);
Menus.init(this);
}
private void changeBlastResistence(){
//aF == resistence
Arrays.stream(Blocks.GLASS.getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredFields()).forEach(field -> {
if(field.getType() == float.class){
try {
field.setAccessible(true);
if(field.getName().equals("aF")){
field.setFloat(Blocks.GLASS, 1200.0F);
field.setFloat(Blocks.BLACK_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.WHITE_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.CYAN_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.LIGHT_BLUE_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.BLUE_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.PINK_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.PURPLE_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.LIME_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.GREEN_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.RED_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.ORANGE_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.YELLOW_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.LIGHT_GRAY_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.GRAY_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.BROWN_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.MAGENTA_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.BLACK_BED, 1200.0F);
field.setFloat(Blocks.WHITE_BED, 1200.0F);
field.setFloat(Blocks.CYAN_BED, 1200.0F);
field.setFloat(Blocks.LIGHT_BLUE_BED, 1200.0F);
field.setFloat(Blocks.BLUE_BED, 1200.0F);
field.setFloat(Blocks.PINK_BED, 1200.0F);
field.setFloat(Blocks.PURPLE_BED, 1200.0F);
field.setFloat(Blocks.LIME_BED, 1200.0F);
field.setFloat(Blocks.GREEN_BED, 1200.0F);
field.setFloat(Blocks.RED_BED, 1200.0F);
field.setFloat(Blocks.ORANGE_BED, 1200.0F);
field.setFloat(Blocks.YELLOW_BED, 1200.0F);
field.setFloat(Blocks.LIGHT_GRAY_BED, 1200.0F);
field.setFloat(Blocks.GRAY_BED, 1200.0F);
field.setFloat(Blocks.BROWN_BED, 1200.0F);
field.setFloat(Blocks.MAGENTA_BED, 1200.0F);
}
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
});
}
@Override
public void onDisable() {
gameManager.cleanup();
}
private void registerListeners(){
getServer().getPluginManager().registerEvents(new DamageListener(this), this);
getServer().getPluginManager().registerEvents(new JoinListener(this), this);
getServer().getPluginManager().registerEvents(new LeaveListener(this), this);
getServer().getPluginManager().registerEvents(new BlockBreakListener(this), this);
getServer().getPluginManager().registerEvents(new BlockPlaceListener(this), this);
getServer().getPluginManager().registerEvents(new ExplosionListener(this), this);
getServer().getPluginManager().registerEvents(new InteractListener(this), this);
getServer().getPluginManager().registerEvents(new MoveListener(this), this);
getServer().getPluginManager().registerEvents(new GamemodeChangeListener(this), this);
getServer().getPluginManager().registerEvents(new ArmorEquipListener(this), this);
getServer().getPluginManager().registerEvents(new InventoryClickListener(this), this);
getServer().getPluginManager().registerEvents(new DropItemListener(this), this);
}
private void registerCommands(){
getCommand("debug").setExecutor(new DebugCommand(this)); | package dev.foxikle.webnetbedwars;
public final class WebNetBedWars extends JavaPlugin {
private GameManager gameManager;
public static WebNetBedWars INSTANCE;
private ItemAbilityDispatcher itemAbilityDispatcher;
@Override
public void onEnable() {
INSTANCE = this;
File file = new File("plugins/WebNetBedWars/config.yml");
if(!file.exists())
this.saveResource("config.yml", false);
gameManager = new GameManager(this);
registerCommands();
registerListeners();
gameManager.setup();
NPCApi.initialize();
changeBlastResistence();
itemAbilityDispatcher = new ItemAbilityDispatcher(this);
Menus.init(this);
}
private void changeBlastResistence(){
//aF == resistence
Arrays.stream(Blocks.GLASS.getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass().getDeclaredFields()).forEach(field -> {
if(field.getType() == float.class){
try {
field.setAccessible(true);
if(field.getName().equals("aF")){
field.setFloat(Blocks.GLASS, 1200.0F);
field.setFloat(Blocks.BLACK_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.WHITE_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.CYAN_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.LIGHT_BLUE_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.BLUE_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.PINK_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.PURPLE_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.LIME_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.GREEN_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.RED_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.ORANGE_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.YELLOW_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.LIGHT_GRAY_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.GRAY_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.BROWN_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.MAGENTA_STAINED_GLASS, 1200.0F);
field.setFloat(Blocks.BLACK_BED, 1200.0F);
field.setFloat(Blocks.WHITE_BED, 1200.0F);
field.setFloat(Blocks.CYAN_BED, 1200.0F);
field.setFloat(Blocks.LIGHT_BLUE_BED, 1200.0F);
field.setFloat(Blocks.BLUE_BED, 1200.0F);
field.setFloat(Blocks.PINK_BED, 1200.0F);
field.setFloat(Blocks.PURPLE_BED, 1200.0F);
field.setFloat(Blocks.LIME_BED, 1200.0F);
field.setFloat(Blocks.GREEN_BED, 1200.0F);
field.setFloat(Blocks.RED_BED, 1200.0F);
field.setFloat(Blocks.ORANGE_BED, 1200.0F);
field.setFloat(Blocks.YELLOW_BED, 1200.0F);
field.setFloat(Blocks.LIGHT_GRAY_BED, 1200.0F);
field.setFloat(Blocks.GRAY_BED, 1200.0F);
field.setFloat(Blocks.BROWN_BED, 1200.0F);
field.setFloat(Blocks.MAGENTA_BED, 1200.0F);
}
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
});
}
@Override
public void onDisable() {
gameManager.cleanup();
}
private void registerListeners(){
getServer().getPluginManager().registerEvents(new DamageListener(this), this);
getServer().getPluginManager().registerEvents(new JoinListener(this), this);
getServer().getPluginManager().registerEvents(new LeaveListener(this), this);
getServer().getPluginManager().registerEvents(new BlockBreakListener(this), this);
getServer().getPluginManager().registerEvents(new BlockPlaceListener(this), this);
getServer().getPluginManager().registerEvents(new ExplosionListener(this), this);
getServer().getPluginManager().registerEvents(new InteractListener(this), this);
getServer().getPluginManager().registerEvents(new MoveListener(this), this);
getServer().getPluginManager().registerEvents(new GamemodeChangeListener(this), this);
getServer().getPluginManager().registerEvents(new ArmorEquipListener(this), this);
getServer().getPluginManager().registerEvents(new InventoryClickListener(this), this);
getServer().getPluginManager().registerEvents(new DropItemListener(this), this);
}
private void registerCommands(){
getCommand("debug").setExecutor(new DebugCommand(this)); | getCommand("item").setExecutor(new ItemCommand()); | 1 | 2023-11-04 00:18:20+00:00 | 8k |
satisfyu/HerbalBrews | common/src/main/java/satisfyu/herbalbrews/blocks/CauldronBlock.java | [
{
"identifier": "CauldronBlockEntity",
"path": "common/src/main/java/satisfyu/herbalbrews/entities/CauldronBlockEntity.java",
"snippet": "public class CauldronBlockEntity extends BlockEntity implements ImplementedInventory, BlockEntityTicker<CauldronBlockEntity>, MenuProvider {\n private NonNullList<... | import net.minecraft.ChatFormatting;
import net.minecraft.Util;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.core.particles.SimpleParticleType;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.util.RandomSource;
import net.minecraft.world.Containers;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.MenuProvider;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.item.enchantment.EnchantmentHelper;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.EntityBlock;
import net.minecraft.world.level.block.HorizontalDirectionalBlock;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityTicker;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import net.minecraft.world.level.block.state.properties.BooleanProperty;
import net.minecraft.world.level.block.state.properties.DirectionProperty;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.Vec3;
import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape;
import org.jetbrains.annotations.Nullable;
import satisfyu.herbalbrews.entities.CauldronBlockEntity;
import satisfyu.herbalbrews.util.GeneralUtil;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier; | 5,399 | if (world instanceof ServerLevel) {
Containers.dropContents(world, pos, entity);
}
world.updateNeighbourForOutputSignal(pos, this);
}
super.onRemove(state, world, pos, newState, moved);
}
@Override
@Nullable
public BlockState getStateForPlacement(BlockPlaceContext ctx) {
return this.defaultBlockState().setValue(FACING, ctx.getHorizontalDirection().getOpposite());
}
@Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
builder.add(FACING);
}
@Nullable
@Override
public <T extends BlockEntity> BlockEntityTicker<T> getTicker(Level world, BlockState state, BlockEntityType<T> type) {
return (theWorld, pos, theState, blockEntity) -> {
if (blockEntity instanceof BlockEntityTicker<?>) {
((BlockEntityTicker) blockEntity).tick(theWorld, pos, theState, blockEntity);
}
};
}
@Nullable
@Override
public BlockEntity newBlockEntity(BlockPos pos, BlockState state) {
return new CauldronBlockEntity(pos, state);
}
@Override
public void animateTick(BlockState state, Level world, BlockPos pos, RandomSource random) {
double blockX = (double) pos.getX() + 0.5;
double blockY = pos.getY() + 0.24;
double blockZ = (double) pos.getZ() + 0.5;
if (random.nextDouble() < 0.1)
world.playLocalSound(blockX, blockY, blockZ, SoundEvents.FURNACE_FIRE_CRACKLE, SoundSource.BLOCKS, 1.0f, 1.0f, false);
world.playLocalSound(blockX, blockY, blockZ, SoundEvents.SMOKER_SMOKE, SoundSource.BLOCKS, 1.0f, 1.0f, false);
world.playLocalSound(blockX, blockY, blockZ, SoundEvents.CAMPFIRE_CRACKLE, SoundSource.BLOCKS, 1.0f, 1.0f, false);
for (Direction direction : Direction.values()) {
if (direction != Direction.DOWN) {
double offsetX = random.nextDouble() * 0.6 - 0.3;
double offsetY = random.nextDouble() * 6.0 / 16.0;
double offsetZ = random.nextDouble() * 0.6 - 0.3;
double particleX = blockX + offsetX + 0.5 * direction.getStepX();
double particleY = blockY + offsetY;
double particleZ = blockZ + offsetZ + 0.5 * direction.getStepZ();
world.addParticle(ParticleTypes.SMOKE, particleX, particleY, particleZ, 0.0, 0.0, 0.0);
world.addParticle(ParticleTypes.SOUL_FIRE_FLAME, particleX, particleY, particleZ, 0.0, 0.0, 0.0);
if (random.nextDouble() < 0.6) {
double middleParticleX = blockX + offsetX + 0.5 * direction.getStepX() * random.nextDouble();
double middleParticleY = blockY + offsetY + 0.7 * random.nextDouble();
double middleParticleZ = blockZ + offsetZ + 0.5 * direction.getStepZ() * random.nextDouble();
world.addParticle(ParticleTypes.BUBBLE_POP, middleParticleX, middleParticleY, middleParticleZ, 0.0, 0.0, 0.0);
}
if (random.nextDouble() < 0.1) {
SimpleParticleType simpleParticleType = ParticleTypes.CAMPFIRE_COSY_SMOKE;
world.addAlwaysVisibleParticle(simpleParticleType, true, pos.getX() + 0.5 + random.nextDouble() / 3.0 * (random.nextBoolean() ? 1 : -1), pos.getY() + random.nextDouble() + random.nextDouble(), pos.getZ() + 0.5 + random.nextDouble() / 3.0 * (random.nextBoolean() ? 1 : -1), 0.0, 0.07, 0.0);
world.addParticle(ParticleTypes.SMOKE, pos.getX() + 0.5 + random.nextDouble() / 4.0 * (random.nextBoolean() ? 1 : -1), pos.getY() + 2.2, pos.getZ() + 0.5 + random.nextDouble() / 4.0 * (random.nextBoolean() ? 1 : -1), 0.0, 0.005, 0.0);
}
}
}
}
@Override
public void stepOn(Level world, BlockPos pos, BlockState state, Entity entity) {
if (!entity.fireImmune() && entity instanceof LivingEntity livingEntity &&
!EnchantmentHelper.hasFrostWalker(livingEntity)) {
entity.hurt(world.damageSources().hotFloor(), 1.f);
}
super.stepOn(world, pos, state, entity);
}
@Override
public void appendHoverText(ItemStack itemStack, BlockGetter world, List<Component> tooltip, TooltipFlag tooltipContext) {
tooltip.add(Component.translatable("tooltip.herbalbrews.cauldron").withStyle(ChatFormatting.WHITE));
tooltip.add(Component.empty());
tooltip.add(Component.translatable("tooltip.herbalbrews.canbeplaced").withStyle(ChatFormatting.ITALIC, ChatFormatting.GRAY));
}
private static final Supplier<VoxelShape> voxelShapeSupplier = () -> {
VoxelShape shape = Shapes.empty();
shape = Shapes.or(shape, Shapes.box(0, 0, 0, 0.125, 0.1875, 0.25));
shape = Shapes.or(shape, Shapes.box(0.125, 0, 0, 0.25, 0.1875, 0.125));
shape = Shapes.or(shape, Shapes.box(0.75, 0, 0, 1, 0.1875, 0.125));
shape = Shapes.or(shape, Shapes.box(0.875, 0, 0.125, 1, 0.1875, 0.25));
shape = Shapes.or(shape, Shapes.box(0.875, 0, 0.75, 1, 0.1875, 1));
shape = Shapes.or(shape, Shapes.box(0.75, 0, 0.875, 0.875, 0.1875, 1));
shape = Shapes.or(shape, Shapes.box(0, 0, 0.875, 0.25, 0.1875, 1));
shape = Shapes.or(shape, Shapes.box(0, 0, 0.75, 0.125, 0.1875, 0.875));
shape = Shapes.or(shape, Shapes.box(0, 0.1875, 0, 1, 0.6875, 1));
shape = Shapes.or(shape, Shapes.box(0.0625, 0.6875, 0.0625, 0.9375, 0.8125, 0.9375));
shape = Shapes.or(shape, Shapes.box(0, 0.8125, 0.8125, 1, 1, 1));
shape = Shapes.or(shape, Shapes.box(0, 0.8125, 0, 1, 1, 0.1875));
shape = Shapes.or(shape, Shapes.box(0, 0.8125, 0.1875, 0.1875, 1, 0.8125));
shape = Shapes.or(shape, Shapes.box(0.8125, 0.8125, 0.1875, 1, 1, 0.8125));
shape = Shapes.or(shape, Shapes.box(0.125, 0.0625, 0.125, 0.875, 0.25, 0.875));
shape = Shapes.or(shape, Shapes.box(0.0625, 0.000625, 0.0625, 0.9375, 0.063125, 0.9375));
shape = Shapes.or(shape, Shapes.box(0.1875, 0.0625, 0.6875, 0.8125, 0.1875, 0.8125));
shape = Shapes.or(shape, Shapes.box(0.1875, 0.0625, 0.4375, 0.8125, 0.1875, 0.5625));
shape = Shapes.or(shape, Shapes.box(0.1875, 0.0625, 0.1875, 0.8125, 0.1875, 0.3125));
return shape;
};
public static final Map<Direction, VoxelShape> SHAPE = Util.make(new HashMap<>(), map -> {
for (Direction direction : Direction.Plane.HORIZONTAL.stream().toList()) { | package satisfyu.herbalbrews.blocks;
public class CauldronBlock extends Block implements EntityBlock {
public static final DirectionProperty FACING = HorizontalDirectionalBlock.FACING;
public CauldronBlock(Properties settings) {
super(settings);
this.registerDefaultState(this.defaultBlockState().setValue(FACING, Direction.NORTH));
}
@Override
public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) {
final BlockEntity entity = world.getBlockEntity(pos);
if (entity instanceof MenuProvider factory) {
player.openMenu(factory);
return InteractionResult.sidedSuccess(world.isClientSide());
} else {
return InteractionResult.PASS;
}
}
@Override
public void onRemove(BlockState state, Level world, BlockPos pos, BlockState newState, boolean moved) {
if (state.is(newState.getBlock())) {
return;
}
final BlockEntity blockEntity = world.getBlockEntity(pos);
if (blockEntity instanceof CauldronBlockEntity entity) {
if (world instanceof ServerLevel) {
Containers.dropContents(world, pos, entity);
}
world.updateNeighbourForOutputSignal(pos, this);
}
super.onRemove(state, world, pos, newState, moved);
}
@Override
@Nullable
public BlockState getStateForPlacement(BlockPlaceContext ctx) {
return this.defaultBlockState().setValue(FACING, ctx.getHorizontalDirection().getOpposite());
}
@Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
builder.add(FACING);
}
@Nullable
@Override
public <T extends BlockEntity> BlockEntityTicker<T> getTicker(Level world, BlockState state, BlockEntityType<T> type) {
return (theWorld, pos, theState, blockEntity) -> {
if (blockEntity instanceof BlockEntityTicker<?>) {
((BlockEntityTicker) blockEntity).tick(theWorld, pos, theState, blockEntity);
}
};
}
@Nullable
@Override
public BlockEntity newBlockEntity(BlockPos pos, BlockState state) {
return new CauldronBlockEntity(pos, state);
}
@Override
public void animateTick(BlockState state, Level world, BlockPos pos, RandomSource random) {
double blockX = (double) pos.getX() + 0.5;
double blockY = pos.getY() + 0.24;
double blockZ = (double) pos.getZ() + 0.5;
if (random.nextDouble() < 0.1)
world.playLocalSound(blockX, blockY, blockZ, SoundEvents.FURNACE_FIRE_CRACKLE, SoundSource.BLOCKS, 1.0f, 1.0f, false);
world.playLocalSound(blockX, blockY, blockZ, SoundEvents.SMOKER_SMOKE, SoundSource.BLOCKS, 1.0f, 1.0f, false);
world.playLocalSound(blockX, blockY, blockZ, SoundEvents.CAMPFIRE_CRACKLE, SoundSource.BLOCKS, 1.0f, 1.0f, false);
for (Direction direction : Direction.values()) {
if (direction != Direction.DOWN) {
double offsetX = random.nextDouble() * 0.6 - 0.3;
double offsetY = random.nextDouble() * 6.0 / 16.0;
double offsetZ = random.nextDouble() * 0.6 - 0.3;
double particleX = blockX + offsetX + 0.5 * direction.getStepX();
double particleY = blockY + offsetY;
double particleZ = blockZ + offsetZ + 0.5 * direction.getStepZ();
world.addParticle(ParticleTypes.SMOKE, particleX, particleY, particleZ, 0.0, 0.0, 0.0);
world.addParticle(ParticleTypes.SOUL_FIRE_FLAME, particleX, particleY, particleZ, 0.0, 0.0, 0.0);
if (random.nextDouble() < 0.6) {
double middleParticleX = blockX + offsetX + 0.5 * direction.getStepX() * random.nextDouble();
double middleParticleY = blockY + offsetY + 0.7 * random.nextDouble();
double middleParticleZ = blockZ + offsetZ + 0.5 * direction.getStepZ() * random.nextDouble();
world.addParticle(ParticleTypes.BUBBLE_POP, middleParticleX, middleParticleY, middleParticleZ, 0.0, 0.0, 0.0);
}
if (random.nextDouble() < 0.1) {
SimpleParticleType simpleParticleType = ParticleTypes.CAMPFIRE_COSY_SMOKE;
world.addAlwaysVisibleParticle(simpleParticleType, true, pos.getX() + 0.5 + random.nextDouble() / 3.0 * (random.nextBoolean() ? 1 : -1), pos.getY() + random.nextDouble() + random.nextDouble(), pos.getZ() + 0.5 + random.nextDouble() / 3.0 * (random.nextBoolean() ? 1 : -1), 0.0, 0.07, 0.0);
world.addParticle(ParticleTypes.SMOKE, pos.getX() + 0.5 + random.nextDouble() / 4.0 * (random.nextBoolean() ? 1 : -1), pos.getY() + 2.2, pos.getZ() + 0.5 + random.nextDouble() / 4.0 * (random.nextBoolean() ? 1 : -1), 0.0, 0.005, 0.0);
}
}
}
}
@Override
public void stepOn(Level world, BlockPos pos, BlockState state, Entity entity) {
if (!entity.fireImmune() && entity instanceof LivingEntity livingEntity &&
!EnchantmentHelper.hasFrostWalker(livingEntity)) {
entity.hurt(world.damageSources().hotFloor(), 1.f);
}
super.stepOn(world, pos, state, entity);
}
@Override
public void appendHoverText(ItemStack itemStack, BlockGetter world, List<Component> tooltip, TooltipFlag tooltipContext) {
tooltip.add(Component.translatable("tooltip.herbalbrews.cauldron").withStyle(ChatFormatting.WHITE));
tooltip.add(Component.empty());
tooltip.add(Component.translatable("tooltip.herbalbrews.canbeplaced").withStyle(ChatFormatting.ITALIC, ChatFormatting.GRAY));
}
private static final Supplier<VoxelShape> voxelShapeSupplier = () -> {
VoxelShape shape = Shapes.empty();
shape = Shapes.or(shape, Shapes.box(0, 0, 0, 0.125, 0.1875, 0.25));
shape = Shapes.or(shape, Shapes.box(0.125, 0, 0, 0.25, 0.1875, 0.125));
shape = Shapes.or(shape, Shapes.box(0.75, 0, 0, 1, 0.1875, 0.125));
shape = Shapes.or(shape, Shapes.box(0.875, 0, 0.125, 1, 0.1875, 0.25));
shape = Shapes.or(shape, Shapes.box(0.875, 0, 0.75, 1, 0.1875, 1));
shape = Shapes.or(shape, Shapes.box(0.75, 0, 0.875, 0.875, 0.1875, 1));
shape = Shapes.or(shape, Shapes.box(0, 0, 0.875, 0.25, 0.1875, 1));
shape = Shapes.or(shape, Shapes.box(0, 0, 0.75, 0.125, 0.1875, 0.875));
shape = Shapes.or(shape, Shapes.box(0, 0.1875, 0, 1, 0.6875, 1));
shape = Shapes.or(shape, Shapes.box(0.0625, 0.6875, 0.0625, 0.9375, 0.8125, 0.9375));
shape = Shapes.or(shape, Shapes.box(0, 0.8125, 0.8125, 1, 1, 1));
shape = Shapes.or(shape, Shapes.box(0, 0.8125, 0, 1, 1, 0.1875));
shape = Shapes.or(shape, Shapes.box(0, 0.8125, 0.1875, 0.1875, 1, 0.8125));
shape = Shapes.or(shape, Shapes.box(0.8125, 0.8125, 0.1875, 1, 1, 0.8125));
shape = Shapes.or(shape, Shapes.box(0.125, 0.0625, 0.125, 0.875, 0.25, 0.875));
shape = Shapes.or(shape, Shapes.box(0.0625, 0.000625, 0.0625, 0.9375, 0.063125, 0.9375));
shape = Shapes.or(shape, Shapes.box(0.1875, 0.0625, 0.6875, 0.8125, 0.1875, 0.8125));
shape = Shapes.or(shape, Shapes.box(0.1875, 0.0625, 0.4375, 0.8125, 0.1875, 0.5625));
shape = Shapes.or(shape, Shapes.box(0.1875, 0.0625, 0.1875, 0.8125, 0.1875, 0.3125));
return shape;
};
public static final Map<Direction, VoxelShape> SHAPE = Util.make(new HashMap<>(), map -> {
for (Direction direction : Direction.Plane.HORIZONTAL.stream().toList()) { | map.put(direction, GeneralUtil.rotateShape(Direction.NORTH, direction, voxelShapeSupplier.get())); | 1 | 2023-11-05 16:46:52+00:00 | 8k |
sizdshi/download-server | server/main/src/main/java/com/example/service/impl/DownloadServiceImpl.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.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.ErrorCode;
import com.example.constant.CommonConstant;
import com.example.model.dto.DownloadRequest;
import com.example.model.dto.ThreadRequest;
import com.example.model.entity.Download;
import com.example.model.vo.DownloadVO;
import com.example.utils.SqlUtils;
import com.example.exception.BusinessException;
import com.example.model.enums.DownloadStatus;
import com.example.service.DownloadService;
import com.example.mapper.DownloadMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.collections4.CollectionUtils;
| 4,367 | return resumeCount;
}
@Override
public long suspend(List<String> ids, HttpServletRequest request) {
if(!CollectionUtils.isNotEmpty(ids)){
throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"传入数组为空");
}
LambdaUpdateWrapper<Download> invokeLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
invokeLambdaUpdateWrapper.in(Download::getId,ids);
invokeLambdaUpdateWrapper.eq(Download::getIs_delete,0);
long count = downloadMapper.selectCount(invokeLambdaUpdateWrapper);
if(count<=0){
throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求数据不存在");
}
invokeLambdaUpdateWrapper.set(Download::getStatus,DownloadStatus.STATUS_PAUSED.getValue());
int updateCount = downloadMapper.update(new Download(),invokeLambdaUpdateWrapper);
// List<Download> up = downloadMapper.selectList(invokeLambdaUpdateWrapper);
if(updateCount<=0){
throw new BusinessException(ErrorCode.SYSTEM_ERROR,"download 暂停任务数失败 数据库异常");
}
return updateCount;
}
@Override
public long restart(List<String> ids, HttpServletRequest request) {
if(!CollectionUtils.isNotEmpty(ids)){
throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"传入数组为空");
}
LambdaUpdateWrapper<Download> resumeWrapper = new LambdaUpdateWrapper<>();
resumeWrapper.in(Download::getId,ids);
resumeWrapper.eq(Download::getIs_delete,0);
long count = downloadMapper.selectCount(resumeWrapper);
if(count<=0){
throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求文件不存在");
}
//todo 检查本地文件是否存在,存在则删除
resumeWrapper.set(Download::getStatus,DownloadStatus.STATUS_DOWNLOADING.getValue());
int resumeCount = downloadMapper.update(new Download(),resumeWrapper);
if(resumeCount<=0){
throw new BusinessException(ErrorCode.SYSTEM_ERROR,"download 重新下载任务数失败 数据库异常");
}
return resumeCount;
}
@Override
public long delete(List<String> ids) {
if(!CollectionUtils.isNotEmpty(ids)){
throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"传入数组为空");
}
LambdaUpdateWrapper<Download> invokeLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
invokeLambdaUpdateWrapper.in(Download::getId,ids);
long count = downloadMapper.selectCount(invokeLambdaUpdateWrapper);
if(count<=0){
throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求数据不存在");
}
invokeLambdaUpdateWrapper.set(Download::getStatus,DownloadStatus.STATUS_DELETE.getValue());
invokeLambdaUpdateWrapper.set(Download::getIs_delete,1);
int deleteCount = downloadMapper.update(new Download(),invokeLambdaUpdateWrapper);
System.out.println("删除成功");
if(deleteCount<=0){
throw new BusinessException(ErrorCode.SYSTEM_ERROR,"download 删除任务数失败 数据库异常");
}
return deleteCount;
}
@Override
public String submit(String url) {
if(!StringUtils.isNotEmpty(url)){
throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
}
String urlPattern = "^(http|https):\\/\\/(www\\.)?([a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*|\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})(:\\d+)?(\\/\\S*)?$";
if(!Pattern.matches(urlPattern,url)){
throw new BusinessException(ErrorCode.PARAMS_ERROR, "不合法的URL");
}
//todo 检查是否逻辑删除,如果是,改为否
LambdaUpdateWrapper<Download> invokeLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
invokeLambdaUpdateWrapper.eq(Download::getUrl,url);
long count = downloadMapper.selectCount(invokeLambdaUpdateWrapper);
if(count>0){
throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求文件已存在");
}
String fileName = url.substring(url.lastIndexOf('/') + 1);
Download download = new Download();
download.setUrl(url);
download.setTask_type("http");
download.setFile_name(fileName);
download.setUpdate_time(new Date());
download.setCreate_time(new Date());
download.setIs_delete(0);
//todo 文件大小在哪里处理
boolean saveResult = this.save(download);
if(!saveResult){
throw new BusinessException(ErrorCode.SYSTEM_ERROR,"download 提交任务失败 数据库异常");
}
return Long.toString(download.getId());
}
@Override
| package com.example.service.impl;
/**
* @author sizd-shi
* @description 针对表【download(上传下载表)】的数据库操作Service实现
* @createDate 2023-11-09 14:40:30
*/
@Service
@Slf4j
public class DownloadServiceImpl extends ServiceImpl<DownloadMapper, Download>
implements DownloadService {
@Resource
private DownloadMapper downloadMapper;
@Override
public long suspend(List<String> ids) {
if(!CollectionUtils.isNotEmpty(ids)){
throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"传入数组为空");
}
LambdaUpdateWrapper<Download> invokeLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
invokeLambdaUpdateWrapper.in(Download::getId,ids);
long count = downloadMapper.selectCount(invokeLambdaUpdateWrapper);
if(count<=0){
throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求数据不存在");
}
invokeLambdaUpdateWrapper.set(Download::getStatus,DownloadStatus.STATUS_PAUSED.getValue());
int updateCount = downloadMapper.update(new Download(),invokeLambdaUpdateWrapper);
List<Download> up = downloadMapper.selectList(invokeLambdaUpdateWrapper);
if(updateCount<=0){
throw new BusinessException(ErrorCode.SYSTEM_ERROR,"download 暂停任务数失败 数据库异常");
}
return up.get(1).getId();
}
@Override
public long changeThread(ThreadRequest threadRequest, HttpServletRequest request) {
if (!StringUtils.isNotEmpty(threadRequest.getId()) || !StringUtils.isNotEmpty(String.valueOf(threadRequest.getCount()))) {
throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
}
LambdaUpdateWrapper<Download> invokeLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
invokeLambdaUpdateWrapper.eq(Download::getId,Long.parseLong(threadRequest.getId()));
long count = downloadMapper.selectCount(invokeLambdaUpdateWrapper);
if(count<=0){
throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求文件不存在");
}
invokeLambdaUpdateWrapper.set(Download::getCount,threadRequest.getCount());
int changeThread = downloadMapper.update(new Download(),invokeLambdaUpdateWrapper);
if(changeThread<=0){
throw new BusinessException(ErrorCode.SYSTEM_ERROR,"修改任务数失败 数据库异常");
}
return changeThread;
}
@Override
public long start(List<String> ids,HttpServletRequest request) {
if(!CollectionUtils.isNotEmpty(ids)){
throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"传入数组为空");
}
LambdaUpdateWrapper<Download> invokeLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
invokeLambdaUpdateWrapper.in(Download::getId,ids);
long count = downloadMapper.selectCount(invokeLambdaUpdateWrapper);
if(count<=0){
throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求文件不存在");
}
invokeLambdaUpdateWrapper.set(Download::getStatus,DownloadStatus.STATUS_DOWNLOADING.getValue());
int resumeCount = downloadMapper.update(new Download(),invokeLambdaUpdateWrapper);
if(resumeCount<=0){
throw new BusinessException(ErrorCode.SYSTEM_ERROR,"download 开始下载任务数失败 数据库异常");
}
return resumeCount;
}
@Override
public long suspend(List<String> ids, HttpServletRequest request) {
if(!CollectionUtils.isNotEmpty(ids)){
throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"传入数组为空");
}
LambdaUpdateWrapper<Download> invokeLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
invokeLambdaUpdateWrapper.in(Download::getId,ids);
invokeLambdaUpdateWrapper.eq(Download::getIs_delete,0);
long count = downloadMapper.selectCount(invokeLambdaUpdateWrapper);
if(count<=0){
throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求数据不存在");
}
invokeLambdaUpdateWrapper.set(Download::getStatus,DownloadStatus.STATUS_PAUSED.getValue());
int updateCount = downloadMapper.update(new Download(),invokeLambdaUpdateWrapper);
// List<Download> up = downloadMapper.selectList(invokeLambdaUpdateWrapper);
if(updateCount<=0){
throw new BusinessException(ErrorCode.SYSTEM_ERROR,"download 暂停任务数失败 数据库异常");
}
return updateCount;
}
@Override
public long restart(List<String> ids, HttpServletRequest request) {
if(!CollectionUtils.isNotEmpty(ids)){
throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"传入数组为空");
}
LambdaUpdateWrapper<Download> resumeWrapper = new LambdaUpdateWrapper<>();
resumeWrapper.in(Download::getId,ids);
resumeWrapper.eq(Download::getIs_delete,0);
long count = downloadMapper.selectCount(resumeWrapper);
if(count<=0){
throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求文件不存在");
}
//todo 检查本地文件是否存在,存在则删除
resumeWrapper.set(Download::getStatus,DownloadStatus.STATUS_DOWNLOADING.getValue());
int resumeCount = downloadMapper.update(new Download(),resumeWrapper);
if(resumeCount<=0){
throw new BusinessException(ErrorCode.SYSTEM_ERROR,"download 重新下载任务数失败 数据库异常");
}
return resumeCount;
}
@Override
public long delete(List<String> ids) {
if(!CollectionUtils.isNotEmpty(ids)){
throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"传入数组为空");
}
LambdaUpdateWrapper<Download> invokeLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
invokeLambdaUpdateWrapper.in(Download::getId,ids);
long count = downloadMapper.selectCount(invokeLambdaUpdateWrapper);
if(count<=0){
throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求数据不存在");
}
invokeLambdaUpdateWrapper.set(Download::getStatus,DownloadStatus.STATUS_DELETE.getValue());
invokeLambdaUpdateWrapper.set(Download::getIs_delete,1);
int deleteCount = downloadMapper.update(new Download(),invokeLambdaUpdateWrapper);
System.out.println("删除成功");
if(deleteCount<=0){
throw new BusinessException(ErrorCode.SYSTEM_ERROR,"download 删除任务数失败 数据库异常");
}
return deleteCount;
}
@Override
public String submit(String url) {
if(!StringUtils.isNotEmpty(url)){
throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
}
String urlPattern = "^(http|https):\\/\\/(www\\.)?([a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*|\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})(:\\d+)?(\\/\\S*)?$";
if(!Pattern.matches(urlPattern,url)){
throw new BusinessException(ErrorCode.PARAMS_ERROR, "不合法的URL");
}
//todo 检查是否逻辑删除,如果是,改为否
LambdaUpdateWrapper<Download> invokeLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
invokeLambdaUpdateWrapper.eq(Download::getUrl,url);
long count = downloadMapper.selectCount(invokeLambdaUpdateWrapper);
if(count>0){
throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求文件已存在");
}
String fileName = url.substring(url.lastIndexOf('/') + 1);
Download download = new Download();
download.setUrl(url);
download.setTask_type("http");
download.setFile_name(fileName);
download.setUpdate_time(new Date());
download.setCreate_time(new Date());
download.setIs_delete(0);
//todo 文件大小在哪里处理
boolean saveResult = this.save(download);
if(!saveResult){
throw new BusinessException(ErrorCode.SYSTEM_ERROR,"download 提交任务失败 数据库异常");
}
return Long.toString(download.getId());
}
@Override
| public Page<DownloadVO> listDownloadVOByPage(DownloadRequest downloadRequest, HttpServletRequest request) {
| 5 | 2023-11-02 06:09:03+00:00 | 8k |
SatyaRajAwasth1/smart-credit-manager | src/main/java/np/com/satyarajawasthi/smartcreditmanager/manager/UserManager.java | [
{
"identifier": "ChangeCredentialsDialogController",
"path": "src/main/java/np/com/satyarajawasthi/smartcreditmanager/controller/ChangeCredentialsDialogController.java",
"snippet": "public class ChangeCredentialsDialogController {\n\n @FXML\n private TextField newUsernameField;\n\n @FXML\n p... | import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import np.com.satyarajawasthi.smartcreditmanager.controller.ChangeCredentialsDialogController;
import np.com.satyarajawasthi.smartcreditmanager.model.User;
import np.com.satyarajawasthi.smartcreditmanager.repository.CredentialRepository;
import np.com.satyarajawasthi.smartcreditmanager.repository.UserRepository;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import static np.com.satyarajawasthi.smartcreditmanager.util.DatabaseUtil.closeConnection;
import static np.com.satyarajawasthi.smartcreditmanager.util.DatabaseUtil.getConnection; | 4,537 | package np.com.satyarajawasthi.smartcreditmanager.manager;
public class UserManager {
private static final String CONFIG_URL = "/np/com/satyarajawasthi/smartcreditmanager/config.properties";
private static final Logger logger = Logger.getLogger(UserManager.class.getName());
public static boolean isFirstLogin() {
try {
// Check if it's the first login by reading from the properties file
if (isFirstLoginInPropertiesFile()) {
if (!UserRepository.isUserTableExists()) {
return true; // Table doesn't exist yet, consider it as the first login
}
int passwordUpdatedValue = UserRepository.getPasswordUpdatedValue();
return (passwordUpdatedValue == 0);
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
return false;
}
public static void onFirstLogin
() {
Connection connection = null;
try {
connection = getConnection();
connection.setAutoCommit(false); // Start a transaction
UserRepository.createUserTable(connection);
UserRepository.insertInitialUserRecords(connection);
UserRepository.restrictUserInsertion(connection);
CredentialRepository.createCredentialTable(connection);
connection.commit(); // Commit the transaction
logger.info("Users & credentials table created, default user inserted, and insertion restricted.");
} catch (SQLException e) {
if (connection != null) {
try {
connection.rollback(); // Rollback in case of an error
} catch (SQLException rollbackException) {
logger.log(Level.WARNING, "Error during rollback: {0}", rollbackException.getMessage());
} finally {
closeConnection();
}
}
logger.log(Level.SEVERE, "Error during database initialization: {0}", e.getMessage());
} finally {
closeConnection();
}
}
public static void showChangeCredentialsDialog() {
try {
FXMLLoader loader = new FXMLLoader(UserManager.class.getResource("/np/com/satyarajawasthi/smartcreditmanager/fxml/change_credentials_dialog.fxml"));
Parent root = loader.load();
Stage dialogStage = new Stage();
dialogStage.setTitle("Change Credentials");
dialogStage.initModality(Modality.APPLICATION_MODAL);
dialogStage.initStyle(StageStyle.UTILITY);
dialogStage.initOwner(null); // Set to null or the main stage if you have a reference to it.
Scene scene = new Scene(root);
dialogStage.setScene(scene);
ChangeCredentialsDialogController controller = loader.getController();
controller.setDialogStage(dialogStage);
// Show the dialog and wait for it to be closed
dialogStage.showAndWait();
} catch (IOException e) {
e.printStackTrace();
}
}
private static boolean isFirstLoginInPropertiesFile() {
try (InputStream input = UserRepository.class.getResourceAsStream(CONFIG_URL)) {
Properties properties = new Properties();
properties.load(input);
return Boolean.parseBoolean(properties.getProperty("isFirstLogin"));
} catch (IOException e) {
logger.log(Level.SEVERE, "Error reading from the properties file: {0}", e.getMessage());
}
return true;
}
public static void finalizeFirstLoginSetup() {
try (FileOutputStream output = new FileOutputStream(CONFIG_URL)) {
Properties properties = new Properties();
properties.setProperty("isFirstLogin", String.valueOf(false));
properties.store(output, null);
} catch (IOException e) {
logger.log(Level.SEVERE, "Error updating the properties file: {0}", e.getMessage());
}
// Call incrementPasswordUpdateCount from UserRepository
try {
UserRepository.markPasswordAsUpdated();
} catch (SQLException e) {
logger.log(Level.SEVERE, "Error incrementing password update count: {0}", e.getMessage());
}
}
| package np.com.satyarajawasthi.smartcreditmanager.manager;
public class UserManager {
private static final String CONFIG_URL = "/np/com/satyarajawasthi/smartcreditmanager/config.properties";
private static final Logger logger = Logger.getLogger(UserManager.class.getName());
public static boolean isFirstLogin() {
try {
// Check if it's the first login by reading from the properties file
if (isFirstLoginInPropertiesFile()) {
if (!UserRepository.isUserTableExists()) {
return true; // Table doesn't exist yet, consider it as the first login
}
int passwordUpdatedValue = UserRepository.getPasswordUpdatedValue();
return (passwordUpdatedValue == 0);
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
return false;
}
public static void onFirstLogin
() {
Connection connection = null;
try {
connection = getConnection();
connection.setAutoCommit(false); // Start a transaction
UserRepository.createUserTable(connection);
UserRepository.insertInitialUserRecords(connection);
UserRepository.restrictUserInsertion(connection);
CredentialRepository.createCredentialTable(connection);
connection.commit(); // Commit the transaction
logger.info("Users & credentials table created, default user inserted, and insertion restricted.");
} catch (SQLException e) {
if (connection != null) {
try {
connection.rollback(); // Rollback in case of an error
} catch (SQLException rollbackException) {
logger.log(Level.WARNING, "Error during rollback: {0}", rollbackException.getMessage());
} finally {
closeConnection();
}
}
logger.log(Level.SEVERE, "Error during database initialization: {0}", e.getMessage());
} finally {
closeConnection();
}
}
public static void showChangeCredentialsDialog() {
try {
FXMLLoader loader = new FXMLLoader(UserManager.class.getResource("/np/com/satyarajawasthi/smartcreditmanager/fxml/change_credentials_dialog.fxml"));
Parent root = loader.load();
Stage dialogStage = new Stage();
dialogStage.setTitle("Change Credentials");
dialogStage.initModality(Modality.APPLICATION_MODAL);
dialogStage.initStyle(StageStyle.UTILITY);
dialogStage.initOwner(null); // Set to null or the main stage if you have a reference to it.
Scene scene = new Scene(root);
dialogStage.setScene(scene);
ChangeCredentialsDialogController controller = loader.getController();
controller.setDialogStage(dialogStage);
// Show the dialog and wait for it to be closed
dialogStage.showAndWait();
} catch (IOException e) {
e.printStackTrace();
}
}
private static boolean isFirstLoginInPropertiesFile() {
try (InputStream input = UserRepository.class.getResourceAsStream(CONFIG_URL)) {
Properties properties = new Properties();
properties.load(input);
return Boolean.parseBoolean(properties.getProperty("isFirstLogin"));
} catch (IOException e) {
logger.log(Level.SEVERE, "Error reading from the properties file: {0}", e.getMessage());
}
return true;
}
public static void finalizeFirstLoginSetup() {
try (FileOutputStream output = new FileOutputStream(CONFIG_URL)) {
Properties properties = new Properties();
properties.setProperty("isFirstLogin", String.valueOf(false));
properties.store(output, null);
} catch (IOException e) {
logger.log(Level.SEVERE, "Error updating the properties file: {0}", e.getMessage());
}
// Call incrementPasswordUpdateCount from UserRepository
try {
UserRepository.markPasswordAsUpdated();
} catch (SQLException e) {
logger.log(Level.SEVERE, "Error incrementing password update count: {0}", e.getMessage());
}
}
| public static void changeDefaultUser(User updatedUser){ | 1 | 2023-11-05 03:53:02+00:00 | 8k |
wqj666666/embyboot | src/main/java/com/emby/boot/telegram/TelegramBot.java | [
{
"identifier": "MusicDownReq",
"path": "src/main/java/com/emby/boot/dto/req/MusicDownReq.java",
"snippet": "@Schema(description = \"muisc下载成员变量\")\n@Data\npublic class MusicDownReq {\n\n private String album;\n private String albumMid;\n private String extra;\n private String mid;\n priv... | import com.alibaba.fastjson.JSONObject;
import com.emby.boot.dto.req.MusicDownReq;
import com.emby.boot.dto.resp.EmbyUserInfoResp;
import com.emby.boot.dto.resp.MusicUserInfoResp;
import com.emby.boot.dto.resp.RestResp;
import com.emby.boot.service.EmbyUserService;
import com.emby.boot.service.MusicDownloaderService;
import com.emby.boot.service.MusicUserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.bots.DefaultBotOptions;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.methods.groupadministration.GetChatMember;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.chatmember.ChatMember;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; | 5,057 | Collections.addAll(rowList,deleteButtonRow);
InlineKeyboardMarkup inlineKeyboardMarkup = InlineKeyboardMarkup.builder().keyboard(rowList).build();
sendMessagesendMessage(chatId,messageBuilder,inlineKeyboardMarkup);
return;
}
//重置音乐服密码:/musicreset
if ("/musicreset".equals(update.getMessage().getText())){
try {
musicUserService.userPassword(String.valueOf(chatId));
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("音乐服重置成功,初始密码为用户名,建议修改密码");
sendMessage(chatId, messageBuilder);
return;
} catch (Exception e) {
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("音乐服重置失败");
messageBuilder.append(e.getMessage());
sendMessage(chatId, messageBuilder);
return;
}
}
//查看音乐服线路:/musicurl
if ("/musicurl".equals(update.getMessage().getText())){
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("音乐服地址:\n");
messageBuilder.append("chunmusic.imetyou.top (落地服务器线路) \n");
messageBuilder.append("cfmusic.imetyou.top (cf线路,可以加https访问))\n");
messageBuilder.append("music.imetyou.top (国内网盘线路)\n");
sendMessage(chatId, messageBuilder);
return;
}
//求片:/forum 片名 TMDB链接求片
if (update.getMessage().getText().startsWith("/forum ")){
String regex = "^/forum (.*?) https://www\\.themoviedb\\.org/.+";
String messageText= update.getMessage().getText();
//先判断求片是否符合规则
if (!messageText.matches(regex)){
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("求片格式不正确,请检查格式,然后重新求");
//发送消息
sendMessage(chatId,messageBuilder);
return;
}
String[] upText = messageText.split(" ");
//发送给管理员求片信息
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("#求片 \n");
messageBuilder.append("影片名:"+upText[1]+"\n");
messageBuilder.append("TMDB链接: \n");
messageBuilder.append(upText[2]+"\n");
messageBuilder.append("TGID:@"+update.getMessage().getFrom().getUserName());
//发送消息
sendMessage(Long.parseLong(adminId),messageBuilder);
//发送给用户反馈
StringBuilder usermMessageBuilder = new StringBuilder();
usermMessageBuilder.append("求片已经提交给管理员");
sendMessage(chatId,usermMessageBuilder);
return;
}
//反馈:/bug
if (update.getMessage().getText().startsWith("/bug ")){
String messageText= update.getMessage().getText();
String[] upText = messageText.split(" ");
//发送给管理员反馈信息
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("#反馈 \n");
messageBuilder.append(upText[1]+"\n");
messageBuilder.append("TGID:@"+update.getMessage().getFrom().getUserName());
//发送消息
sendMessage(Long.parseLong(adminId),messageBuilder);
//发送给用户反馈
StringBuilder usermMessageBuilder = new StringBuilder();
usermMessageBuilder.append("反馈已经提交给管理员,感谢反馈!");
sendMessage(chatId,usermMessageBuilder);
return;
}
//音乐下载搜索
if (update.getMessage().getText().startsWith("/musicsearch ")){
//创建搜索结果显示内联按钮
String keywords = update.getMessage().getText().replace("/musicsearch ", "").trim();
JSONObject search = musicDownloaderService.search(keywords,1,5);
int listSize = search.getJSONArray("list").size();
StringBuilder messageBuilder = new StringBuilder();
for (int i = 0; i < listSize; i++) {
String messageList=i+1+"."+" "+search.getJSONArray("list").getJSONObject(i).getString("readableText");
messageBuilder.append(messageList).append("\n");
}
messageBuilder.append("\n").append("现在是第 1 页数据");
List<List<InlineKeyboardButton>> rowList = new ArrayList<>();
Integer cur = search.getJSONObject("page").getInteger("cur");
//创建第一行按钮:确认搜索结果
List<InlineKeyboardButton> buttonRow1 = new ArrayList<>();
for (int i = 0; i < listSize; i++) {
InlineKeyboardButton button = InlineKeyboardButton.builder().text(String.valueOf(i+1)).callbackData("musicOk_"+i+"_"+search.getJSONObject("page").getInteger("cur")+"_"+keywords).build();
buttonRow1.add(button);
}
//创建第二行按钮:说明
List<InlineKeyboardButton> buttonRow2 = new ArrayList<>();
InlineKeyboardButton button2 = InlineKeyboardButton.builder().text("↑确认搜索结果, ↓下一页数据").callbackData("dummy_data").build();
buttonRow2.add(button2);
//创建第三行按钮:页码
List<InlineKeyboardButton> buttonRow3 = new ArrayList<>();
for (int i = 0; i < search.getJSONObject("page").getInteger("size")/5; i++) {
InlineKeyboardButton button3 = InlineKeyboardButton.builder().text(String.valueOf(i+1)).callbackData("musicSearch_"+(i+1)+"_"+keywords).build();
buttonRow3.add(button3);
}
// 现在,为键盘创建一个列表,并将buttonRow添加为其行
Collections.addAll(rowList,buttonRow1,buttonRow2,buttonRow3);
InlineKeyboardMarkup inlineKeyboardMarkup = InlineKeyboardMarkup.builder().keyboard(rowList).build();
//回复内联消息
sendMessagesendMessage(chatId,messageBuilder,inlineKeyboardMarkup);
}
//查询账号信息:/info
if ("/info".equals(update.getMessage().getText())){
try { | package com.emby.boot.telegram;
/**
* @author laojian
* @date 2023/8/27
*/
@Component
public class TelegramBot extends TelegramLongPollingBot {
private final EmbyUserService embyUserService;
private final MusicUserService musicUserService;
private final MusicDownloaderService musicDownloaderService;
//填你自己的token和username
@Value("${spring.telegrambot.config.token}")
private String token;
@Value("${spring.telegrambot.config.username}")
private String username;
@Value("${spring.telegrambot.config.groupChatId}")
private String groupChatId;
@Value("${spring.telegrambot.config.adminId}")
private String adminId;
//调用的时候初始化
public TelegramBot(DefaultBotOptions botOptions,EmbyUserService embyUserService,MusicUserService musicUserService,MusicDownloaderService musicDownloaderService) {
super(botOptions);
this.embyUserService = embyUserService;
this.musicUserService=musicUserService;
this.musicDownloaderService=musicDownloaderService;
}
/**
* 一对一的
* onUpdateReceived(Update update): 这个方法是当Telegram服务器向bot发送一个更新时调用的。
* Update是一个对象,包含了所有可能的信息,例如收到的消息、回调查询、新的聊天参与者等等。
* 大多数的单个交互,如接收消息或命令,会触发这个方法。
* @param update
*/
@Override
public void onUpdateReceived(Update update) {
// 判断是否是点击了内联菜单的按钮
if (update.hasCallbackQuery()){
Long chatId = update.getCallbackQuery().getFrom().getId();
// 获取回调数据
String callbackData = update.getCallbackQuery().getData();
//判断是否是删除emby的内联的按钮
if (callbackData.startsWith("embyDelete_")){
String[] parts = callbackData.split("_");
String embyDeleteText = parts[1];
if ("true".equals(embyDeleteText)){
//执行emby删除用户
try {
embyUserService.userDelete(String.valueOf(chatId));
// 处理BusinessException的代码
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("emby删除成功");
sendMessage(chatId, messageBuilder);
return;
} catch (Exception e) {
// 处理BusinessException的代码
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("emby删除失败:\n");
messageBuilder.append(e.getMessage());
sendMessage(chatId, messageBuilder);
return; }
}
}
//判断是否是删除音乐服的内联的按钮
if (callbackData.startsWith("musicDelete_")){
String[] parts = callbackData.split("_");
String embyDeleteText = parts[1];
if ("true".equals(embyDeleteText)){
//执行emby删除用户
try {
musicUserService.userDelete(String.valueOf(chatId));
// 处理BusinessException的代码
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("音乐服删除成功");
sendMessage(chatId, messageBuilder);
return;
} catch (Exception e) {
// 处理BusinessException的代码
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("音乐服删除失败:\n");
messageBuilder.append(e.getMessage());
sendMessage(chatId, messageBuilder);
return; }
}
}
//确认音乐下载结果
if (callbackData.startsWith("musicOk_")){
String[] parts = callbackData.split("_");
Integer num = Integer.valueOf(parts[1]);
Integer cur = Integer.valueOf(parts[2]);
String keywords = parts[3];
JSONObject jsonObject = musicDownloaderService.search(keywords, cur, 5).getJSONArray("list").getJSONObject(num);
MusicDownReq musicDownReq = new MusicDownReq();
musicDownReq.setReadableText(jsonObject.getString("readableText"));
musicDownReq.setSinger(jsonObject.getString("singer"));
musicDownReq.setTime_publish(jsonObject.getString("time_publish"));
musicDownReq.setAlbum(jsonObject.getString("album"));
musicDownReq.setPrefix(jsonObject.getString("prefix"));
musicDownReq.setSongmid(jsonObject.getString("songmid"));
musicDownReq.setAlbumMid(jsonObject.getString("albumMid"));
musicDownReq.setMid(jsonObject.getString("mid"));
musicDownReq.setTitle(jsonObject.getString("title"));
musicDownReq.setMusicid(jsonObject.getInteger("musicid"));
musicDownReq.setSize(jsonObject.getString("size"));
musicDownReq.setExtra(jsonObject.getString("extra"));
musicDownReq.setNotice(jsonObject.getString("notice"));
try {
musicDownloaderService.download(musicDownReq, String.valueOf(chatId));
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append(jsonObject.getString("readableText")+",下载成功,等待扫库");
//发送消息
sendMessage(chatId,messageBuilder);
return;
} catch (Exception e) {
// 处理BusinessException的代码
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("音乐下载失败:\n");
messageBuilder.append(e.getMessage()); // 假设BusinessException有getMessage方法返回错误信息
sendMessage(chatId, messageBuilder);
return;
}
}
//下一页搜索结果
if (callbackData.startsWith("musicSearch_")){
String[] parts = callbackData.split("_");
Integer cur = Integer.valueOf(parts[1]);
String keywords =parts[2];
JSONObject search = musicDownloaderService.search(keywords, cur, 5);
int listSize = search.getJSONArray("list").size();
StringBuilder messageBuilder = new StringBuilder();
for (int i = 0; i < listSize; i++) {
String messageList=i+1+"."+" "+search.getJSONArray("list").getJSONObject(i).getString("readableText");
messageBuilder.append(messageList).append("\n");
}
messageBuilder.append("\n").append("现在是第 "+cur+" 页数据");
List<List<InlineKeyboardButton>> rowList = new ArrayList<>();
//创建第一行按钮:确认搜索结果
List<InlineKeyboardButton> buttonRow1 = new ArrayList<>();
for (int i = 0; i < listSize; i++) {
InlineKeyboardButton button = InlineKeyboardButton.builder().text(String.valueOf(i+1)).callbackData("musicOk_"+i+"_"+search.getJSONObject("page").getInteger("cur")+"_"+keywords).build();
buttonRow1.add(button);
}
//创建第二行按钮:说明
List<InlineKeyboardButton> buttonRow2 = new ArrayList<>();
InlineKeyboardButton button2 = InlineKeyboardButton.builder().text("↑确认搜索结果, ↓下一页数据").callbackData("dummy_data").build();
buttonRow2.add(button2);
//创建第三行按钮:页码
List<InlineKeyboardButton> buttonRow3 = new ArrayList<>();
for (int i = 0; i < search.getJSONObject("page").getInteger("size")/5; i++) {
if (cur==i+1){
InlineKeyboardButton button3 = InlineKeyboardButton.builder().text(String.valueOf(i+1+"✅")).callbackData("musicSearch_"+(i+1)+"_"+keywords).build();
buttonRow3.add(button3);
}else {
InlineKeyboardButton button3 = InlineKeyboardButton.builder().text(String.valueOf(i+1)).callbackData("musicSearch_"+(i+1)+"_"+keywords).build();
buttonRow3.add(button3);
}
}
// 现在,为键盘创建一个列表,并将buttonRow添加为其行
Collections.addAll(rowList,buttonRow1,buttonRow2,buttonRow3);
InlineKeyboardMarkup inlineKeyboardMarkup = InlineKeyboardMarkup.builder().keyboard(rowList).build();
Integer messageId = update.getCallbackQuery().getMessage().getMessageId();
//编辑回复内联消息
editMessageText(chatId,messageId,messageBuilder,inlineKeyboardMarkup);
return;
}
return;
}
//电报用户id
Long chatId = update.getMessage().getChatId();
//先判断是否在群组或者频道
if (checkUserInTheGroup(chatId)){
//组装回复消息
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("你还未加入频道https://t.me/paulemby");
//发送消息
sendMessage(chatId,messageBuilder);
return;
}
// /help命令
if ("/help".equals(update.getMessage().getText())) {
//组装回复消息
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("chatid: " + chatId + "\n\n"); // 添加chatid信息
messageBuilder.append("创建emby账号:/create + 用户名\n");
messageBuilder.append("e.g:/create helloworld\n\n");
messageBuilder.append("重置emby密码:/reset\n");
messageBuilder.append("删除emby账户:/delete\n\n");
messageBuilder.append("创建音乐服账号:/musiccreate + 用户名\n");
messageBuilder.append("e.g:/musiccreate helloworld\n\n");
messageBuilder.append("重置音乐服密码:/musicreset\n");
messageBuilder.append("删除音乐服账户: /musicdelete\n\n");
messageBuilder.append("查看emby线路:/embyurl\n");
messageBuilder.append("查看音乐服线路:/musicurl\n");
messageBuilder.append("求片:/forum 片名 TMDB链接求片\n");
messageBuilder.append("e.g:/forum 你的名字 https://www.themoviedb.org/movie/372058\n\n");
messageBuilder.append("反馈:/bug\n");
messageBuilder.append("e.g:/bug 你的名字缺少字幕\n\n");
messageBuilder.append("音乐服添加音乐:/musicsearch 关键字\n");
messageBuilder.append("e.g:/musicsearch 你好\n\n");
messageBuilder.append("查询账号信息:/info\n");
//发送消息
sendMessage(chatId, messageBuilder);
return;
}
// 创建emby账号:/create + 用户名
if (update.getMessage().getText().startsWith("/create ")){
//创建emby账户
String username = update.getMessage().getText().replace("/create ", "").trim();
//先判断用户名是否符合规则
if (!username.matches("^[a-zA-Z0-9]+$")){
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("emby注册的用户只能是数字或者英文,或者两个组合");
//发送消息
sendMessage(chatId,messageBuilder);
return;
}
try {
embyUserService.userNew(username,String.valueOf(chatId));
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("emby注册成功,初始密码为空,登录不需要输入,建议修改密码\n");
messageBuilder.append("Emby用户名:"+username);
//发送消息
sendMessage(chatId,messageBuilder);
return;
} catch (Exception e) {
// 处理BusinessException的代码
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("emby注册失败:\n");
messageBuilder.append(e.getMessage()); // 假设BusinessException有getMessage方法返回错误信息
sendMessage(chatId, messageBuilder);
return;
}
}
//删除emby账户:/delete
if ("/delete".equals(update.getMessage().getText())){
//创建删除emby确定按钮
List<List<InlineKeyboardButton>> rowList = new ArrayList<>();
// 现在,为键盘创建一个列表,并将buttonRow添加为其行,第四个按钮
List<InlineKeyboardButton> deleteButtonRow = new ArrayList<>();
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("请确认是否删除emby用户");
InlineKeyboardButton buttonA = InlineKeyboardButton.builder().text("是").callbackData("embyDelete_true").build();
InlineKeyboardButton buttonB = InlineKeyboardButton.builder().text("否").callbackData("embyDelete_false").build();
deleteButtonRow.add(buttonA);
deleteButtonRow.add(buttonB);
Collections.addAll(rowList,deleteButtonRow);
InlineKeyboardMarkup inlineKeyboardMarkup = InlineKeyboardMarkup.builder().keyboard(rowList).build();
sendMessagesendMessage(chatId,messageBuilder,inlineKeyboardMarkup);
return;
}
//重置emby密码:/reset
if ("/reset".equals(update.getMessage().getText())){
try {
embyUserService.userPassword(String.valueOf(chatId));
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("emby重置成功,初始密码为空,登录不需要输入,建议修改密码");
sendMessage(chatId, messageBuilder);
return;
} catch (Exception e) {
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("emby重置失败");
messageBuilder.append(e.getMessage());
sendMessage(chatId, messageBuilder);
return;
}
}
//查看emby线路:/embyurl
if ("/embyurl".equals(update.getMessage().getText())){
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("emby服地址:\n");
messageBuilder.append("http://cf.imetyou.top (cf线路,可以加https访问)\n");
messageBuilder.append("http://emby.imetyou.top:8096 (随机线路)\n");
messageBuilder.append("http://fk.imetyou.top:8096 (落地机线路)\n");
messageBuilder.append("http://kr.imetyou.top:22333 (首尔中转)\n");
messageBuilder.append("http://sg.imetyou.top:22333 (新加坡中转)\n");
messageBuilder.append("http://chun.imetyou.top:22333 (春川中转)\n");
sendMessage(chatId, messageBuilder);
return;
}
//创建音乐服账号:/musiccreate + 用户名
if (update.getMessage().getText().startsWith("/musiccreate ")){
//创建emby账户
String username = update.getMessage().getText().replace("/musiccreate ", "").trim();
//先判断用户名是否符合规则
if (!username.matches("^[a-zA-Z0-9]+$")){
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("音乐服的注册的用户只能是数字或者英文,或者两个组合");
//发送消息
sendMessage(chatId,messageBuilder);
return;
}
try {
musicUserService.userNew(username,String.valueOf(chatId));
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("音乐服成功,初始密码为用户名,建议修改密码\n");
messageBuilder.append("音乐服用户名:"+username);
//发送消息
sendMessage(chatId,messageBuilder);
return;
} catch (Exception e) {
// 处理BusinessException的代码
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("音乐服注册失败:\n");
messageBuilder.append(e.getMessage()); // 假设BusinessException有getMessage方法返回错误信息
sendMessage(chatId, messageBuilder);
return;
}
}
//删除音乐服账户: /musicdelete
if ("/musicdelete".equals(update.getMessage().getText())){
//创建删除音乐服确定按钮
List<List<InlineKeyboardButton>> rowList = new ArrayList<>();
// 现在,为键盘创建一个列表,并将buttonRow添加为其行
List<InlineKeyboardButton> deleteButtonRow = new ArrayList<>();
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("请确认是否删除音乐服用户");
InlineKeyboardButton buttonA = InlineKeyboardButton.builder().text("是").callbackData("musicDelete_true").build();
InlineKeyboardButton buttonB = InlineKeyboardButton.builder().text("否").callbackData("musicDelete_false").build();
deleteButtonRow.add(buttonA);
deleteButtonRow.add(buttonB);
Collections.addAll(rowList,deleteButtonRow);
InlineKeyboardMarkup inlineKeyboardMarkup = InlineKeyboardMarkup.builder().keyboard(rowList).build();
sendMessagesendMessage(chatId,messageBuilder,inlineKeyboardMarkup);
return;
}
//重置音乐服密码:/musicreset
if ("/musicreset".equals(update.getMessage().getText())){
try {
musicUserService.userPassword(String.valueOf(chatId));
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("音乐服重置成功,初始密码为用户名,建议修改密码");
sendMessage(chatId, messageBuilder);
return;
} catch (Exception e) {
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("音乐服重置失败");
messageBuilder.append(e.getMessage());
sendMessage(chatId, messageBuilder);
return;
}
}
//查看音乐服线路:/musicurl
if ("/musicurl".equals(update.getMessage().getText())){
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("音乐服地址:\n");
messageBuilder.append("chunmusic.imetyou.top (落地服务器线路) \n");
messageBuilder.append("cfmusic.imetyou.top (cf线路,可以加https访问))\n");
messageBuilder.append("music.imetyou.top (国内网盘线路)\n");
sendMessage(chatId, messageBuilder);
return;
}
//求片:/forum 片名 TMDB链接求片
if (update.getMessage().getText().startsWith("/forum ")){
String regex = "^/forum (.*?) https://www\\.themoviedb\\.org/.+";
String messageText= update.getMessage().getText();
//先判断求片是否符合规则
if (!messageText.matches(regex)){
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("求片格式不正确,请检查格式,然后重新求");
//发送消息
sendMessage(chatId,messageBuilder);
return;
}
String[] upText = messageText.split(" ");
//发送给管理员求片信息
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("#求片 \n");
messageBuilder.append("影片名:"+upText[1]+"\n");
messageBuilder.append("TMDB链接: \n");
messageBuilder.append(upText[2]+"\n");
messageBuilder.append("TGID:@"+update.getMessage().getFrom().getUserName());
//发送消息
sendMessage(Long.parseLong(adminId),messageBuilder);
//发送给用户反馈
StringBuilder usermMessageBuilder = new StringBuilder();
usermMessageBuilder.append("求片已经提交给管理员");
sendMessage(chatId,usermMessageBuilder);
return;
}
//反馈:/bug
if (update.getMessage().getText().startsWith("/bug ")){
String messageText= update.getMessage().getText();
String[] upText = messageText.split(" ");
//发送给管理员反馈信息
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("#反馈 \n");
messageBuilder.append(upText[1]+"\n");
messageBuilder.append("TGID:@"+update.getMessage().getFrom().getUserName());
//发送消息
sendMessage(Long.parseLong(adminId),messageBuilder);
//发送给用户反馈
StringBuilder usermMessageBuilder = new StringBuilder();
usermMessageBuilder.append("反馈已经提交给管理员,感谢反馈!");
sendMessage(chatId,usermMessageBuilder);
return;
}
//音乐下载搜索
if (update.getMessage().getText().startsWith("/musicsearch ")){
//创建搜索结果显示内联按钮
String keywords = update.getMessage().getText().replace("/musicsearch ", "").trim();
JSONObject search = musicDownloaderService.search(keywords,1,5);
int listSize = search.getJSONArray("list").size();
StringBuilder messageBuilder = new StringBuilder();
for (int i = 0; i < listSize; i++) {
String messageList=i+1+"."+" "+search.getJSONArray("list").getJSONObject(i).getString("readableText");
messageBuilder.append(messageList).append("\n");
}
messageBuilder.append("\n").append("现在是第 1 页数据");
List<List<InlineKeyboardButton>> rowList = new ArrayList<>();
Integer cur = search.getJSONObject("page").getInteger("cur");
//创建第一行按钮:确认搜索结果
List<InlineKeyboardButton> buttonRow1 = new ArrayList<>();
for (int i = 0; i < listSize; i++) {
InlineKeyboardButton button = InlineKeyboardButton.builder().text(String.valueOf(i+1)).callbackData("musicOk_"+i+"_"+search.getJSONObject("page").getInteger("cur")+"_"+keywords).build();
buttonRow1.add(button);
}
//创建第二行按钮:说明
List<InlineKeyboardButton> buttonRow2 = new ArrayList<>();
InlineKeyboardButton button2 = InlineKeyboardButton.builder().text("↑确认搜索结果, ↓下一页数据").callbackData("dummy_data").build();
buttonRow2.add(button2);
//创建第三行按钮:页码
List<InlineKeyboardButton> buttonRow3 = new ArrayList<>();
for (int i = 0; i < search.getJSONObject("page").getInteger("size")/5; i++) {
InlineKeyboardButton button3 = InlineKeyboardButton.builder().text(String.valueOf(i+1)).callbackData("musicSearch_"+(i+1)+"_"+keywords).build();
buttonRow3.add(button3);
}
// 现在,为键盘创建一个列表,并将buttonRow添加为其行
Collections.addAll(rowList,buttonRow1,buttonRow2,buttonRow3);
InlineKeyboardMarkup inlineKeyboardMarkup = InlineKeyboardMarkup.builder().keyboard(rowList).build();
//回复内联消息
sendMessagesendMessage(chatId,messageBuilder,inlineKeyboardMarkup);
}
//查询账号信息:/info
if ("/info".equals(update.getMessage().getText())){
try { | RestResp<EmbyUserInfoResp> userEmbyInfo = embyUserService.userInfo(String.valueOf(chatId)); | 1 | 2023-11-09 17:15:57+00:00 | 8k |
AnhyDev/AnhyLingo | src/main/java/ink/anh/lingo/AnhyLingo.java | [
{
"identifier": "LingoCommand",
"path": "src/main/java/ink/anh/lingo/command/LingoCommand.java",
"snippet": "public class LingoCommand implements CommandExecutor {\n\t\n\tprivate AnhyLingo lingoPlugin;\n private GlobalManager globalManager;\n\n /**\n * Constructor for the LingoCommand class.\n... | import org.bukkit.Bukkit;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import ink.anh.api.messages.Logger;
import ink.anh.lingo.command.LingoCommand;
import ink.anh.lingo.listeners.ListenerManager;
import ink.anh.lingo.listeners.protocol.PacketListenerManager; | 3,645 | package ink.anh.lingo;
/**
* Main class for the AnhyLingo plugin.
* This class handles the initialization, enabling, and disabling of the plugin.
* It also provides utility methods to check the server type and version.
*/
public class AnhyLingo extends JavaPlugin {
private static AnhyLingo instance;
private boolean isSpigot;
private boolean isPaper;
private boolean isFolia;
private boolean hasPaperComponent;
private GlobalManager globalManager;
/**
* Called when the plugin is loaded by the Bukkit system.
* Sets the static instance for global access.
*/
@Override
public void onLoad() {
instance = this;
}
/**
* Called when the plugin is enabled.
* Performs initial setup such as checking dependencies, determining server type,
* initializing managers, and setting up commands and listeners.
*/
@Override
public void onEnable() {
checkDepends("ProtocolLib");
checkServer();
globalManager = GlobalManager.getManager(this); | package ink.anh.lingo;
/**
* Main class for the AnhyLingo plugin.
* This class handles the initialization, enabling, and disabling of the plugin.
* It also provides utility methods to check the server type and version.
*/
public class AnhyLingo extends JavaPlugin {
private static AnhyLingo instance;
private boolean isSpigot;
private boolean isPaper;
private boolean isFolia;
private boolean hasPaperComponent;
private GlobalManager globalManager;
/**
* Called when the plugin is loaded by the Bukkit system.
* Sets the static instance for global access.
*/
@Override
public void onLoad() {
instance = this;
}
/**
* Called when the plugin is enabled.
* Performs initial setup such as checking dependencies, determining server type,
* initializing managers, and setting up commands and listeners.
*/
@Override
public void onEnable() {
checkDepends("ProtocolLib");
checkServer();
globalManager = GlobalManager.getManager(this); | new PacketListenerManager().addListeners(); | 2 | 2023-11-10 00:35:39+00:00 | 8k |
Oselan/ExcelUtils | src/main/java/com/oselan/sample/UserService.java | [
{
"identifier": "ConflictException",
"path": "src/main/java/com/oselan/commons/exceptions/ConflictException.java",
"snippet": "public class ConflictException extends BaseException {\n\tprivate static final long serialVersionUID = -8596472890741536409L;\n \n private static final String DEFAULT_ERROR_COD... | import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.oselan.commons.exceptions.ConflictException;
import com.oselan.excelexporter.ColumnDefinition;
import com.oselan.excelexporter.ExcelExporter;
import lombok.extern.slf4j.Slf4j; | 5,214 | package com.oselan.sample;
@Service
@Slf4j
public class UserService {
@Autowired
private UserRepository userRepository;
@Async
// @SneakyThrows(InterruptedException.class)
public void generateReport(OutputStream stream) throws ConflictException, IOException {
log.info("Generating report ... "); | package com.oselan.sample;
@Service
@Slf4j
public class UserService {
@Autowired
private UserRepository userRepository;
@Async
// @SneakyThrows(InterruptedException.class)
public void generateReport(OutputStream stream) throws ConflictException, IOException {
log.info("Generating report ... "); | List<ColumnDefinition> columnsDef = ColumnDefinition.listBuilder() | 1 | 2023-11-03 20:17:51+00:00 | 8k |
BaderTim/minecraft-measurement-mod | src/main/java/io/github/mmm/measurement/device/objects/lidar/LiDARController.java | [
{
"identifier": "SubLiDARPipeline",
"path": "src/main/java/io/github/mmm/measurement/device/objects/lidar/multithread/SubLiDARPipeline.java",
"snippet": "public class SubLiDARPipeline implements Runnable {\n\n private final LiDAR[] subLidars;\n private volatile LidarScan[] scans;\n\n public Sub... | import io.github.mmm.measurement.device.objects.lidar.multithread.SubLiDARPipeline;
import io.github.mmm.measurement.device.scans.LidarScan;
import io.github.mmm.measurement.device.scans.LidarScan2D;
import io.github.mmm.measurement.device.scans.LidarScan3D;
import io.github.mmm.modconfig.Config;
import java.util.ArrayList;
import static io.github.mmm.MMM.DEVICE_CONTROLLER; | 6,398 | package io.github.mmm.measurement.device.objects.lidar;
public class LiDARController {
private final LiDAR[] lidars;
private ArrayList<LidarScan>[] scans;
private int maxThreadCount;
private int passedTicks;
public LiDARController(LiDAR[] lidars) {
if (Config.MULTITHREAD_SWITCH.get()) {
this.maxThreadCount = Config.THREAD_COUNT_MULTIPLIER.get() * Runtime.getRuntime().availableProcessors();
} else {
this.maxThreadCount = 1;
}
this.lidars = lidars;
this.scans = new ArrayList[this.lidars.length];
for(int i = 0; i < this.lidars.length; i++) {
this.scans[i] = new ArrayList<>();
}
}
public ArrayList<LidarScan>[] getScans() {
return this.scans;
}
public void clearScans() {
this.scans = new ArrayList[this.lidars.length];
for(int i = 0; i < this.lidars.length; i++) {
this.scans[i] = new ArrayList<>();
}
}
public void scan() {
this.passedTicks = 0;
this.executeScan();
}
public void scan(int passedTicks) {
this.passedTicks = passedTicks;
this.executeScan();
}
private void executeScan() {
LidarScan[] currentScans;
if(this.maxThreadCount == 1) {
currentScans = this.getScansSingleThreaded();
} else {
currentScans = this.getScansMultiThreaded();
}
for(int i = 0; i < currentScans.length; i++) {
this.scans[i].add(currentScans[i]);
}
}
private LidarScan[] getScansSingleThreaded() {
LidarScan[] scans = new LidarScan[this.lidars.length];
for (int i = 0; i < this.lidars.length; i++) {
if(this.isLidarAllowedToScan(this.lidars[i])) {
scans[i] = this.lidars[i].performScan();
} else {
scans[i] = null;
}
}
return scans;
}
private LidarScan[] getScansMultiThreaded() {
int[] subLidarsPerLidar = new int[this.lidars.length];
ArrayList<LiDAR> subLidars = new ArrayList<>();
// slice main lidars into sublidars
for(int l = 0; l < this.lidars.length; l++) {
LiDAR lidar = this.lidars[l];
if(!this.isLidarAllowedToScan(lidar)) continue;
ArrayList<LiDAR> newSubLidars;
if(lidar.getVerticalScanRadiusInDeg() == 0) { // 2D
newSubLidars = this.getSubLidarsFrom2DLidar(lidar);
} else { // 3D
newSubLidars = this.getSubLidarsFrom3DLidar(lidar);
}
subLidarsPerLidar[l] = newSubLidars.size();
subLidars.addAll(newSubLidars);
}
int threadCount = Math.min(this.maxThreadCount, subLidars.size());
int subLidarsPerThread = (int)Math.ceil((double)subLidars.size() / threadCount);
// create threads | package io.github.mmm.measurement.device.objects.lidar;
public class LiDARController {
private final LiDAR[] lidars;
private ArrayList<LidarScan>[] scans;
private int maxThreadCount;
private int passedTicks;
public LiDARController(LiDAR[] lidars) {
if (Config.MULTITHREAD_SWITCH.get()) {
this.maxThreadCount = Config.THREAD_COUNT_MULTIPLIER.get() * Runtime.getRuntime().availableProcessors();
} else {
this.maxThreadCount = 1;
}
this.lidars = lidars;
this.scans = new ArrayList[this.lidars.length];
for(int i = 0; i < this.lidars.length; i++) {
this.scans[i] = new ArrayList<>();
}
}
public ArrayList<LidarScan>[] getScans() {
return this.scans;
}
public void clearScans() {
this.scans = new ArrayList[this.lidars.length];
for(int i = 0; i < this.lidars.length; i++) {
this.scans[i] = new ArrayList<>();
}
}
public void scan() {
this.passedTicks = 0;
this.executeScan();
}
public void scan(int passedTicks) {
this.passedTicks = passedTicks;
this.executeScan();
}
private void executeScan() {
LidarScan[] currentScans;
if(this.maxThreadCount == 1) {
currentScans = this.getScansSingleThreaded();
} else {
currentScans = this.getScansMultiThreaded();
}
for(int i = 0; i < currentScans.length; i++) {
this.scans[i].add(currentScans[i]);
}
}
private LidarScan[] getScansSingleThreaded() {
LidarScan[] scans = new LidarScan[this.lidars.length];
for (int i = 0; i < this.lidars.length; i++) {
if(this.isLidarAllowedToScan(this.lidars[i])) {
scans[i] = this.lidars[i].performScan();
} else {
scans[i] = null;
}
}
return scans;
}
private LidarScan[] getScansMultiThreaded() {
int[] subLidarsPerLidar = new int[this.lidars.length];
ArrayList<LiDAR> subLidars = new ArrayList<>();
// slice main lidars into sublidars
for(int l = 0; l < this.lidars.length; l++) {
LiDAR lidar = this.lidars[l];
if(!this.isLidarAllowedToScan(lidar)) continue;
ArrayList<LiDAR> newSubLidars;
if(lidar.getVerticalScanRadiusInDeg() == 0) { // 2D
newSubLidars = this.getSubLidarsFrom2DLidar(lidar);
} else { // 3D
newSubLidars = this.getSubLidarsFrom3DLidar(lidar);
}
subLidarsPerLidar[l] = newSubLidars.size();
subLidars.addAll(newSubLidars);
}
int threadCount = Math.min(this.maxThreadCount, subLidars.size());
int subLidarsPerThread = (int)Math.ceil((double)subLidars.size() / threadCount);
// create threads | SubLiDARPipeline[] pipelines = new SubLiDARPipeline[threadCount]; | 0 | 2023-11-06 16:56:46+00:00 | 8k |
KilianCollins/road-runner-quickstart-master | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/opmode/ManualFeedforwardTuner.java | [
{
"identifier": "MAX_ACCEL",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java",
"snippet": "public static double MAX_ACCEL = 73.17330064499293;"
},
{
"identifier": "MAX_VEL",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveCon... | import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ACCEL;
import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_VEL;
import static org.firstinspires.ftc.teamcode.drive.DriveConstants.RUN_USING_ENCODER;
import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kA;
import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kStatic;
import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kV;
import com.acmerobotics.dashboard.FtcDashboard;
import com.acmerobotics.dashboard.config.Config;
import com.acmerobotics.dashboard.telemetry.MultipleTelemetry;
import com.acmerobotics.roadrunner.geometry.Pose2d;
import com.acmerobotics.roadrunner.kinematics.Kinematics;
import com.acmerobotics.roadrunner.profile.MotionProfile;
import com.acmerobotics.roadrunner.profile.MotionProfileGenerator;
import com.acmerobotics.roadrunner.profile.MotionState;
import com.acmerobotics.roadrunner.util.NanoClock;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.VoltageSensor;
import com.qualcomm.robotcore.util.RobotLog;
import org.firstinspires.ftc.robotcore.external.Telemetry;
import org.firstinspires.ftc.teamcode.drive.SampleMecanumDrive;
import java.util.Objects; | 3,813 | package org.firstinspires.ftc.teamcode.drive.opmode;
/*
* This routine is designed to tune the open-loop feedforward coefficients. Although it may seem unnecessary,
* tuning these coefficients is just as important as the positional parameters. Like the other
* manual tuning routines, this op mode relies heavily upon the dashboard. To access the dashboard,
* connect your computer to the RC's WiFi network. In your browser, navigate to
* https://192.168.49.1:8080/dash if you're using the RC phone or https://192.168.43.1:8080/dash if
* you are using the Control Hub. Once you've successfully connected, start the program, and your
* robot will begin moving forward and backward according to a motion profile. Your job is to graph
* the velocity errors over time and adjust the feedforward coefficients. Once you've found a
* satisfactory set of gains, add them to the appropriate fields in the DriveConstants.java file.
*
* Pressing Y/Δ (Xbox/PS4) will pause the tuning process and enter driver override, allowing the
* user to reset the position of the bot in the event that it drifts off the path.
* Pressing B/O (Xbox/PS4) will cede control back to the tuning process.
*/
@Config
@Autonomous(group = "drive")
public class ManualFeedforwardTuner extends LinearOpMode {
public static double DISTANCE = 72; // in
private FtcDashboard dashboard = FtcDashboard.getInstance();
private SampleMecanumDrive drive;
enum Mode {
DRIVER_MODE,
TUNING_MODE
}
private Mode mode;
private static MotionProfile generateProfile(boolean movingForward) {
MotionState start = new MotionState(movingForward ? 0 : DISTANCE, 0, 0, 0);
MotionState goal = new MotionState(movingForward ? DISTANCE : 0, 0, 0, 0);
return MotionProfileGenerator.generateSimpleMotionProfile(start, goal, MAX_VEL, MAX_ACCEL);
}
@Override
public void runOpMode() {
if (RUN_USING_ENCODER) {
RobotLog.setGlobalErrorMsg("Feedforward constants usually don't need to be tuned " +
"when using the built-in drive motor velocity PID.");
}
Telemetry telemetry = new MultipleTelemetry(this.telemetry, dashboard.getTelemetry());
drive = new SampleMecanumDrive(hardwareMap);
final VoltageSensor voltageSensor = hardwareMap.voltageSensor.iterator().next();
mode = Mode.TUNING_MODE;
NanoClock clock = NanoClock.system();
telemetry.addLine("Ready!");
telemetry.update();
telemetry.clearAll();
waitForStart();
if (isStopRequested()) return;
boolean movingForwards = true;
MotionProfile activeProfile = generateProfile(true);
double profileStart = clock.seconds();
while (!isStopRequested()) {
telemetry.addData("mode", mode);
switch (mode) {
case TUNING_MODE:
if (gamepad1.y) {
mode = Mode.DRIVER_MODE;
}
// calculate and set the motor power
double profileTime = clock.seconds() - profileStart;
if (profileTime > activeProfile.duration()) {
// generate a new profile
movingForwards = !movingForwards;
activeProfile = generateProfile(movingForwards);
profileStart = clock.seconds();
}
MotionState motionState = activeProfile.get(profileTime); | package org.firstinspires.ftc.teamcode.drive.opmode;
/*
* This routine is designed to tune the open-loop feedforward coefficients. Although it may seem unnecessary,
* tuning these coefficients is just as important as the positional parameters. Like the other
* manual tuning routines, this op mode relies heavily upon the dashboard. To access the dashboard,
* connect your computer to the RC's WiFi network. In your browser, navigate to
* https://192.168.49.1:8080/dash if you're using the RC phone or https://192.168.43.1:8080/dash if
* you are using the Control Hub. Once you've successfully connected, start the program, and your
* robot will begin moving forward and backward according to a motion profile. Your job is to graph
* the velocity errors over time and adjust the feedforward coefficients. Once you've found a
* satisfactory set of gains, add them to the appropriate fields in the DriveConstants.java file.
*
* Pressing Y/Δ (Xbox/PS4) will pause the tuning process and enter driver override, allowing the
* user to reset the position of the bot in the event that it drifts off the path.
* Pressing B/O (Xbox/PS4) will cede control back to the tuning process.
*/
@Config
@Autonomous(group = "drive")
public class ManualFeedforwardTuner extends LinearOpMode {
public static double DISTANCE = 72; // in
private FtcDashboard dashboard = FtcDashboard.getInstance();
private SampleMecanumDrive drive;
enum Mode {
DRIVER_MODE,
TUNING_MODE
}
private Mode mode;
private static MotionProfile generateProfile(boolean movingForward) {
MotionState start = new MotionState(movingForward ? 0 : DISTANCE, 0, 0, 0);
MotionState goal = new MotionState(movingForward ? DISTANCE : 0, 0, 0, 0);
return MotionProfileGenerator.generateSimpleMotionProfile(start, goal, MAX_VEL, MAX_ACCEL);
}
@Override
public void runOpMode() {
if (RUN_USING_ENCODER) {
RobotLog.setGlobalErrorMsg("Feedforward constants usually don't need to be tuned " +
"when using the built-in drive motor velocity PID.");
}
Telemetry telemetry = new MultipleTelemetry(this.telemetry, dashboard.getTelemetry());
drive = new SampleMecanumDrive(hardwareMap);
final VoltageSensor voltageSensor = hardwareMap.voltageSensor.iterator().next();
mode = Mode.TUNING_MODE;
NanoClock clock = NanoClock.system();
telemetry.addLine("Ready!");
telemetry.update();
telemetry.clearAll();
waitForStart();
if (isStopRequested()) return;
boolean movingForwards = true;
MotionProfile activeProfile = generateProfile(true);
double profileStart = clock.seconds();
while (!isStopRequested()) {
telemetry.addData("mode", mode);
switch (mode) {
case TUNING_MODE:
if (gamepad1.y) {
mode = Mode.DRIVER_MODE;
}
// calculate and set the motor power
double profileTime = clock.seconds() - profileStart;
if (profileTime > activeProfile.duration()) {
// generate a new profile
movingForwards = !movingForwards;
activeProfile = generateProfile(movingForwards);
profileStart = clock.seconds();
}
MotionState motionState = activeProfile.get(profileTime); | double targetPower = Kinematics.calculateMotorFeedforward(motionState.getV(), motionState.getA(), kV, kA, kStatic); | 3 | 2023-11-04 04:11:26+00:00 | 8k |
InfantinoAndrea00/polimi-software-engineering-project-2022 | src/main/java/it/polimi/ingsw/server/Server.java | [
{
"identifier": "ViewObserver",
"path": "src/main/java/it/polimi/ingsw/server/controller/ViewObserver.java",
"snippet": "public class ViewObserver {\n private GameController gameController;\n private int counter;\n private boolean canAddPlayer;\n private CharacterCardHandler characterCardHan... | import it.polimi.ingsw.server.controller.ViewObserver;
import it.polimi.ingsw.server.model.Game;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.atomic.AtomicBoolean; | 4,535 | package it.polimi.ingsw.server;
public class Server {
public static final int PORT = 5555; | package it.polimi.ingsw.server;
public class Server {
public static final int PORT = 5555; | public static ViewObserver viewObserver; | 0 | 2023-11-06 00:50:18+00:00 | 8k |
conductor-oss/conductor | amqp/src/test/java/com/netflix/conductor/contribs/queue/amqp/AMQPEventQueueProviderTest.java | [
{
"identifier": "AMQPEventQueueProperties",
"path": "amqp/src/main/java/com/netflix/conductor/contribs/queue/amqp/config/AMQPEventQueueProperties.java",
"snippet": "@ConfigurationProperties(\"conductor.event-queues.amqp\")\npublic class AMQPEventQueueProperties {\n\n private int batchSize = 1;\n\n ... | import java.time.Duration;
import org.junit.Before;
import org.junit.Test;
import com.netflix.conductor.contribs.queue.amqp.config.AMQPEventQueueProperties;
import com.netflix.conductor.contribs.queue.amqp.config.AMQPEventQueueProvider;
import com.netflix.conductor.contribs.queue.amqp.util.AMQPConstants;
import com.netflix.conductor.core.events.queue.ObservableQueue;
import com.rabbitmq.client.AMQP.PROTOCOL;
import com.rabbitmq.client.ConnectionFactory;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; | 4,241 | /*
* Copyright 2023 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.contribs.queue.amqp;
public class AMQPEventQueueProviderTest {
private AMQPEventQueueProperties properties;
@Before
public void setUp() {
properties = mock(AMQPEventQueueProperties.class);
when(properties.getBatchSize()).thenReturn(1);
when(properties.getPollTimeDuration()).thenReturn(Duration.ofMillis(100));
when(properties.getHosts()).thenReturn(ConnectionFactory.DEFAULT_HOST);
when(properties.getUsername()).thenReturn(ConnectionFactory.DEFAULT_USER);
when(properties.getPassword()).thenReturn(ConnectionFactory.DEFAULT_PASS);
when(properties.getVirtualHost()).thenReturn(ConnectionFactory.DEFAULT_VHOST);
when(properties.getPort()).thenReturn(PROTOCOL.PORT);
when(properties.getConnectionTimeoutInMilliSecs()).thenReturn(60000);
when(properties.isUseNio()).thenReturn(false);
when(properties.isDurable()).thenReturn(true);
when(properties.isExclusive()).thenReturn(false);
when(properties.isAutoDelete()).thenReturn(false);
when(properties.getContentType()).thenReturn("application/json");
when(properties.getContentEncoding()).thenReturn("UTF-8");
when(properties.getExchangeType()).thenReturn("topic");
when(properties.getDeliveryMode()).thenReturn(2);
when(properties.isUseExchange()).thenReturn(true);
}
@Test
public void testAMQPEventQueueProvider_defaultconfig_exchange() {
String exchangestring =
"amqp_exchange:myExchangeName?exchangeType=topic&routingKey=test&deliveryMode=2";
AMQPEventQueueProvider eventqProvider =
new AMQPEventQueueProvider(properties, "amqp_exchange", true);
ObservableQueue queue = eventqProvider.getQueue(exchangestring);
assertNotNull(queue);
assertEquals(exchangestring, queue.getName()); | /*
* Copyright 2023 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.contribs.queue.amqp;
public class AMQPEventQueueProviderTest {
private AMQPEventQueueProperties properties;
@Before
public void setUp() {
properties = mock(AMQPEventQueueProperties.class);
when(properties.getBatchSize()).thenReturn(1);
when(properties.getPollTimeDuration()).thenReturn(Duration.ofMillis(100));
when(properties.getHosts()).thenReturn(ConnectionFactory.DEFAULT_HOST);
when(properties.getUsername()).thenReturn(ConnectionFactory.DEFAULT_USER);
when(properties.getPassword()).thenReturn(ConnectionFactory.DEFAULT_PASS);
when(properties.getVirtualHost()).thenReturn(ConnectionFactory.DEFAULT_VHOST);
when(properties.getPort()).thenReturn(PROTOCOL.PORT);
when(properties.getConnectionTimeoutInMilliSecs()).thenReturn(60000);
when(properties.isUseNio()).thenReturn(false);
when(properties.isDurable()).thenReturn(true);
when(properties.isExclusive()).thenReturn(false);
when(properties.isAutoDelete()).thenReturn(false);
when(properties.getContentType()).thenReturn("application/json");
when(properties.getContentEncoding()).thenReturn("UTF-8");
when(properties.getExchangeType()).thenReturn("topic");
when(properties.getDeliveryMode()).thenReturn(2);
when(properties.isUseExchange()).thenReturn(true);
}
@Test
public void testAMQPEventQueueProvider_defaultconfig_exchange() {
String exchangestring =
"amqp_exchange:myExchangeName?exchangeType=topic&routingKey=test&deliveryMode=2";
AMQPEventQueueProvider eventqProvider =
new AMQPEventQueueProvider(properties, "amqp_exchange", true);
ObservableQueue queue = eventqProvider.getQueue(exchangestring);
assertNotNull(queue);
assertEquals(exchangestring, queue.getName()); | assertEquals(AMQPConstants.AMQP_EXCHANGE_TYPE, queue.getType()); | 2 | 2023-12-08 06:06:09+00:00 | 8k |
10cks/fofaEX | src/main/java/plugins/CommonTemplate.java | [
{
"identifier": "RightClickFunctions",
"path": "src/main/java/tableInit/RightClickFunctions.java",
"snippet": "public class RightClickFunctions {\n // 在类的成员变量中创建弹出菜单\n public static JPopupMenu popupMenu = new JPopupMenu();\n private static JMenuItem itemSelectColumn = new JMenuItem(\"选择当前整列\");... | import com.google.gson.*;
import com.google.gson.stream.JsonReader;
import org.json.JSONArray;
import org.json.JSONObject;
import tableInit.RightClickFunctions;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.*;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicBoolean;
import static java.awt.BorderLayout.CENTER;
import static tableInit.GetjTableHeader.adjustColumnWidths;
import static tableInit.GetjTableHeader.getjTableHeader;
import static tableInit.RightClickFunctions.popupMenu; | 4,470 | // 用与保存 table 数据
private static JScrollPane findScrollPane(Container container) {
for (Component comp : container.getComponents()) {
if (comp instanceof JScrollPane) {
return (JScrollPane) comp;
} else if (comp instanceof Container) {
JScrollPane scrollPane = findScrollPane((Container) comp);
if (scrollPane != null) {
return scrollPane;
}
}
}
return null;
}
// 动态创建子菜单,核心代码
public static void addMenuItemsFromFile(JMenu pluginMenu, JTabbedPane tabbedPane) {
EventQueue.invokeLater(() -> {
Path file = Paths.get(allPluginsPath + "AllPlugins.json");
if (!Files.exists(file)) { // 如果不存在这个文件,则新建这个文件
try {
Files.createDirectories(file.getParent());
Files.createFile(file);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
// Create a new Gson
Gson gson = new Gson();
if (Files.size(file) == 0) {
System.out.println("[!] 当前无第三方插件");
return;
}
// Read the JSON from the file into a Map
Map<String, Boolean> plugins = gson.fromJson(
new FileReader(file.toFile()), Map.class);
// Process each plugin
for (Map.Entry<String, Boolean> plugin : plugins.entrySet()) {
// Only process plugins that are enabled
if (plugin.getValue()) {
// 检查对应的插件的文件夹和json文件是否都存在
String pluginFolderPath = allPluginsPath + plugin.getKey();
String pluginJsonPath = pluginFolderPath + "/" + plugin.getKey() + "Setting.json";
if (!Files.exists(Paths.get(pluginFolderPath))) {
System.out.println("[-] 当前插件 " + plugin.getKey() + " 缺失文件夹:" + pluginFolderPath);
continue;
}
if (!Files.exists(Paths.get(pluginJsonPath))) {
System.out.println("[-] 当前插件 " + plugin.getKey() + " 缺失文件:" + pluginJsonPath);
continue;
}
// 创建插件的菜单项
JMenu submenu = new JMenu(plugin.getKey());
System.out.println("[+] 当前插件 " + plugin.getKey() + " 已加载");
// 为插件添加"运行"、"设置"、"关于"三个选项
JMenuItem runItem = new JMenuItem("运行");
JMenuItem settingItem = new JMenuItem("设置");
JMenuItem aboutItem = new JMenuItem("关于");
// 对菜单项添加相应的事件处理器
runItem.addActionListener(event -> {
addPluginFrame(pluginJsonPath, plugin.getKey(), tabbedPane); // 弹出运行面板
});
settingItem.addActionListener(event -> {
// 这里添加设置的事件处理代码
addPluginsSettingOpen(pluginJsonPath);
});
aboutItem.addActionListener(event -> {
// 这里添加关于的事件处理代码
addPluginAbout(pluginJsonPath);
});
// 把菜单项添加到子菜单中
submenu.add(runItem);
submenu.add(settingItem);
submenu.add(aboutItem);
// 把子菜单添加到主菜单中
pluginMenu.add(submenu);
}
}
} catch (IOException e) {
e.printStackTrace();
}
});
}
// 点击运行新增 tab 页
public static void addPluginTab(JTabbedPane tabbedPane, String pluginName, String pluginJsonPath) {
// 检查标签是否已经存在
if (tabbedPane.indexOfTab(pluginName) != -1) {
int existingTabIndex = tabbedPane.indexOfTab(pluginName);
tabbedPane.removeTabAt(existingTabIndex);
}
//ActionListener在选择“关闭”时关闭标签页
ActionListener closeListener = event -> tabbedPane.removeTabAt(tabbedPane.indexOfTab(pluginName));
// 创建表格
JTable table = createTableFromJson(pluginJsonPath);
// 清理可能已经添加的菜单项
// 初始化 table 右键
RightClickFunctions.table = table;
RightClickFunctions.initializeTable();
// 重新设置表格头,以便新的渲染器生效
JTableHeader header = getjTableHeader(table);
table.setTableHeader(header);
// 自动调整列宽 | package plugins;
public class CommonTemplate {
private static String pluginName = "";
private static String allPluginsPath = "./plugins/";
private static Process runningProcess = null;
static AtomicBoolean wasManuallyStopped = new AtomicBoolean(false);
public static JLabel addBanner(String banner) {
JLabel labelIcon = new JLabel(banner);
labelIcon.setForeground(new Color(48, 49, 52));
Font iconFont = new Font("Times New Roman", Font.BOLD, 60);
labelIcon.setFont(iconFont);
return labelIcon;
}
// 保存 table 核心代码到对应 json 文件中
public static void saveTableData(JTabbedPane tabbedPane) {
EventQueue.invokeLater(() -> {
// 检查或创建coredata文件夹
File directory = new File("coredata");
if (!directory.exists()) {
directory.mkdir();
}
// 获取当前选中的标签索引
int selectedIndex = tabbedPane.getSelectedIndex();
if (selectedIndex == -1) {
// 如果没有选中的标签,不执行任何操作
return;
}
// 获取当前选中的标签的标题
String tabName = tabbedPane.getTitleAt(selectedIndex);
// 获取选中的标签对应的组件
Component selectedComponent = tabbedPane.getComponentAt(selectedIndex);
if (!(selectedComponent instanceof JPanel)) {
System.err.println("The selected component is not a JPanel.");
return;
}
JPanel panel = (JPanel) selectedComponent;
// 查找JScrollPane组件
JScrollPane scrollPane = findScrollPane(panel);
if (scrollPane == null) {
System.err.println("No JScrollPane found in the selected tab.");
return;
}
// 获取JTable
JTable table = (JTable) scrollPane.getViewport().getView();
// 转换表格数据为JSON
JSONArray jsonArray = new JSONArray();
for (int row = 0; row < table.getRowCount(); row++) {
JSONObject rowJson = new JSONObject();
for (int col = 0; col < table.getColumnCount(); col++) {
rowJson.put(table.getColumnName(col), table.getValueAt(row, col));
}
jsonArray.put(rowJson);
}
// 写入JSON文件
String filename = "coredata/" + tabName + ".json";
try (FileWriter file = new FileWriter(filename)) {
file.write(jsonArray.toString(4)); // 缩进为4个空格
System.out.println("[+] Successfully saved JSON data to " + filename);
} catch (IOException e) {
e.printStackTrace();
}
});
}
// 用与保存 table 数据
private static JScrollPane findScrollPane(Container container) {
for (Component comp : container.getComponents()) {
if (comp instanceof JScrollPane) {
return (JScrollPane) comp;
} else if (comp instanceof Container) {
JScrollPane scrollPane = findScrollPane((Container) comp);
if (scrollPane != null) {
return scrollPane;
}
}
}
return null;
}
// 动态创建子菜单,核心代码
public static void addMenuItemsFromFile(JMenu pluginMenu, JTabbedPane tabbedPane) {
EventQueue.invokeLater(() -> {
Path file = Paths.get(allPluginsPath + "AllPlugins.json");
if (!Files.exists(file)) { // 如果不存在这个文件,则新建这个文件
try {
Files.createDirectories(file.getParent());
Files.createFile(file);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
// Create a new Gson
Gson gson = new Gson();
if (Files.size(file) == 0) {
System.out.println("[!] 当前无第三方插件");
return;
}
// Read the JSON from the file into a Map
Map<String, Boolean> plugins = gson.fromJson(
new FileReader(file.toFile()), Map.class);
// Process each plugin
for (Map.Entry<String, Boolean> plugin : plugins.entrySet()) {
// Only process plugins that are enabled
if (plugin.getValue()) {
// 检查对应的插件的文件夹和json文件是否都存在
String pluginFolderPath = allPluginsPath + plugin.getKey();
String pluginJsonPath = pluginFolderPath + "/" + plugin.getKey() + "Setting.json";
if (!Files.exists(Paths.get(pluginFolderPath))) {
System.out.println("[-] 当前插件 " + plugin.getKey() + " 缺失文件夹:" + pluginFolderPath);
continue;
}
if (!Files.exists(Paths.get(pluginJsonPath))) {
System.out.println("[-] 当前插件 " + plugin.getKey() + " 缺失文件:" + pluginJsonPath);
continue;
}
// 创建插件的菜单项
JMenu submenu = new JMenu(plugin.getKey());
System.out.println("[+] 当前插件 " + plugin.getKey() + " 已加载");
// 为插件添加"运行"、"设置"、"关于"三个选项
JMenuItem runItem = new JMenuItem("运行");
JMenuItem settingItem = new JMenuItem("设置");
JMenuItem aboutItem = new JMenuItem("关于");
// 对菜单项添加相应的事件处理器
runItem.addActionListener(event -> {
addPluginFrame(pluginJsonPath, plugin.getKey(), tabbedPane); // 弹出运行面板
});
settingItem.addActionListener(event -> {
// 这里添加设置的事件处理代码
addPluginsSettingOpen(pluginJsonPath);
});
aboutItem.addActionListener(event -> {
// 这里添加关于的事件处理代码
addPluginAbout(pluginJsonPath);
});
// 把菜单项添加到子菜单中
submenu.add(runItem);
submenu.add(settingItem);
submenu.add(aboutItem);
// 把子菜单添加到主菜单中
pluginMenu.add(submenu);
}
}
} catch (IOException e) {
e.printStackTrace();
}
});
}
// 点击运行新增 tab 页
public static void addPluginTab(JTabbedPane tabbedPane, String pluginName, String pluginJsonPath) {
// 检查标签是否已经存在
if (tabbedPane.indexOfTab(pluginName) != -1) {
int existingTabIndex = tabbedPane.indexOfTab(pluginName);
tabbedPane.removeTabAt(existingTabIndex);
}
//ActionListener在选择“关闭”时关闭标签页
ActionListener closeListener = event -> tabbedPane.removeTabAt(tabbedPane.indexOfTab(pluginName));
// 创建表格
JTable table = createTableFromJson(pluginJsonPath);
// 清理可能已经添加的菜单项
// 初始化 table 右键
RightClickFunctions.table = table;
RightClickFunctions.initializeTable();
// 重新设置表格头,以便新的渲染器生效
JTableHeader header = getjTableHeader(table);
table.setTableHeader(header);
// 自动调整列宽 | adjustColumnWidths(table); | 1 | 2023-12-07 13:46:27+00:00 | 8k |
specmock/specmock | specmock/src/test/java/io/specmock/core/SpringWebTest.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.List;
import java.util.Map;
import java.util.Objects;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.module.kotlin.KotlinModule;
import com.linecorp.armeria.client.WebClient;
import io.specmock.core.example.Example1Request;
import io.specmock.core.example.Example1Response;
import io.specmock.core.example.Example2Response;
import io.specmock.core.example.Example3Request;
import io.specmock.core.example.Example3Response;
import io.specmock.core.example.Example4Request;
import io.specmock.core.example.Example4Response;
import io.specmock.core.example.Example5Request;
import io.specmock.core.example.Example5Response;
import io.specmock.core.example.Example6Request;
import io.specmock.core.example.Example6Response;
import io.specmock.core.example.Example7Request;
import io.specmock.core.example.Example7Response;
import io.specmock.core.example.Example8Response;
import io.specmock.core.example.ExampleApi; | 5,618 | /*
* 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 SpringWebTest {
private static final String RESPONSE_VALUE = "SUCCESS";
private final ObjectMapper mapper = new ObjectMapper().registerModule(new KotlinModule.Builder().build());
private final WebClient webClient = WebClient.of("http://localhost:18080");
private HttpSpecServer specServer;
private Example1Request example1Request;
private Example3Request example3Request;
private Example4Request example4Request;
private Example5Request example5Request;
private Example6Request example6Request;
private Example7Request example7Request;
@BeforeEach
void setUp() {
example1Request = new Example1Request("EXAMPLE1", 10, 10L, BigDecimal.TEN);
example3Request = new Example3Request("EXAMPLE3", 10, 10L, BigDecimal.TEN);
example4Request = new Example4Request("EXAMPLE4", 10, 10L, BigDecimal.TEN);
example5Request = new Example5Request("EXAMPLE5", 10, 10L, BigDecimal.TEN);
example6Request = new Example6Request("EXAMPLE6", 10, 10L, BigDecimal.TEN);
example7Request = new Example7Request("EXAMPLE7", 10, 10L, BigDecimal.TEN);
final List<HttpSpec> specs = HttpSpec.springWebBuilder() | /*
* 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 SpringWebTest {
private static final String RESPONSE_VALUE = "SUCCESS";
private final ObjectMapper mapper = new ObjectMapper().registerModule(new KotlinModule.Builder().build());
private final WebClient webClient = WebClient.of("http://localhost:18080");
private HttpSpecServer specServer;
private Example1Request example1Request;
private Example3Request example3Request;
private Example4Request example4Request;
private Example5Request example5Request;
private Example6Request example6Request;
private Example7Request example7Request;
@BeforeEach
void setUp() {
example1Request = new Example1Request("EXAMPLE1", 10, 10L, BigDecimal.TEN);
example3Request = new Example3Request("EXAMPLE3", 10, 10L, BigDecimal.TEN);
example4Request = new Example4Request("EXAMPLE4", 10, 10L, BigDecimal.TEN);
example5Request = new Example5Request("EXAMPLE5", 10, 10L, BigDecimal.TEN);
example6Request = new Example6Request("EXAMPLE6", 10, 10L, BigDecimal.TEN);
example7Request = new Example7Request("EXAMPLE7", 10, 10L, BigDecimal.TEN);
final List<HttpSpec> specs = HttpSpec.springWebBuilder() | .springWebBind(ExampleApi.class) | 14 | 2023-12-13 10:43:07+00:00 | 8k |
kaifangqian/open-sign | src/main/java/com/resrun/service/pdf/CalculatePositionService.java | [
{
"identifier": "RealPositionProperty",
"path": "src/main/java/com/resrun/service/pojo/RealPositionProperty.java",
"snippet": "@AllArgsConstructor\n@NoArgsConstructor\n@Data\npublic class RealPositionProperty implements Serializable {\n\n\n private static final long serialVersionUID = 85869844096... | import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfReader;
import com.resrun.service.pojo.RealPositionProperty;
import com.resrun.service.pojo.SelectKeywords;
import com.resrun.service.pojo.SourcePositionProperty;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List; | 4,515 | package com.resrun.service.pdf;
/**
* @Description: 计算签署位置业务
* @Package: com.resrun.service.pdf
* @ClassName: CalculatePositionService
* @copyright 北京资源律动科技有限公司
*/
@Service
public class CalculatePositionService {
/**
* @Description #批量计算真实签署位置
* @Param [sourcePositionProperties]
* @return java.util.List<com.resrun.modules.sign.service.tool.pojo.RealPositionProperty>
**/
public List<RealPositionProperty> calculatePositions(List<SourcePositionProperty> sourcePositionProperties, byte[] pdfFileByte){
List<RealPositionProperty> realPositionProperties = new ArrayList<>();
PdfReader reader = null ;
try {
//将pdf文件读入PdfReader工具类
reader = new PdfReader(pdfFileByte);
for(SourcePositionProperty sourcePositionProperty : sourcePositionProperties){
RealPositionProperty realPositionProperty = calculatePosition(sourcePositionProperty,pdfFileByte);
Document document = new Document(reader.getPageSize(sourcePositionProperty.getPage()));
//获取真实pdf文件指定页的真实文档宽高
float realPdfHeight = document.getPageSize().getHeight();
float realPdfWidth = document.getPageSize().getWidth();
//获取页面上文档的宽高
float sourcePageWidth = sourcePositionProperty.getPageWidth();
float sourcePageHeight = sourcePositionProperty.getPageHeight();
//计算真实文档的宽高和页面文档的宽高的比率
float rateHeight = realPdfHeight / sourcePageHeight;
float rateWidth = realPdfWidth / sourcePageWidth;
//计算页面上的横纵坐标,由于页面上给出的是左上角的坐标,所以需要再转换计算一下
//左下角
float pageStartX = sourcePositionProperty.getOffsetX();
float pageStartY = sourcePositionProperty.getOffsetY() + sourcePositionProperty.getHeight() ;
//右上角
float pageEndX = sourcePositionProperty.getOffsetX() + sourcePositionProperty.getWidth();
float pageEndY = sourcePositionProperty.getOffsetY();
//根据比率去计算真实文档上的坐标位置
float startX = pageStartX * rateWidth ;
float startY = pageStartY * rateHeight;
float endX = pageEndX * rateWidth ;
float endY = pageEndY * rateHeight ;
//由于页面的纵坐标和pdf的纵坐标是相反的,所以真实的pdf的纵坐标在计算的时候需要再反转一下
startY = realPdfHeight - startY ;
endY = realPdfHeight - endY ;
//封装返回数据
realPositionProperty.setStartx(startX);
realPositionProperty.setStarty(startY);
realPositionProperty.setEndx(endX);
realPositionProperty.setEndy(endY);
realPositionProperty.setPageNum(sourcePositionProperty.getPage());
document.close();
realPositionProperties.add(realPositionProperty);
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return realPositionProperties ;
}
/**
* @Description #单独计算真实签署位置
* @Param [sourcePositionProperty]
* @return com.resrun.modules.sign.service.tool.pojo.RealPositionProperty
**/
public RealPositionProperty calculatePosition(SourcePositionProperty sourcePositionProperty, byte[] pdfFileByte){
RealPositionProperty realPositionProperty = new RealPositionProperty();
PdfReader reader = null ;
Document document = null ;
try {
//将pdf文件读入PdfReader工具类
reader = new PdfReader(pdfFileByte);
document = new Document(reader.getPageSize(sourcePositionProperty.getPage()));
//获取真实pdf文件指定页的真实文档宽高
float realPdfHeight = document.getPageSize().getHeight();
float realPdfWidth = document.getPageSize().getWidth();
//获取页面上文档的宽高
float sourcePageWidth = sourcePositionProperty.getPageWidth();
float sourcePageHeight = sourcePositionProperty.getPageHeight();
//计算真实文档的宽高和页面文档的宽高的比率
float rateHeight = realPdfHeight / sourcePageHeight;
float rateWidth = realPdfWidth / sourcePageWidth;
//计算页面上的横纵坐标,由于页面上给出的是左上角的坐标,所以需要再转换计算一下
//左下角
float pageStartX = sourcePositionProperty.getOffsetX();
float pageStartY = sourcePositionProperty.getOffsetY() + sourcePositionProperty.getHeight() ;
//右上角
float pageEndX = sourcePositionProperty.getOffsetX() + sourcePositionProperty.getWidth();
float pageEndY = sourcePositionProperty.getOffsetY();
//根据比率去计算真实文档上的坐标位置
float startX = pageStartX * rateWidth ;
float startY = pageStartY * rateHeight;
float endX = pageEndX * rateWidth ;
float endY = pageEndY * rateHeight ;
//由于页面的纵坐标和pdf的纵坐标是相反的,所以真实的pdf的纵坐标在计算的时候需要再反转一下
startY = realPdfHeight - startY ;
endY = realPdfHeight - endY ;
//封装返回数据
realPositionProperty.setStartx(startX);
realPositionProperty.setStarty(startY);
realPositionProperty.setEndx(endX);
realPositionProperty.setEndy(endY);
realPositionProperty.setPageNum(sourcePositionProperty.getPage());
document.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return realPositionProperty ;
}
public RealPositionProperty calculatePosition(SourcePositionProperty sourcePositionProperty){
RealPositionProperty realPositionProperty = new RealPositionProperty();
//获取真实pdf文件指定页的真实文档宽高
float realPdfHeight = sourcePositionProperty.getRealHeight();
float realPdfWidth = sourcePositionProperty.getRealWidth();
//获取页面上文档的宽高
float sourcePageWidth = sourcePositionProperty.getPageWidth();
float sourcePageHeight = sourcePositionProperty.getPageHeight();
//计算真实文档的宽高和页面文档的宽高的比率
float rateHeight = realPdfHeight / sourcePageHeight;
float rateWidth = realPdfWidth / sourcePageWidth;
//计算页面上的横纵坐标,由于页面上给出的是左上角的坐标,所以需要再转换计算一下
//左下角
float pageStartX = sourcePositionProperty.getOffsetX();
float pageStartY = sourcePositionProperty.getOffsetY() + sourcePositionProperty.getHeight() ;
//右上角
float pageEndX = sourcePositionProperty.getOffsetX() + sourcePositionProperty.getWidth();
float pageEndY = sourcePositionProperty.getOffsetY();
//根据比率去计算真实文档上的坐标位置
float startX = pageStartX * rateWidth ;
float startY = pageStartY * rateHeight;
float endX = pageEndX * rateWidth ;
float endY = pageEndY * rateHeight ;
//由于页面的纵坐标和pdf的纵坐标是相反的,所以真实的pdf的纵坐标在计算的时候需要再反转一下
startY = realPdfHeight - startY ;
endY = realPdfHeight - endY ;
//封装返回数据
realPositionProperty.setStartx(startX);
realPositionProperty.setStarty(startY);
realPositionProperty.setEndx(endX);
realPositionProperty.setEndy(endY);
realPositionProperty.setPageNum(sourcePositionProperty.getPage());
return realPositionProperty ;
}
/**
* 通过查询关键字来获得签名位置信息
* @param pdfFile 签署源文件
* @param keyWords 关键字
* @param width 签章宽度
* @param height 签章高度
* @return 签署位置信息
* @throws IOException
*/
public RealPositionProperty getPositionByKeyWords(byte[] pdfFile, String keyWords, int width, int height) {
RealPositionProperty positionProperty = new RealPositionProperty();
//调用通过关键字查询位置的方法
float[] result = new float[0];
try { | package com.resrun.service.pdf;
/**
* @Description: 计算签署位置业务
* @Package: com.resrun.service.pdf
* @ClassName: CalculatePositionService
* @copyright 北京资源律动科技有限公司
*/
@Service
public class CalculatePositionService {
/**
* @Description #批量计算真实签署位置
* @Param [sourcePositionProperties]
* @return java.util.List<com.resrun.modules.sign.service.tool.pojo.RealPositionProperty>
**/
public List<RealPositionProperty> calculatePositions(List<SourcePositionProperty> sourcePositionProperties, byte[] pdfFileByte){
List<RealPositionProperty> realPositionProperties = new ArrayList<>();
PdfReader reader = null ;
try {
//将pdf文件读入PdfReader工具类
reader = new PdfReader(pdfFileByte);
for(SourcePositionProperty sourcePositionProperty : sourcePositionProperties){
RealPositionProperty realPositionProperty = calculatePosition(sourcePositionProperty,pdfFileByte);
Document document = new Document(reader.getPageSize(sourcePositionProperty.getPage()));
//获取真实pdf文件指定页的真实文档宽高
float realPdfHeight = document.getPageSize().getHeight();
float realPdfWidth = document.getPageSize().getWidth();
//获取页面上文档的宽高
float sourcePageWidth = sourcePositionProperty.getPageWidth();
float sourcePageHeight = sourcePositionProperty.getPageHeight();
//计算真实文档的宽高和页面文档的宽高的比率
float rateHeight = realPdfHeight / sourcePageHeight;
float rateWidth = realPdfWidth / sourcePageWidth;
//计算页面上的横纵坐标,由于页面上给出的是左上角的坐标,所以需要再转换计算一下
//左下角
float pageStartX = sourcePositionProperty.getOffsetX();
float pageStartY = sourcePositionProperty.getOffsetY() + sourcePositionProperty.getHeight() ;
//右上角
float pageEndX = sourcePositionProperty.getOffsetX() + sourcePositionProperty.getWidth();
float pageEndY = sourcePositionProperty.getOffsetY();
//根据比率去计算真实文档上的坐标位置
float startX = pageStartX * rateWidth ;
float startY = pageStartY * rateHeight;
float endX = pageEndX * rateWidth ;
float endY = pageEndY * rateHeight ;
//由于页面的纵坐标和pdf的纵坐标是相反的,所以真实的pdf的纵坐标在计算的时候需要再反转一下
startY = realPdfHeight - startY ;
endY = realPdfHeight - endY ;
//封装返回数据
realPositionProperty.setStartx(startX);
realPositionProperty.setStarty(startY);
realPositionProperty.setEndx(endX);
realPositionProperty.setEndy(endY);
realPositionProperty.setPageNum(sourcePositionProperty.getPage());
document.close();
realPositionProperties.add(realPositionProperty);
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return realPositionProperties ;
}
/**
* @Description #单独计算真实签署位置
* @Param [sourcePositionProperty]
* @return com.resrun.modules.sign.service.tool.pojo.RealPositionProperty
**/
public RealPositionProperty calculatePosition(SourcePositionProperty sourcePositionProperty, byte[] pdfFileByte){
RealPositionProperty realPositionProperty = new RealPositionProperty();
PdfReader reader = null ;
Document document = null ;
try {
//将pdf文件读入PdfReader工具类
reader = new PdfReader(pdfFileByte);
document = new Document(reader.getPageSize(sourcePositionProperty.getPage()));
//获取真实pdf文件指定页的真实文档宽高
float realPdfHeight = document.getPageSize().getHeight();
float realPdfWidth = document.getPageSize().getWidth();
//获取页面上文档的宽高
float sourcePageWidth = sourcePositionProperty.getPageWidth();
float sourcePageHeight = sourcePositionProperty.getPageHeight();
//计算真实文档的宽高和页面文档的宽高的比率
float rateHeight = realPdfHeight / sourcePageHeight;
float rateWidth = realPdfWidth / sourcePageWidth;
//计算页面上的横纵坐标,由于页面上给出的是左上角的坐标,所以需要再转换计算一下
//左下角
float pageStartX = sourcePositionProperty.getOffsetX();
float pageStartY = sourcePositionProperty.getOffsetY() + sourcePositionProperty.getHeight() ;
//右上角
float pageEndX = sourcePositionProperty.getOffsetX() + sourcePositionProperty.getWidth();
float pageEndY = sourcePositionProperty.getOffsetY();
//根据比率去计算真实文档上的坐标位置
float startX = pageStartX * rateWidth ;
float startY = pageStartY * rateHeight;
float endX = pageEndX * rateWidth ;
float endY = pageEndY * rateHeight ;
//由于页面的纵坐标和pdf的纵坐标是相反的,所以真实的pdf的纵坐标在计算的时候需要再反转一下
startY = realPdfHeight - startY ;
endY = realPdfHeight - endY ;
//封装返回数据
realPositionProperty.setStartx(startX);
realPositionProperty.setStarty(startY);
realPositionProperty.setEndx(endX);
realPositionProperty.setEndy(endY);
realPositionProperty.setPageNum(sourcePositionProperty.getPage());
document.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return realPositionProperty ;
}
public RealPositionProperty calculatePosition(SourcePositionProperty sourcePositionProperty){
RealPositionProperty realPositionProperty = new RealPositionProperty();
//获取真实pdf文件指定页的真实文档宽高
float realPdfHeight = sourcePositionProperty.getRealHeight();
float realPdfWidth = sourcePositionProperty.getRealWidth();
//获取页面上文档的宽高
float sourcePageWidth = sourcePositionProperty.getPageWidth();
float sourcePageHeight = sourcePositionProperty.getPageHeight();
//计算真实文档的宽高和页面文档的宽高的比率
float rateHeight = realPdfHeight / sourcePageHeight;
float rateWidth = realPdfWidth / sourcePageWidth;
//计算页面上的横纵坐标,由于页面上给出的是左上角的坐标,所以需要再转换计算一下
//左下角
float pageStartX = sourcePositionProperty.getOffsetX();
float pageStartY = sourcePositionProperty.getOffsetY() + sourcePositionProperty.getHeight() ;
//右上角
float pageEndX = sourcePositionProperty.getOffsetX() + sourcePositionProperty.getWidth();
float pageEndY = sourcePositionProperty.getOffsetY();
//根据比率去计算真实文档上的坐标位置
float startX = pageStartX * rateWidth ;
float startY = pageStartY * rateHeight;
float endX = pageEndX * rateWidth ;
float endY = pageEndY * rateHeight ;
//由于页面的纵坐标和pdf的纵坐标是相反的,所以真实的pdf的纵坐标在计算的时候需要再反转一下
startY = realPdfHeight - startY ;
endY = realPdfHeight - endY ;
//封装返回数据
realPositionProperty.setStartx(startX);
realPositionProperty.setStarty(startY);
realPositionProperty.setEndx(endX);
realPositionProperty.setEndy(endY);
realPositionProperty.setPageNum(sourcePositionProperty.getPage());
return realPositionProperty ;
}
/**
* 通过查询关键字来获得签名位置信息
* @param pdfFile 签署源文件
* @param keyWords 关键字
* @param width 签章宽度
* @param height 签章高度
* @return 签署位置信息
* @throws IOException
*/
public RealPositionProperty getPositionByKeyWords(byte[] pdfFile, String keyWords, int width, int height) {
RealPositionProperty positionProperty = new RealPositionProperty();
//调用通过关键字查询位置的方法
float[] result = new float[0];
try { | result = new SelectKeywords().selectKeyword(pdfFile,keyWords); | 1 | 2023-12-14 06:53:32+00:00 | 8k |
Mahmud0808/ColorBlendr | app/src/main/java/com/drdisagree/colorblendr/utils/OverlayManager.java | [
{
"identifier": "FABRICATED_OVERLAY_NAME_APPS",
"path": "app/src/main/java/com/drdisagree/colorblendr/common/Const.java",
"snippet": "public static final String FABRICATED_OVERLAY_NAME_APPS = BuildConfig.APPLICATION_ID + \".%s_dynamic_theme\";"
},
{
"identifier": "FABRICATED_OVERLAY_NAME_SYSTEM"... | import static com.drdisagree.colorblendr.common.Const.FABRICATED_OVERLAY_NAME_APPS;
import static com.drdisagree.colorblendr.common.Const.FABRICATED_OVERLAY_NAME_SYSTEM;
import static com.drdisagree.colorblendr.common.Const.FRAMEWORK_PACKAGE;
import static com.drdisagree.colorblendr.common.Const.MONET_ACCENT_SATURATION;
import static com.drdisagree.colorblendr.common.Const.MONET_ACCURATE_SHADES;
import static com.drdisagree.colorblendr.common.Const.MONET_BACKGROUND_LIGHTNESS;
import static com.drdisagree.colorblendr.common.Const.MONET_BACKGROUND_SATURATION;
import static com.drdisagree.colorblendr.common.Const.MONET_PITCH_BLACK_THEME;
import static com.drdisagree.colorblendr.common.Const.MONET_STYLE;
import static com.drdisagree.colorblendr.common.Const.THEMING_ENABLED;
import static com.drdisagree.colorblendr.common.Const.TINT_TEXT_COLOR;
import android.content.Context;
import android.graphics.Color;
import android.os.RemoteException;
import android.util.Log;
import com.drdisagree.colorblendr.ColorBlendr;
import com.drdisagree.colorblendr.R;
import com.drdisagree.colorblendr.common.Const;
import com.drdisagree.colorblendr.config.RPrefs;
import com.drdisagree.colorblendr.service.IRootService;
import com.drdisagree.colorblendr.utils.fabricated.FabricatedOverlayResource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap; | 4,654 | package com.drdisagree.colorblendr.utils;
public class OverlayManager {
private static final String TAG = OverlayManager.class.getSimpleName();
private static final IRootService mRootService = ColorBlendr.getRootService();
private static final String[][] colorNames = ColorUtil.getColorNames();
public static void enableOverlay(String packageName) {
try {
mRootService.enableOverlay(Collections.singletonList(packageName));
} catch (RemoteException e) {
Log.e(TAG, "Failed to enable overlay: " + packageName, e);
}
}
public static void disableOverlay(String packageName) {
try {
mRootService.disableOverlay(Collections.singletonList(packageName));
} catch (RemoteException e) {
Log.e(TAG, "Failed to disable overlay: " + packageName, e);
}
}
public static boolean isOverlayInstalled(String packageName) {
try {
return mRootService.isOverlayInstalled(packageName);
} catch (RemoteException e) {
Log.e(TAG, "Failed to check if overlay is installed: " + packageName, e);
return false;
}
}
public static boolean isOverlayEnabled(String packageName) {
try {
return mRootService.isOverlayEnabled(packageName);
} catch (RemoteException e) {
Log.e(TAG, "Failed to check if overlay is enabled: " + packageName, e);
return false;
}
}
public static void uninstallOverlayUpdates(String packageName) {
try {
mRootService.uninstallOverlayUpdates(packageName);
} catch (RemoteException e) {
Log.e(TAG, "Failed to uninstall overlay updates: " + packageName, e);
}
}
public static void registerFabricatedOverlay(FabricatedOverlayResource fabricatedOverlay) {
try {
mRootService.registerFabricatedOverlay(fabricatedOverlay);
mRootService.enableOverlayWithIdentifier(Collections.singletonList(fabricatedOverlay.overlayName));
} catch (RemoteException e) {
Log.e(TAG, "Failed to register fabricated overlay: " + fabricatedOverlay.overlayName, e);
}
}
public static void unregisterFabricatedOverlay(String packageName) {
try {
mRootService.unregisterFabricatedOverlay(packageName);
} catch (RemoteException e) {
Log.e(TAG, "Failed to unregister fabricated overlay: " + packageName, e);
}
}
public static void applyFabricatedColors(Context context) {
if (!RPrefs.getBoolean(THEMING_ENABLED, true)) {
return;
}
ColorSchemeUtil.MONET style = ColorSchemeUtil.stringToEnumMonetStyle(
context,
RPrefs.getString(MONET_STYLE, context.getString(R.string.monet_tonalspot))
);
int monetAccentSaturation = RPrefs.getInt(MONET_ACCENT_SATURATION, 100);
int monetBackgroundSaturation = RPrefs.getInt(MONET_BACKGROUND_SATURATION, 100);
int monetBackgroundLightness = RPrefs.getInt(MONET_BACKGROUND_LIGHTNESS, 100);
boolean pitchBlackTheme = RPrefs.getBoolean(MONET_PITCH_BLACK_THEME, false);
boolean accurateShades = RPrefs.getBoolean(MONET_ACCURATE_SHADES, true);
ArrayList<ArrayList<Integer>> paletteLight = ColorUtil.generateModifiedColors(
context,
style,
monetAccentSaturation,
monetBackgroundSaturation,
monetBackgroundLightness,
pitchBlackTheme,
accurateShades,
false,
false
);
ArrayList<ArrayList<Integer>> paletteDark = ColorUtil.generateModifiedColors(
context,
style,
monetAccentSaturation,
monetBackgroundSaturation,
monetBackgroundLightness,
pitchBlackTheme,
accurateShades,
false,
true
);
ArrayList<FabricatedOverlayResource> fabricatedOverlays = new ArrayList<>();
fabricatedOverlays.add(new FabricatedOverlayResource(
FABRICATED_OVERLAY_NAME_SYSTEM, | package com.drdisagree.colorblendr.utils;
public class OverlayManager {
private static final String TAG = OverlayManager.class.getSimpleName();
private static final IRootService mRootService = ColorBlendr.getRootService();
private static final String[][] colorNames = ColorUtil.getColorNames();
public static void enableOverlay(String packageName) {
try {
mRootService.enableOverlay(Collections.singletonList(packageName));
} catch (RemoteException e) {
Log.e(TAG, "Failed to enable overlay: " + packageName, e);
}
}
public static void disableOverlay(String packageName) {
try {
mRootService.disableOverlay(Collections.singletonList(packageName));
} catch (RemoteException e) {
Log.e(TAG, "Failed to disable overlay: " + packageName, e);
}
}
public static boolean isOverlayInstalled(String packageName) {
try {
return mRootService.isOverlayInstalled(packageName);
} catch (RemoteException e) {
Log.e(TAG, "Failed to check if overlay is installed: " + packageName, e);
return false;
}
}
public static boolean isOverlayEnabled(String packageName) {
try {
return mRootService.isOverlayEnabled(packageName);
} catch (RemoteException e) {
Log.e(TAG, "Failed to check if overlay is enabled: " + packageName, e);
return false;
}
}
public static void uninstallOverlayUpdates(String packageName) {
try {
mRootService.uninstallOverlayUpdates(packageName);
} catch (RemoteException e) {
Log.e(TAG, "Failed to uninstall overlay updates: " + packageName, e);
}
}
public static void registerFabricatedOverlay(FabricatedOverlayResource fabricatedOverlay) {
try {
mRootService.registerFabricatedOverlay(fabricatedOverlay);
mRootService.enableOverlayWithIdentifier(Collections.singletonList(fabricatedOverlay.overlayName));
} catch (RemoteException e) {
Log.e(TAG, "Failed to register fabricated overlay: " + fabricatedOverlay.overlayName, e);
}
}
public static void unregisterFabricatedOverlay(String packageName) {
try {
mRootService.unregisterFabricatedOverlay(packageName);
} catch (RemoteException e) {
Log.e(TAG, "Failed to unregister fabricated overlay: " + packageName, e);
}
}
public static void applyFabricatedColors(Context context) {
if (!RPrefs.getBoolean(THEMING_ENABLED, true)) {
return;
}
ColorSchemeUtil.MONET style = ColorSchemeUtil.stringToEnumMonetStyle(
context,
RPrefs.getString(MONET_STYLE, context.getString(R.string.monet_tonalspot))
);
int monetAccentSaturation = RPrefs.getInt(MONET_ACCENT_SATURATION, 100);
int monetBackgroundSaturation = RPrefs.getInt(MONET_BACKGROUND_SATURATION, 100);
int monetBackgroundLightness = RPrefs.getInt(MONET_BACKGROUND_LIGHTNESS, 100);
boolean pitchBlackTheme = RPrefs.getBoolean(MONET_PITCH_BLACK_THEME, false);
boolean accurateShades = RPrefs.getBoolean(MONET_ACCURATE_SHADES, true);
ArrayList<ArrayList<Integer>> paletteLight = ColorUtil.generateModifiedColors(
context,
style,
monetAccentSaturation,
monetBackgroundSaturation,
monetBackgroundLightness,
pitchBlackTheme,
accurateShades,
false,
false
);
ArrayList<ArrayList<Integer>> paletteDark = ColorUtil.generateModifiedColors(
context,
style,
monetAccentSaturation,
monetBackgroundSaturation,
monetBackgroundLightness,
pitchBlackTheme,
accurateShades,
false,
true
);
ArrayList<FabricatedOverlayResource> fabricatedOverlays = new ArrayList<>();
fabricatedOverlays.add(new FabricatedOverlayResource(
FABRICATED_OVERLAY_NAME_SYSTEM, | FRAMEWORK_PACKAGE | 2 | 2023-12-06 13:20:16+00:00 | 8k |
bzvs1992/spring-boot-holiday-starter | src/main/java/cn/bzvs/holiday/service/HolidayService.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.entity.vo.CalendarInfoVO;
import cn.bzvs.holiday.entity.vo.CalendarVO;
import cn.bzvs.holiday.util.HolidayUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map; | 3,648 | package cn.bzvs.holiday.service;
/**
* 节假日相关的日历服务
*
* @author bzvs
* @date 2024/12/06
* @since 1.0.0
*/
public class HolidayService {
private static final String format = "yyyy-MM-dd";
/**
* 获取指定日期的节假日信息
* @param date
* @return HolidayVO
*/
public CalendarInfoVO getDate(Date date) {
String day = DateUtil.format(date, format);
return getDate(day);
}
/**
* 获取指定日期的节假日信息
* @param localDate
* @return HolidayVO
*/
public CalendarInfoVO getDate(LocalDate localDate) {
String day = DateUtil.format(localDate.atStartOfDay(), format);
return getDate(day);
}
/**
* 获取指定日期的节假日信息
* @param localDateTime
* @return HolidayVO
*/
public CalendarInfoVO getDate(LocalDateTime localDateTime) {
String day = DateUtil.format(localDateTime, format);
return getDate(day);
}
/**
* 获取指定日期的节假日信息
* @param date 日期格式:yyyy-MM-dd
* @return HolidayVO
*/
public CalendarInfoVO getDate(String date) {
return getVo(date);
}
/**
* 是否是节假日
* @param date
* @return boolean
*/
public boolean isHoliday(Date date) {
String day = DateUtil.format(date, format);
return isHoliday(day);
}
/**
* 是否是节假日
* @param localDate
* @return boolean
*/
public boolean isHoliday(LocalDate localDate) {
return isHoliday(localDate.atStartOfDay());
}
/**
* 是否是节假日
* @param localDateTime
* @return boolean
*/
public boolean isHoliday(LocalDateTime localDateTime) {
String day = DateUtil.format(localDateTime, format);
return isHoliday(day);
}
/**
* 是否是节假日
* @param day
* @return boolean
*/
public boolean isHoliday(String day) {
CalendarVO vo = getDate(day);
return vo.getStatus() == 3;
}
/**
* 是否是工作日或补班
* @param date
* @return boolean
*/
public boolean isWorkDay(Date date) {
String day = DateUtil.format(date, format);
return isWorkDay(day);
}
/**
* 是否是工作日或补班
* @param localDate
* @return boolean
*/
public boolean isWorkDay(LocalDate localDate) {
return isWorkDay(localDate.atStartOfDay());
}
/**
* 是否是工作日或补班
* @param localDateTime
* @return boolean
*/
public boolean isWorkDay(LocalDateTime localDateTime) {
String day = DateUtil.format(localDateTime, format);
return isWorkDay(day);
}
/**
* 是否是工作日或补班
* @param day
* @return boolean
*/
public boolean isWorkDay(String day) {
CalendarVO vo = getDate(day);
return vo.getStatus() == 0 || vo.getStatus() == 2;
}
/**
* 是否是周末
* @param date
* @return boolean
*/
public boolean isWeekend(Date date) {
String day = DateUtil.format(date, format);
return isWeekend(day);
}
/**
* 是否是周末
* @param localDate
* @return boolean
*/
public boolean isWeekend(LocalDate localDate) {
return isWeekend(localDate.atStartOfDay());
}
/**
* 是否是周末
* @param localDateTime
* @return boolean
*/
public boolean isWeekend(LocalDateTime localDateTime) {
String day = DateUtil.format(localDateTime, format);
return isWeekend(day);
}
/**
* 是否是周末
* @param day
* @return boolean
*/
public boolean isWeekend(String day) {
CalendarVO vo = getDate(day);
return vo.getStatus() == 1;
}
private static CalendarInfoVO getVo(String date) {
DateTime dateTime = DateUtil.parseDate(date);
CalendarInfoVO infoVO;
Map<String, CalendarVO> voMap = ConstantData.getAllDateMap(); | package cn.bzvs.holiday.service;
/**
* 节假日相关的日历服务
*
* @author bzvs
* @date 2024/12/06
* @since 1.0.0
*/
public class HolidayService {
private static final String format = "yyyy-MM-dd";
/**
* 获取指定日期的节假日信息
* @param date
* @return HolidayVO
*/
public CalendarInfoVO getDate(Date date) {
String day = DateUtil.format(date, format);
return getDate(day);
}
/**
* 获取指定日期的节假日信息
* @param localDate
* @return HolidayVO
*/
public CalendarInfoVO getDate(LocalDate localDate) {
String day = DateUtil.format(localDate.atStartOfDay(), format);
return getDate(day);
}
/**
* 获取指定日期的节假日信息
* @param localDateTime
* @return HolidayVO
*/
public CalendarInfoVO getDate(LocalDateTime localDateTime) {
String day = DateUtil.format(localDateTime, format);
return getDate(day);
}
/**
* 获取指定日期的节假日信息
* @param date 日期格式:yyyy-MM-dd
* @return HolidayVO
*/
public CalendarInfoVO getDate(String date) {
return getVo(date);
}
/**
* 是否是节假日
* @param date
* @return boolean
*/
public boolean isHoliday(Date date) {
String day = DateUtil.format(date, format);
return isHoliday(day);
}
/**
* 是否是节假日
* @param localDate
* @return boolean
*/
public boolean isHoliday(LocalDate localDate) {
return isHoliday(localDate.atStartOfDay());
}
/**
* 是否是节假日
* @param localDateTime
* @return boolean
*/
public boolean isHoliday(LocalDateTime localDateTime) {
String day = DateUtil.format(localDateTime, format);
return isHoliday(day);
}
/**
* 是否是节假日
* @param day
* @return boolean
*/
public boolean isHoliday(String day) {
CalendarVO vo = getDate(day);
return vo.getStatus() == 3;
}
/**
* 是否是工作日或补班
* @param date
* @return boolean
*/
public boolean isWorkDay(Date date) {
String day = DateUtil.format(date, format);
return isWorkDay(day);
}
/**
* 是否是工作日或补班
* @param localDate
* @return boolean
*/
public boolean isWorkDay(LocalDate localDate) {
return isWorkDay(localDate.atStartOfDay());
}
/**
* 是否是工作日或补班
* @param localDateTime
* @return boolean
*/
public boolean isWorkDay(LocalDateTime localDateTime) {
String day = DateUtil.format(localDateTime, format);
return isWorkDay(day);
}
/**
* 是否是工作日或补班
* @param day
* @return boolean
*/
public boolean isWorkDay(String day) {
CalendarVO vo = getDate(day);
return vo.getStatus() == 0 || vo.getStatus() == 2;
}
/**
* 是否是周末
* @param date
* @return boolean
*/
public boolean isWeekend(Date date) {
String day = DateUtil.format(date, format);
return isWeekend(day);
}
/**
* 是否是周末
* @param localDate
* @return boolean
*/
public boolean isWeekend(LocalDate localDate) {
return isWeekend(localDate.atStartOfDay());
}
/**
* 是否是周末
* @param localDateTime
* @return boolean
*/
public boolean isWeekend(LocalDateTime localDateTime) {
String day = DateUtil.format(localDateTime, format);
return isWeekend(day);
}
/**
* 是否是周末
* @param day
* @return boolean
*/
public boolean isWeekend(String day) {
CalendarVO vo = getDate(day);
return vo.getStatus() == 1;
}
private static CalendarInfoVO getVo(String date) {
DateTime dateTime = DateUtil.parseDate(date);
CalendarInfoVO infoVO;
Map<String, CalendarVO> voMap = ConstantData.getAllDateMap(); | int dayOfWeek = HolidayUtil.getDayOfWeek(dateTime); | 3 | 2023-12-05 10:59:02+00:00 | 8k |
HelpChat/DeluxeMenus | src/main/java/com/extendedclip/deluxemenus/hooks/TextureHeadHook.java | [
{
"identifier": "DeluxeMenus",
"path": "src/main/java/com/extendedclip/deluxemenus/DeluxeMenus.java",
"snippet": "public class DeluxeMenus extends JavaPlugin {\r\n\r\n public final static Map<String, Material> MATERIALS\r\n = Arrays.stream(Material.values()).collect(Collectors.toUnmodifiableMa... | import com.extendedclip.deluxemenus.DeluxeMenus;
import com.extendedclip.deluxemenus.cache.SimpleCache;
import com.extendedclip.deluxemenus.utils.SkullUtils;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
| 3,958 | package com.extendedclip.deluxemenus.hooks;
public class TextureHeadHook implements ItemHook, SimpleCache {
private final Map<String, ItemStack> cache = new ConcurrentHashMap<>();
@Override
public ItemStack getItem(@NotNull final String... arguments) {
if (arguments.length == 0) {
| package com.extendedclip.deluxemenus.hooks;
public class TextureHeadHook implements ItemHook, SimpleCache {
private final Map<String, ItemStack> cache = new ConcurrentHashMap<>();
@Override
public ItemStack getItem(@NotNull final String... arguments) {
if (arguments.length == 0) {
| return DeluxeMenus.getInstance().getHead().clone();
| 0 | 2023-12-14 23:41:07+00:00 | 8k |
lxs2601055687/contextAdminRuoYi | ruoyi-demo/src/main/java/com/ruoyi/contest/service/impl/UserServiceImpl.java | [
{
"identifier": "StringUtils",
"path": "ruoyi-common/src/main/java/com/ruoyi/common/utils/StringUtils.java",
"snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class StringUtils extends org.apache.commons.lang3.StringUtils {\n\n public static final String SEPARATOR = \",\";\n\n /... | import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.contest.domain.TeamInfo;
import com.ruoyi.contest.mapper.TeamInfoMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.contest.domain.bo.UserBo;
import com.ruoyi.contest.domain.vo.UserVo;
import com.ruoyi.contest.domain.User;
import com.ruoyi.contest.mapper.UserMapper;
import com.ruoyi.contest.service.IUserService;
import org.springframework.util.DigestUtils;
import java.util.List;
import java.util.Map;
import java.util.Collection; | 6,114 | package com.ruoyi.contest.service.impl;
/**
* 学生管理Service业务层处理
*
* @author 李祥生
* @date 2023-04-14
*/
@RequiredArgsConstructor
@Service
public class UserServiceImpl implements IUserService {
| package com.ruoyi.contest.service.impl;
/**
* 学生管理Service业务层处理
*
* @author 李祥生
* @date 2023-04-14
*/
@RequiredArgsConstructor
@Service
public class UserServiceImpl implements IUserService {
| private final UserMapper baseMapper; | 8 | 2023-12-07 12:06:21+00:00 | 8k |
DHBin/isme-java-serve | src/main/java/cn/dhbin/isme/pms/service/impl/UserServiceImpl.java | [
{
"identifier": "SaTokenConfigure",
"path": "src/main/java/cn/dhbin/isme/common/auth/SaTokenConfigure.java",
"snippet": "@Configuration\npublic class SaTokenConfigure implements WebMvcConfigurer {\n\n public static final String JWT_USER_ID_KEY = \"userId\";\n\n public static final String JWT_USERN... | import cn.dev33.satoken.stp.SaLoginConfig;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dhbin.isme.common.auth.SaTokenConfigure;
import cn.dhbin.isme.common.exception.BizException;
import cn.dhbin.isme.common.preview.PreviewProperties;
import cn.dhbin.isme.common.response.BizResponseCode;
import cn.dhbin.isme.common.response.Page;
import cn.dhbin.isme.pms.domain.dto.LoginTokenDto;
import cn.dhbin.isme.pms.domain.dto.ProfileDto;
import cn.dhbin.isme.pms.domain.dto.RoleDto;
import cn.dhbin.isme.pms.domain.dto.UserDetailDto;
import cn.dhbin.isme.pms.domain.dto.UserPageDto;
import cn.dhbin.isme.pms.domain.entity.Profile;
import cn.dhbin.isme.pms.domain.entity.Role;
import cn.dhbin.isme.pms.domain.entity.User;
import cn.dhbin.isme.pms.domain.entity.UserRole;
import cn.dhbin.isme.pms.domain.request.AddUserRolesRequest;
import cn.dhbin.isme.pms.domain.request.ChangePasswordRequest;
import cn.dhbin.isme.pms.domain.request.LoginRequest;
import cn.dhbin.isme.pms.domain.request.RegisterUserProfileRequest;
import cn.dhbin.isme.pms.domain.request.RegisterUserRequest;
import cn.dhbin.isme.pms.domain.request.UpdatePasswordRequest;
import cn.dhbin.isme.pms.domain.request.UpdateProfileRequest;
import cn.dhbin.isme.pms.domain.request.UserPageRequest;
import cn.dhbin.isme.pms.mapper.UserMapper;
import cn.dhbin.isme.pms.service.CaptchaService;
import cn.dhbin.isme.pms.service.ProfileService;
import cn.dhbin.isme.pms.service.RoleService;
import cn.dhbin.isme.pms.service.UserRoleService;
import cn.dhbin.isme.pms.service.UserService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.List;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; | 4,714 | package cn.dhbin.isme.pms.service.impl;
/**
* User Service impl
*
* @author dhb
*/
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
private final RoleService roleService;
private final ProfileService profileService;
private final UserRoleService userRoleService;
private final CaptchaService captchaService;
private final PreviewProperties previewProperties;
@Override
public LoginTokenDto login(LoginRequest request) {
User user = lambdaQuery().eq(User::getUsername, request.getUsername()).one();
if (user == null) { | package cn.dhbin.isme.pms.service.impl;
/**
* User Service impl
*
* @author dhb
*/
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
private final RoleService roleService;
private final ProfileService profileService;
private final UserRoleService userRoleService;
private final CaptchaService captchaService;
private final PreviewProperties previewProperties;
@Override
public LoginTokenDto login(LoginRequest request) {
User user = lambdaQuery().eq(User::getUsername, request.getUsername()).one();
if (user == null) { | throw new BizException(BizResponseCode.ERR_10002); | 3 | 2023-12-13 17:21:04+00:00 | 8k |
Earthcomputer/ModCompatChecker | root/src/main/java/net/earthcomputer/modcompatchecker/checker/ClassCheckVisitor.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 net.earthcomputer.modcompatchecker.util.AsmUtil;
import net.earthcomputer.modcompatchecker.util.ClassMember;
import net.earthcomputer.modcompatchecker.util.InheritanceUtil;
import net.earthcomputer.modcompatchecker.util.UnimplementedMethodChecker;
import org.jetbrains.annotations.Nullable;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type; | 5,580 | package net.earthcomputer.modcompatchecker.checker;
public final class ClassCheckVisitor extends ClassVisitor {
private final Index index;
private final CheckerConfig config;
private final ProblemCollector problems;
private String superName;
@Nullable
private IResolvedClass superClass;
private String className;
public ClassCheckVisitor(Index index, CheckerConfig config, ProblemCollector problems) { | package net.earthcomputer.modcompatchecker.checker;
public final class ClassCheckVisitor extends ClassVisitor {
private final Index index;
private final CheckerConfig config;
private final ProblemCollector problems;
private String superName;
@Nullable
private IResolvedClass superClass;
private String className;
public ClassCheckVisitor(Index index, CheckerConfig config, ProblemCollector problems) { | super(AsmUtil.API); | 2 | 2023-12-11 00:48:12+00:00 | 8k |
wkgcass/jdkman | src/main/java/io/vproxy/jdkman/action/AddAction.java | [
{
"identifier": "JDKInfo",
"path": "src/main/java/io/vproxy/jdkman/entity/JDKInfo.java",
"snippet": "public class JDKInfo implements JSONObject, Comparable<JDKInfo> {\n private String id;\n private int majorVersion;\n private int minorVersion;\n private int patchVersion;\n private String ... | import io.vproxy.base.util.LogType;
import io.vproxy.base.util.Logger;
import io.vproxy.jdkman.entity.JDKInfo;
import io.vproxy.jdkman.entity.JDKInfoMatcher;
import io.vproxy.jdkman.entity.JDKManConfig;
import io.vproxy.jdkman.ex.ErrorResult;
import io.vproxy.jdkman.util.Utils;
import vjson.JSON;
import vjson.ex.JsonParseException;
import java.io.File;
import java.io.FileInputStream;
import java.nio.file.Path;
import java.util.*; | 5,121 | package io.vproxy.jdkman.action;
public class AddAction implements Action {
@Override
public String validate(String[] options) {
if (options.length == 0) {
return "missing JAVA_HOME for `add`";
}
if (options.length > 1) {
return STR."unknown options for `add`: \{Arrays.toString(options)}";
}
return Utils.validateJavaHome(options[0]);
}
@Override
public boolean execute(JDKManConfig config, String[] options) throws Exception {
var javaHome = new File(options[0]).getCanonicalPath();
for (var jdk : config.getJdks()) {
if (javaHome.equals(jdk.getHome())) {
throw new ErrorResult(STR."JDK with JAVA_HOME \{javaHome} is already registered");
}
}
var javaPath = Path.of(javaHome, "bin", "java").toAbsolutePath();
var process = new ProcessBuilder()
.command(javaPath.toString(), "-version")
.start();
var exitCode = process.waitFor();
var stdout = Utils.readInputStream(process.getInputStream());
var stderr = Utils.readInputStream(process.getErrorStream());
if (exitCode != 0) {
throw new ErrorResult(STR."""
unable to retrieve java version: exit code: \{exitCode}
stdout:
\{stdout}
stderr:
\{stderr}""");
}
var lines = stderr.split("\n");
if (lines.length == 0) {
throw new ErrorResult(STR."""
missing java version: empty output
stdout:
\{stdout}
stderr:
\{stderr}""");
}
var firstLine = lines[0].trim();
if (!firstLine.contains("\"")) {
throw new ErrorResult(STR."""
missing java version: first line doesn't contain `"`
stdout:
\{stdout}
stderr:
\{stderr}""");
}
var split = firstLine.split("\"");
if (split.length < 2) {
throw new ErrorResult(STR."""
missing java version: invalid first line
stdout:
\{stdout}
stderr:
\{stderr}""");
}
var versionStr = split[1];
var versionInfo = Utils.parseVersion(versionStr);
if (lines.length >= 2) {
var detailedVersionInfo = parseLine2(lines[1]);
if (detailedVersionInfo != null) {
if (versionInfo.majorVersion != detailedVersionInfo.majorVersion) {
throw new ErrorResult(STR."""
major version mismatch:
\{stderr}""");
}
if (!Objects.equals(versionInfo.minorVersion, detailedVersionInfo.minorVersion)) {
throw new ErrorResult(STR."""
minor version mismatch:
\{stderr}""");
}
if (!Objects.equals(versionInfo.patchVersion, detailedVersionInfo.patchVersion)) {
throw new ErrorResult(STR."""
patch version mismatch:
\{stderr}""");
}
versionInfo = detailedVersionInfo;
}
}
// check release file
String implementor = null;
var releaseFile = Path.of(javaHome, "release").toFile();
if (releaseFile.exists() && releaseFile.isFile()) {
var p = new Properties();
try (var input = new FileInputStream(releaseFile)) {
p.load(input);
}
implementor = p.getProperty("IMPLEMENTOR");
if (implementor != null && implementor.startsWith("\"")) {
JSON.String jsonStr = null;
try {
var o = JSON.parse(implementor);
if (o instanceof JSON.String s) {
jsonStr = s;
}
} catch (JsonParseException e) {
Logger.warn(LogType.ALERT, STR."implementor field is not a valid json string: \{implementor}", e);
}
if (jsonStr != null) {
implementor = jsonStr.toJavaObject();
}
}
}
var uuid = UUID.randomUUID().toString();
var version = new JDKInfo(versionInfo);
version.setId(uuid);
version.setHome(javaHome);
version.setImplementor(implementor);
config.getJdks().add(version);
config.getJdks().sort(Comparator.reverseOrder());
if (config.getDefaultJDK() == null) {
config.setDefaultJDK(uuid);
}
return true;
}
| package io.vproxy.jdkman.action;
public class AddAction implements Action {
@Override
public String validate(String[] options) {
if (options.length == 0) {
return "missing JAVA_HOME for `add`";
}
if (options.length > 1) {
return STR."unknown options for `add`: \{Arrays.toString(options)}";
}
return Utils.validateJavaHome(options[0]);
}
@Override
public boolean execute(JDKManConfig config, String[] options) throws Exception {
var javaHome = new File(options[0]).getCanonicalPath();
for (var jdk : config.getJdks()) {
if (javaHome.equals(jdk.getHome())) {
throw new ErrorResult(STR."JDK with JAVA_HOME \{javaHome} is already registered");
}
}
var javaPath = Path.of(javaHome, "bin", "java").toAbsolutePath();
var process = new ProcessBuilder()
.command(javaPath.toString(), "-version")
.start();
var exitCode = process.waitFor();
var stdout = Utils.readInputStream(process.getInputStream());
var stderr = Utils.readInputStream(process.getErrorStream());
if (exitCode != 0) {
throw new ErrorResult(STR."""
unable to retrieve java version: exit code: \{exitCode}
stdout:
\{stdout}
stderr:
\{stderr}""");
}
var lines = stderr.split("\n");
if (lines.length == 0) {
throw new ErrorResult(STR."""
missing java version: empty output
stdout:
\{stdout}
stderr:
\{stderr}""");
}
var firstLine = lines[0].trim();
if (!firstLine.contains("\"")) {
throw new ErrorResult(STR."""
missing java version: first line doesn't contain `"`
stdout:
\{stdout}
stderr:
\{stderr}""");
}
var split = firstLine.split("\"");
if (split.length < 2) {
throw new ErrorResult(STR."""
missing java version: invalid first line
stdout:
\{stdout}
stderr:
\{stderr}""");
}
var versionStr = split[1];
var versionInfo = Utils.parseVersion(versionStr);
if (lines.length >= 2) {
var detailedVersionInfo = parseLine2(lines[1]);
if (detailedVersionInfo != null) {
if (versionInfo.majorVersion != detailedVersionInfo.majorVersion) {
throw new ErrorResult(STR."""
major version mismatch:
\{stderr}""");
}
if (!Objects.equals(versionInfo.minorVersion, detailedVersionInfo.minorVersion)) {
throw new ErrorResult(STR."""
minor version mismatch:
\{stderr}""");
}
if (!Objects.equals(versionInfo.patchVersion, detailedVersionInfo.patchVersion)) {
throw new ErrorResult(STR."""
patch version mismatch:
\{stderr}""");
}
versionInfo = detailedVersionInfo;
}
}
// check release file
String implementor = null;
var releaseFile = Path.of(javaHome, "release").toFile();
if (releaseFile.exists() && releaseFile.isFile()) {
var p = new Properties();
try (var input = new FileInputStream(releaseFile)) {
p.load(input);
}
implementor = p.getProperty("IMPLEMENTOR");
if (implementor != null && implementor.startsWith("\"")) {
JSON.String jsonStr = null;
try {
var o = JSON.parse(implementor);
if (o instanceof JSON.String s) {
jsonStr = s;
}
} catch (JsonParseException e) {
Logger.warn(LogType.ALERT, STR."implementor field is not a valid json string: \{implementor}", e);
}
if (jsonStr != null) {
implementor = jsonStr.toJavaObject();
}
}
}
var uuid = UUID.randomUUID().toString();
var version = new JDKInfo(versionInfo);
version.setId(uuid);
version.setHome(javaHome);
version.setImplementor(implementor);
config.getJdks().add(version);
config.getJdks().sort(Comparator.reverseOrder());
if (config.getDefaultJDK() == null) {
config.setDefaultJDK(uuid);
}
return true;
}
| private JDKInfoMatcher parseLine2(String secondLine) throws ErrorResult { | 1 | 2023-12-07 04:55:35+00:00 | 8k |
DantSu/studio | core/src/main/java/studio/core/v1/reader/fs/FsStoryPackReader.java | [
{
"identifier": "ActionNode",
"path": "core/src/main/java/studio/core/v1/model/ActionNode.java",
"snippet": "public class ActionNode extends Node {\n\n private List<StageNode> options;\n\n public ActionNode(EnrichedNodeMetadata enriched, List<StageNode> options) {\n super(enriched);\n ... | import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import studio.core.v1.model.ActionNode;
import studio.core.v1.model.ControlSettings;
import studio.core.v1.model.StageNode;
import studio.core.v1.model.StoryPack;
import studio.core.v1.model.Transition;
import studio.core.v1.model.asset.AudioAsset;
import studio.core.v1.model.asset.AudioType;
import studio.core.v1.model.asset.ImageAsset;
import studio.core.v1.model.asset.ImageType;
import studio.core.v1.model.metadata.StoryPackMetadata;
import studio.core.v1.reader.StoryPackReader;
import studio.core.v1.utils.PackFormat;
import studio.core.v1.utils.XXTEACipher;
import studio.core.v1.utils.XXTEACipher.CipherMode; | 4,752 | /*
* 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.core.v1.reader.fs;
public class FsStoryPackReader implements StoryPackReader {
private static final Logger LOGGER = LogManager.getLogger(FsStoryPackReader.class);
private static final String NODE_INDEX_FILENAME = "ni";
private static final String LIST_INDEX_FILENAME = "li";
private static final String IMAGE_INDEX_FILENAME = "ri";
private static final String IMAGE_FOLDER = "rf";
private static final String SOUND_INDEX_FILENAME = "si";
private static final String SOUND_FOLDER = "sf";
private static final String NIGHT_MODE_FILENAME = "nm";
public StoryPackMetadata readMetadata(Path inputFolder) throws IOException {
// Pack metadata model
StoryPackMetadata metadata = new StoryPackMetadata(PackFormat.FS);
// Open 'ni' file
Path niPath = inputFolder.resolve(NODE_INDEX_FILENAME);
try(InputStream niDis = new BufferedInputStream(Files.newInputStream(niPath))) {
ByteBuffer bb = ByteBuffer.wrap(niDis.readNBytes(512)).order(ByteOrder.LITTLE_ENDIAN);
metadata.setVersion(bb.getShort(2));
}
// Folder name is the uuid (minus the eventual timestamp, so we just trim everything starting at the dot)
String uuid = inputFolder.getFileName().toString().split("\\.", 2)[0];
metadata.setUuid(uuid);
// Night mode is available if file 'nm' exists
Path nmPath = inputFolder.resolve(NIGHT_MODE_FILENAME);
metadata.setNightModeAvailable(Files.exists(nmPath));
return metadata;
}
| /*
* 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.core.v1.reader.fs;
public class FsStoryPackReader implements StoryPackReader {
private static final Logger LOGGER = LogManager.getLogger(FsStoryPackReader.class);
private static final String NODE_INDEX_FILENAME = "ni";
private static final String LIST_INDEX_FILENAME = "li";
private static final String IMAGE_INDEX_FILENAME = "ri";
private static final String IMAGE_FOLDER = "rf";
private static final String SOUND_INDEX_FILENAME = "si";
private static final String SOUND_FOLDER = "sf";
private static final String NIGHT_MODE_FILENAME = "nm";
public StoryPackMetadata readMetadata(Path inputFolder) throws IOException {
// Pack metadata model
StoryPackMetadata metadata = new StoryPackMetadata(PackFormat.FS);
// Open 'ni' file
Path niPath = inputFolder.resolve(NODE_INDEX_FILENAME);
try(InputStream niDis = new BufferedInputStream(Files.newInputStream(niPath))) {
ByteBuffer bb = ByteBuffer.wrap(niDis.readNBytes(512)).order(ByteOrder.LITTLE_ENDIAN);
metadata.setVersion(bb.getShort(2));
}
// Folder name is the uuid (minus the eventual timestamp, so we just trim everything starting at the dot)
String uuid = inputFolder.getFileName().toString().split("\\.", 2)[0];
metadata.setUuid(uuid);
// Night mode is available if file 'nm' exists
Path nmPath = inputFolder.resolve(NIGHT_MODE_FILENAME);
metadata.setNightModeAvailable(Files.exists(nmPath));
return metadata;
}
| public StoryPack read(Path inputFolder) throws IOException { | 3 | 2023-12-14 15:08:35+00:00 | 8k |
conductor-oss/conductor-community | event-queue/amqp/src/main/java/com/netflix/conductor/contribs/queue/amqp/AMQPObservableQueue.java | [
{
"identifier": "AMQPEventQueueProperties",
"path": "event-queue/amqp/src/main/java/com/netflix/conductor/contribs/queue/amqp/config/AMQPEventQueueProperties.java",
"snippet": "@ConfigurationProperties(\"conductor.event-queues.amqp\")\npublic class AMQPEventQueueProperties {\n\n private int batchSize... | import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.netflix.conductor.contribs.queue.amqp.config.AMQPEventQueueProperties;
import com.netflix.conductor.contribs.queue.amqp.config.AMQPRetryPattern;
import com.netflix.conductor.contribs.queue.amqp.util.AMQPConstants;
import com.netflix.conductor.contribs.queue.amqp.util.AMQPSettings;
import com.netflix.conductor.contribs.queue.amqp.util.ConnectionType;
import com.netflix.conductor.core.events.queue.Message;
import com.netflix.conductor.core.events.queue.ObservableQueue;
import com.netflix.conductor.metrics.Monitors;
import com.google.common.collect.Maps;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Address;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.GetResponse;
import rx.Observable;
import rx.Subscriber; | 5,756 | /*
* <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.contribs.queue.amqp;
/**
* @author Ritu Parathody
*/
public class AMQPObservableQueue implements ObservableQueue {
private static final Logger LOGGER = LoggerFactory.getLogger(AMQPObservableQueue.class);
| /*
* <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.contribs.queue.amqp;
/**
* @author Ritu Parathody
*/
public class AMQPObservableQueue implements ObservableQueue {
private static final Logger LOGGER = LoggerFactory.getLogger(AMQPObservableQueue.class);
| private final AMQPSettings settings; | 3 | 2023-12-08 06:06:20+00:00 | 8k |
zhouyqxy/aurora_Lite | src/main/java/com/aurora/service/impl/UserAuthServiceImpl.java | [
{
"identifier": "CommonConstant",
"path": "src/main/java/com/aurora/constant/CommonConstant.java",
"snippet": "public interface CommonConstant {\n\n int ONE = 1;\n\n int ZERO = 0;\n\n int FALSE = 0;\n\n int TRUE = 1;\n\n int BLOGGER_ID = 1;\n\n int DEFAULT_CONFIG_ID = 1;\n\n int DEF... | import com.alibaba.fastjson.JSON;
import com.aurora.constant.CommonConstant;
import com.aurora.entity.UserAuth;
import com.aurora.entity.UserInfo;
import com.aurora.entity.UserRole;
import com.aurora.enums.LoginTypeEnum;
import com.aurora.enums.RoleEnum;
import com.aurora.exception.BizException;
import com.aurora.mapper.UserAuthMapper;
import com.aurora.mapper.UserInfoMapper;
import com.aurora.mapper.UserRoleMapper;
import com.aurora.model.dto.*;
import com.aurora.model.vo.ConditionVO;
import com.aurora.model.vo.PasswordVO;
import com.aurora.model.vo.QQLoginVO;
import com.aurora.model.vo.UserVO;
import com.aurora.service.AuroraInfoService;
import com.aurora.service.RedisService;
import com.aurora.service.TokenService;
import com.aurora.service.UserAuthService;
import com.aurora.strategy.context.SocialLoginStrategyContext;
import com.aurora.util.EmailUtil;
import com.aurora.util.PageUtil;
import com.aurora.util.UserUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import static com.aurora.constant.RedisConstant.*;
import static com.aurora.enums.UserAreaTypeEnum.getUserAreaType;
import static com.aurora.util.CommonUtil.checkEmail;
import static com.aurora.util.CommonUtil.getRandomCode; | 4,862 | package com.aurora.service.impl;
@Service
public class UserAuthServiceImpl implements UserAuthService {
@Autowired
private UserAuthMapper userAuthMapper;
@Autowired
private UserInfoMapper userInfoMapper;
@Autowired
private UserRoleMapper userRoleMapper;
@Autowired
private RedisService redisService;
@Autowired
private AuroraInfoService auroraInfoService;
@Autowired
private TokenService tokenService;
@Autowired
private SocialLoginStrategyContext socialLoginStrategyContext;
@Resource
EmailUtil emailUtil;
@Override
public void sendCode(String username) {
if (!checkEmail(username)) {
throw new BizException("请输入正确邮箱");
}
String code = getRandomCode();
Map<String, Object> map = new HashMap<>();
map.put("content", "您的验证码为 " + code + " 有效期15分钟,请不要告诉他人哦!");
EmailDTO emailDTO = EmailDTO.builder()
.email(username)
.subject(CommonConstant.CAPTCHA)
.template("common.html")
.commentMap(map)
.build();
emailUtil.sendHtmlMail(emailDTO);
// rabbitTemplate.convertAndSend(EMAIL_EXCHANGE, "*", new Message(JSON.toJSONBytes(emailDTO), new MessageProperties()));
redisService.set(USER_CODE_KEY + username, code, CODE_EXPIRE_TIME);
}
@Override
@SuppressWarnings("unchecked")
public List<UserAreaDTO> listUserAreas(ConditionVO conditionVO) {
List<UserAreaDTO> userAreaDTOs = new ArrayList<>();
switch (Objects.requireNonNull(getUserAreaType(conditionVO.getType()))) {
case USER:
Object userArea = redisService.get(USER_AREA);
if (Objects.nonNull(userArea)) {
userAreaDTOs = JSON.parseObject(userArea.toString(), List.class);
}
return userAreaDTOs;
case VISITOR:
Map<String, Object> visitorArea = redisService.hGetAll(VISITOR_AREA);
if (Objects.nonNull(visitorArea)) {
userAreaDTOs = visitorArea.entrySet().stream()
.map(item -> UserAreaDTO.builder()
.name(item.getKey())
.value(Long.valueOf(item.getValue().toString()))
.build())
.collect(Collectors.toList());
}
return userAreaDTOs;
default:
break;
}
return userAreaDTOs;
}
@Override
@Transactional(rollbackFor = Exception.class) | package com.aurora.service.impl;
@Service
public class UserAuthServiceImpl implements UserAuthService {
@Autowired
private UserAuthMapper userAuthMapper;
@Autowired
private UserInfoMapper userInfoMapper;
@Autowired
private UserRoleMapper userRoleMapper;
@Autowired
private RedisService redisService;
@Autowired
private AuroraInfoService auroraInfoService;
@Autowired
private TokenService tokenService;
@Autowired
private SocialLoginStrategyContext socialLoginStrategyContext;
@Resource
EmailUtil emailUtil;
@Override
public void sendCode(String username) {
if (!checkEmail(username)) {
throw new BizException("请输入正确邮箱");
}
String code = getRandomCode();
Map<String, Object> map = new HashMap<>();
map.put("content", "您的验证码为 " + code + " 有效期15分钟,请不要告诉他人哦!");
EmailDTO emailDTO = EmailDTO.builder()
.email(username)
.subject(CommonConstant.CAPTCHA)
.template("common.html")
.commentMap(map)
.build();
emailUtil.sendHtmlMail(emailDTO);
// rabbitTemplate.convertAndSend(EMAIL_EXCHANGE, "*", new Message(JSON.toJSONBytes(emailDTO), new MessageProperties()));
redisService.set(USER_CODE_KEY + username, code, CODE_EXPIRE_TIME);
}
@Override
@SuppressWarnings("unchecked")
public List<UserAreaDTO> listUserAreas(ConditionVO conditionVO) {
List<UserAreaDTO> userAreaDTOs = new ArrayList<>();
switch (Objects.requireNonNull(getUserAreaType(conditionVO.getType()))) {
case USER:
Object userArea = redisService.get(USER_AREA);
if (Objects.nonNull(userArea)) {
userAreaDTOs = JSON.parseObject(userArea.toString(), List.class);
}
return userAreaDTOs;
case VISITOR:
Map<String, Object> visitorArea = redisService.hGetAll(VISITOR_AREA);
if (Objects.nonNull(visitorArea)) {
userAreaDTOs = visitorArea.entrySet().stream()
.map(item -> UserAreaDTO.builder()
.name(item.getKey())
.value(Long.valueOf(item.getValue().toString()))
.build())
.collect(Collectors.toList());
}
return userAreaDTOs;
default:
break;
}
return userAreaDTOs;
}
@Override
@Transactional(rollbackFor = Exception.class) | public void register(UserVO userVO) { | 13 | 2023-12-05 03:38:51+00:00 | 8k |
Ispirer/COBOL-to-Java-Conversion-Samples | IspirerFramework/com/ispirer/sw/types/PictureType.java | [
{
"identifier": "AlphanumericFormat",
"path": "IspirerFramework/com/ispirer/sw/strings/AlphanumericFormat.java",
"snippet": "public class AlphanumericFormat extends Format {\r\n\r\n\tpublic AlphanumericFormat(String format) {\r\n\t\tsuper(format);\r\n\t\tpattern = pattern.replaceAll(\"b\", \" \");\r\n\t... | import com.ispirer.sw.strings.AlphanumericFormat;
import com.ispirer.sw.strings.DecimalFormat;
import com.ispirer.sw.strings.Format;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.nio.charset.Charset;
import java.sql.Clob;
import java.sql.SQLException;
import java.util.regex.Pattern;
import static com.ispirer.sw.types.PictureType.DefaultValue.HighValues;
import static com.ispirer.sw.types.PictureType.DefaultValue.Spaces;
import static java.sql.Types.*; | 5,277 | /*
© 2021, Ispirer Systems OÜ. All rights reserved.
NOTICE OF LICENSE
This file\library is Ispirer Reusable Code (“IRC”) and you are granted a non-exclusive, worldwide, perpetual, irrevocable and fully paid up license to use, modify, adapt, sublicense and otherwise exploit this IRC as provided below and under the terms of Ispirer Systems OÜ. Reusable Code License Agreement (“License”), which can be found in supplementary LICENSE.txt file. By using this IRC, you acknowledge that you have read the License and agree with its terms as well as with the fact that IRC is the property of and belongs to Ispirer Systems OÜ only.
IF YOU ARE NOT AGREE WITH THE TERMS OF THE LICENSE, PLEASE, STOP USING THIS IRC IMMEDIATELY!
PLEASE, NOTE, THAT IRC IS DISTRIBUTED “AS IS” AND WITHOUT ANY WARRANTY. IN NO EVENT WILL ISPIRER BE LIABLE FOR ANY DAMAGES, CLAIMS OR COSTS WHATSOEVER OR ANY CONSEQUENTIAL, INDIRECT, INCIDENTAL DAMAGES, OR ANY LOST PROFITS OR LOST SAVINGS.
Redistributions of this IRC must retain the above copyright notice and a list of significant changes made to this IRC with indication of its author(s) and date of changes.
If you need more information, or you think that the License has been violated, please let us know by e-mail: legal.department@ispirer.com
*/
package com.ispirer.sw.types;
public class PictureType<T extends Object> implements Comparable<Object> {
private static Logger LOGGER = LoggerFactory.getLogger(PictureType.class);
private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
private T value; // stores the value
private T type; // indicates type of variables
private String formatedValue = ""; // stores value in the display mood
private Format format; // the format object.
private int indicator = 0;
public boolean hasDefVal = false;
private String trimmedValue; // stores trimmed value. this value is used for getting and setting value to DB
public static boolean isEBSDIC = false;
private DefaultValue defaultValue;
/**
* Use this constructor if you need to make PT variable quickly. For example if
* you have numeric constant and need to make it PT variable to use in the
* calculations
*
* Do not use this constructor to declare PT variable that is going to be used
* not just in the calculation.
*
* @param value value of PT variable
*/
public PictureType(T value) { // can be used only for calculation and value
this.value = value;
}
/**
* Default constructor for PT variable
*
* @param type indicates type of variable
* @param format object that manage displaying of variables
*/
public PictureType(Type type, Format format) {
this(type, format, Spaces); // bu default value is Spaces
trimmedValue = null;
}
/**
* Constructor for PT variable with value for initialization
*
* @param format object that manage displaying of variables
* @param value value of PT variable. also indicates type variable.
*/
public PictureType(Format format, T value) {
this.type = value;
this.format = format;
setValue(value);
initTrimmedValue(value.toString());
}
/**
* Constructor for PT variable with defaultValue for initialization
*
* @param type indicates type of variable
* @param format object that manage displaying of variables
* @param defaultValue object for initialization.
*/
public PictureType(Type type, Format format, DefaultValue defaultValue) {
this.format = format;
getTypedValue(type);
setDefaultValue(defaultValue); | /*
© 2021, Ispirer Systems OÜ. All rights reserved.
NOTICE OF LICENSE
This file\library is Ispirer Reusable Code (“IRC”) and you are granted a non-exclusive, worldwide, perpetual, irrevocable and fully paid up license to use, modify, adapt, sublicense and otherwise exploit this IRC as provided below and under the terms of Ispirer Systems OÜ. Reusable Code License Agreement (“License”), which can be found in supplementary LICENSE.txt file. By using this IRC, you acknowledge that you have read the License and agree with its terms as well as with the fact that IRC is the property of and belongs to Ispirer Systems OÜ only.
IF YOU ARE NOT AGREE WITH THE TERMS OF THE LICENSE, PLEASE, STOP USING THIS IRC IMMEDIATELY!
PLEASE, NOTE, THAT IRC IS DISTRIBUTED “AS IS” AND WITHOUT ANY WARRANTY. IN NO EVENT WILL ISPIRER BE LIABLE FOR ANY DAMAGES, CLAIMS OR COSTS WHATSOEVER OR ANY CONSEQUENTIAL, INDIRECT, INCIDENTAL DAMAGES, OR ANY LOST PROFITS OR LOST SAVINGS.
Redistributions of this IRC must retain the above copyright notice and a list of significant changes made to this IRC with indication of its author(s) and date of changes.
If you need more information, or you think that the License has been violated, please let us know by e-mail: legal.department@ispirer.com
*/
package com.ispirer.sw.types;
public class PictureType<T extends Object> implements Comparable<Object> {
private static Logger LOGGER = LoggerFactory.getLogger(PictureType.class);
private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
private T value; // stores the value
private T type; // indicates type of variables
private String formatedValue = ""; // stores value in the display mood
private Format format; // the format object.
private int indicator = 0;
public boolean hasDefVal = false;
private String trimmedValue; // stores trimmed value. this value is used for getting and setting value to DB
public static boolean isEBSDIC = false;
private DefaultValue defaultValue;
/**
* Use this constructor if you need to make PT variable quickly. For example if
* you have numeric constant and need to make it PT variable to use in the
* calculations
*
* Do not use this constructor to declare PT variable that is going to be used
* not just in the calculation.
*
* @param value value of PT variable
*/
public PictureType(T value) { // can be used only for calculation and value
this.value = value;
}
/**
* Default constructor for PT variable
*
* @param type indicates type of variable
* @param format object that manage displaying of variables
*/
public PictureType(Type type, Format format) {
this(type, format, Spaces); // bu default value is Spaces
trimmedValue = null;
}
/**
* Constructor for PT variable with value for initialization
*
* @param format object that manage displaying of variables
* @param value value of PT variable. also indicates type variable.
*/
public PictureType(Format format, T value) {
this.type = value;
this.format = format;
setValue(value);
initTrimmedValue(value.toString());
}
/**
* Constructor for PT variable with defaultValue for initialization
*
* @param type indicates type of variable
* @param format object that manage displaying of variables
* @param defaultValue object for initialization.
*/
public PictureType(Type type, Format format, DefaultValue defaultValue) {
this.format = format;
getTypedValue(type);
setDefaultValue(defaultValue); | if (format instanceof DecimalFormat && ((DecimalFormat) format).getCompType() != null) { | 1 | 2023-12-13 14:56:32+00:00 | 8k |
blueokanna/ReverseCoin | src/main/java/ReverseCoinBlockChainGeneration/MiningReverseCoinBlock.java | [
{
"identifier": "CommandCode",
"path": "src/main/java/BlockModel/CommandCode.java",
"snippet": "public enum CommandCode {\n /*\n 查询最后一个区块\n */\n CheckLastestBlock(100),\n /*\n 查询整个区块链\n */\n CheckWholeChain(101),\n /*\n 返回一个最新的区块\n */\n ReturnLastestBlock(102),\n... | import BlockModel.CommandCode;
import BlockModel.PeerMessages;
import BlockModel.PerformRingSign;
import BlockModel.ReverseCoinBlock;
import BlockModel.ReverseCoinTransaction;
import BlockModel.TimeStampGenerator;
import ReverseCoinChainNetwork.P2PNetwork;
import com.google.gson.GsonBuilder;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.CompletionService;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import ConnectionAPI.NewReverseCoinBlockInterface;
import ConnectionAPI.ReverseCoinChainConfigInterface; | 5,011 | package ReverseCoinBlockChainGeneration;
public class MiningReverseCoinBlock {
private volatile long times = new TimeStampGenerator().TimeToSync();
private volatile int numberGenerations;
private volatile long nonce;
private volatile ExecutorService executor;
private volatile ReverseCoinBlock blocks = new ReverseCoinBlock();
| package ReverseCoinBlockChainGeneration;
public class MiningReverseCoinBlock {
private volatile long times = new TimeStampGenerator().TimeToSync();
private volatile int numberGenerations;
private volatile long nonce;
private volatile ExecutorService executor;
private volatile ReverseCoinBlock blocks = new ReverseCoinBlock();
| public ReverseCoinBlock mineBlock(NewReverseCoinBlockInterface addnewblock, ReverseCoinChainConfigInterface config) { | 8 | 2023-12-11 05:18:04+00:00 | 8k |
Patbox/PolyDecorations | src/main/java/eu/pb4/polydecorations/block/DecorationsBlockEntities.java | [
{
"identifier": "ModInit",
"path": "src/main/java/eu/pb4/polydecorations/ModInit.java",
"snippet": "public class ModInit implements ModInitializer {\n\tpublic static final String ID = \"polydecorations\";\n\tpublic static final String VERSION = FabricLoader.getInstance().getModContainer(ID).get().getMet... | import eu.pb4.polydecorations.ModInit;
import eu.pb4.polydecorations.block.item.ShelfBlock;
import eu.pb4.polydecorations.block.item.ShelfBlockEntity;
import eu.pb4.polydecorations.block.other.GenericSingleItemBlockEntity;
import eu.pb4.polydecorations.block.extension.SignPostBlock;
import eu.pb4.polydecorations.block.extension.SignPostBlockEntity;
import eu.pb4.polymer.core.api.block.PolymerBlockUtils;
import net.fabricmc.fabric.api.object.builder.v1.block.entity.FabricBlockEntityTypeBuilder;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.block.entity.BlockEntityType;
import net.minecraft.registry.Registries;
import net.minecraft.registry.Registry;
import net.minecraft.util.Identifier; | 7,073 | package eu.pb4.polydecorations.block;
public class DecorationsBlockEntities {
public static final BlockEntityType<?> SHELF = register("shelf",
FabricBlockEntityTypeBuilder.create(ShelfBlockEntity::new)
.addBlocks(DecorationsBlocks.SHELF.values().toArray(new ShelfBlock[0])));
;
public static final BlockEntityType<?> SIGN_POST = register("sign_post",
FabricBlockEntityTypeBuilder.create(SignPostBlockEntity::new)
.addBlocks(DecorationsBlocks.SIGN_POST.values().toArray(new SignPostBlock[0])));
public static final BlockEntityType<?> GLOBE = register("globe",
FabricBlockEntityTypeBuilder.create(GenericSingleItemBlockEntity::globe).addBlock(DecorationsBlocks.GLOBE));
;
public static final BlockEntityType<?> DISPLAY_CASE = register("display_case",
FabricBlockEntityTypeBuilder.create(GenericSingleItemBlockEntity::displayCase).addBlock(DecorationsBlocks.DISPLAY_CASE));
;
//public static final BlockEntityType<?> BANNER_BED = register("banner_bed",
// FabricBlockEntityTypeBuilder.create(BedWithBannerBlockEntity::new)
// .addBlocks(DecorationsBlocks.BANNER_BED.values().toArray(new BedWithBannerBlock[0])));
;
public static <T extends BlockEntity> BlockEntityType<T> register(String path, FabricBlockEntityTypeBuilder<T> item) { | package eu.pb4.polydecorations.block;
public class DecorationsBlockEntities {
public static final BlockEntityType<?> SHELF = register("shelf",
FabricBlockEntityTypeBuilder.create(ShelfBlockEntity::new)
.addBlocks(DecorationsBlocks.SHELF.values().toArray(new ShelfBlock[0])));
;
public static final BlockEntityType<?> SIGN_POST = register("sign_post",
FabricBlockEntityTypeBuilder.create(SignPostBlockEntity::new)
.addBlocks(DecorationsBlocks.SIGN_POST.values().toArray(new SignPostBlock[0])));
public static final BlockEntityType<?> GLOBE = register("globe",
FabricBlockEntityTypeBuilder.create(GenericSingleItemBlockEntity::globe).addBlock(DecorationsBlocks.GLOBE));
;
public static final BlockEntityType<?> DISPLAY_CASE = register("display_case",
FabricBlockEntityTypeBuilder.create(GenericSingleItemBlockEntity::displayCase).addBlock(DecorationsBlocks.DISPLAY_CASE));
;
//public static final BlockEntityType<?> BANNER_BED = register("banner_bed",
// FabricBlockEntityTypeBuilder.create(BedWithBannerBlockEntity::new)
// .addBlocks(DecorationsBlocks.BANNER_BED.values().toArray(new BedWithBannerBlock[0])));
;
public static <T extends BlockEntity> BlockEntityType<T> register(String path, FabricBlockEntityTypeBuilder<T> item) { | var x = Registry.register(Registries.BLOCK_ENTITY_TYPE, new Identifier(ModInit.ID, path), item.build()); | 0 | 2023-12-10 16:20:36+00:00 | 8k |
i-moonlight/Movie_Manager | backend/src/main/java/ch/xxx/moviemanager/adapter/controller/MovieController.java | [
{
"identifier": "ResourceNotFoundException",
"path": "backend/src/main/java/ch/xxx/moviemanager/domain/exceptions/ResourceNotFoundException.java",
"snippet": "public class ResourceNotFoundException extends RuntimeException {\n\n\tprivate static final long serialVersionUID = -4246075150244552193L;\n\t\n\... | import java.util.List;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import ch.xxx.moviemanager.domain.exceptions.ResourceNotFoundException;
import ch.xxx.moviemanager.domain.model.dto.MovieFilterCriteriaDto;
import ch.xxx.moviemanager.domain.model.dto.GenereDto;
import ch.xxx.moviemanager.domain.model.dto.MovieDto;
import ch.xxx.moviemanager.domain.model.dto.SearchTermDto;
import ch.xxx.moviemanager.usecase.mapper.DefaultMapper;
import ch.xxx.moviemanager.usecase.service.MovieService; | 5,918 | /**
* Copyright 2019 Sven Loesekann
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 ch.xxx.moviemanager.adapter.controller;
@RestController
@RequestMapping("rest/movie")
public class MovieController {
private final MovieService service;
private final DefaultMapper mapper;
public MovieController(MovieService service, DefaultMapper mapper) {
this.service = service;
this.mapper = mapper;
}
@RequestMapping(value = "/{title}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) | /**
* Copyright 2019 Sven Loesekann
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 ch.xxx.moviemanager.adapter.controller;
@RestController
@RequestMapping("rest/movie")
public class MovieController {
private final MovieService service;
private final DefaultMapper mapper;
public MovieController(MovieService service, DefaultMapper mapper) {
this.service = service;
this.mapper = mapper;
}
@RequestMapping(value = "/{title}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) | public List<MovieDto> getMovieSearch(@RequestHeader(value = HttpHeaders.AUTHORIZATION) String bearerStr, | 3 | 2023-12-11 13:53:51+00:00 | 8k |
i-moonlight/Suricate | src/main/java/com/michelin/suricate/security/ldap/LdapAuthentication.java | [
{
"identifier": "User",
"path": "src/main/java/com/michelin/suricate/model/entities/User.java",
"snippet": "@Entity\n@Table(name = \"users\")\n@Getter\n@Setter\n@ToString\n@NoArgsConstructor\npublic class User extends AbstractEntity<Long> {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTIT... | import com.michelin.suricate.model.entities.User;
import com.michelin.suricate.properties.ApplicationProperties;
import com.michelin.suricate.security.LocalUser;
import com.michelin.suricate.services.api.UserService;
import com.michelin.suricate.utils.exceptions.ConfigurationException;
import jakarta.annotation.PostConstruct;
import java.util.Collections;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.ldap.core.AuthenticationSource;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.ldap.DefaultSpringSecurityContextSource;
import org.springframework.security.ldap.authentication.BindAuthenticator;
import org.springframework.security.ldap.authentication.LdapAuthenticationProvider;
import org.springframework.security.ldap.search.FilterBasedLdapUserSearch;
import org.springframework.security.ldap.userdetails.LdapUserDetailsMapper;
import org.springframework.security.ldap.userdetails.UserDetailsContextMapper; | 4,338 | /*
* 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.security.ldap;
/**
* Ldap authentication configuration.
*/
@Configuration
@ConditionalOnProperty(name = "application.authentication.provider", havingValue = "ldap")
public class LdapAuthentication {
@Autowired
private UserService userService;
@Autowired
private ApplicationProperties applicationProperties;
@PostConstruct
private void checkLdapConfiguration() {
if (StringUtils.isBlank(applicationProperties.getAuthentication().getLdap().getUrl())) { | /*
* 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.security.ldap;
/**
* Ldap authentication configuration.
*/
@Configuration
@ConditionalOnProperty(name = "application.authentication.provider", havingValue = "ldap")
public class LdapAuthentication {
@Autowired
private UserService userService;
@Autowired
private ApplicationProperties applicationProperties;
@PostConstruct
private void checkLdapConfiguration() {
if (StringUtils.isBlank(applicationProperties.getAuthentication().getLdap().getUrl())) { | throw new ConfigurationException("The Ldap url is mandatory when the provider is ldap", | 4 | 2023-12-11 11:28:37+00:00 | 8k |
NaerQAQ/js4bukkit | src/main/java/org/js4bukkit/Js4Bukkit.java | [
{
"identifier": "AnnotatedClassProcessor",
"path": "src/main/java/org/js4bukkit/annotations/processors/AnnotatedClassProcessor.java",
"snippet": "@UtilityClass\npublic class AnnotatedClassProcessor {\n /**\n * 获取带有指定注解的类集合。\n *\n * @param annotation 要查找的注解类的 Class 对象\n * @return 包含所有带... | import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.bukkit.plugin.java.JavaPlugin;
import org.js4bukkit.annotations.processors.AnnotatedClassProcessor;
import org.js4bukkit.io.config.ConfigManager;
import org.js4bukkit.script.ScriptHandler;
import org.js4bukkit.script.thirdparty.MavenDependencyLoader;
import org.js4bukkit.script.thirdparty.ThirdPartyJarLoader;
import org.js4bukkit.utils.common.text.QuickUtils;
import org.js4bukkit.utils.common.text.enums.ConsoleMessageTypeEnum;
import java.util.Arrays; | 5,163 | package org.js4bukkit;
/**
* 该类继承 {@link JavaPlugin},插件主类。
*
* @author NaerQAQ / 2000000
* @version 1.0
* @since 2023/10/7
*/
public class Js4Bukkit extends JavaPlugin {
/**
* 实例。
*/
@Getter
@Setter
private static Js4Bukkit instance;
/**
* 服务器版本。
*/
@Getter
@Setter
private static Double serverVersion;
/**
* 插件配置文件夹路径。
*/
@Getter
@Setter
private static String dataFolderAbsolutePath;
@Getter
@Setter
private static String nmsVersion;
/**
* 插件开启。
*
* @author 2000000
*/
@Override
@SneakyThrows
@SuppressWarnings("ResultOfMethodCallIgnored")
public void onEnable() {
setInstance(this);
setDataFolderAbsolutePath(getDataFolder().getAbsolutePath());
String serverPackage =
getServer().getClass().getPackage().getName();
setNmsVersion(
serverPackage.replace(".", ",").split(",")[3]
);
String[] arrayVersion = StringUtils.substringsBetween(
serverPackage, ".v", "_R"
);
String stringVersion = Arrays.toString(arrayVersion)
.replace("_", "0")
.replace("[", "")
.replace("]", "");
setServerVersion(
Double.parseDouble(stringVersion)
);
// 配置文件与注解处理
ConfigManager.getConfig(); | package org.js4bukkit;
/**
* 该类继承 {@link JavaPlugin},插件主类。
*
* @author NaerQAQ / 2000000
* @version 1.0
* @since 2023/10/7
*/
public class Js4Bukkit extends JavaPlugin {
/**
* 实例。
*/
@Getter
@Setter
private static Js4Bukkit instance;
/**
* 服务器版本。
*/
@Getter
@Setter
private static Double serverVersion;
/**
* 插件配置文件夹路径。
*/
@Getter
@Setter
private static String dataFolderAbsolutePath;
@Getter
@Setter
private static String nmsVersion;
/**
* 插件开启。
*
* @author 2000000
*/
@Override
@SneakyThrows
@SuppressWarnings("ResultOfMethodCallIgnored")
public void onEnable() {
setInstance(this);
setDataFolderAbsolutePath(getDataFolder().getAbsolutePath());
String serverPackage =
getServer().getClass().getPackage().getName();
setNmsVersion(
serverPackage.replace(".", ",").split(",")[3]
);
String[] arrayVersion = StringUtils.substringsBetween(
serverPackage, ".v", "_R"
);
String stringVersion = Arrays.toString(arrayVersion)
.replace("_", "0")
.replace("[", "")
.replace("]", "");
setServerVersion(
Double.parseDouble(stringVersion)
);
// 配置文件与注解处理
ConfigManager.getConfig(); | AnnotatedClassProcessor.processAnnotatedClasses(); | 0 | 2023-12-14 13:50:24+00:00 | 8k |
keyboardcat1/Erosio | src/test/java/Demo.java | [
{
"identifier": "Eroder",
"path": "src/main/java/com/github/keyboardcat1/erosio/Eroder.java",
"snippet": "public class Eroder {\n\n /**\n * Computes an eroded heightmap\n *\n * @param settings The parameters of the erosion algorithm\n * @param eroderGeometry The Voronoi tessell... | import com.github.keyboardcat1.erosio.Eroder;
import com.github.keyboardcat1.erosio.EroderGeometry;
import com.github.keyboardcat1.erosio.EroderResults;
import com.github.keyboardcat1.erosio.EroderSettings;
import com.github.keyboardcat1.erosio.geometries.EroderGeometryNatural;
import com.github.keyboardcat1.erosio.interpolation.Interpolator;
import com.github.keyboardcat1.erosio.interpolation.InterpolatorIDW;
import org.kynosarges.tektosyne.geometry.RectI;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException; | 6,095 |
public class Demo {
public static void main(String[] args) throws IOException {
RectI bounds = new RectI(-256, -256, 256, 256);
EroderSettings settings = new EroderSettings(
p -> 1.0, p -> 0.0,
2.0, 0.5,
(p,h) -> 30.0,
1, 10, 1E-2
); |
public class Demo {
public static void main(String[] args) throws IOException {
RectI bounds = new RectI(-256, -256, 256, 256);
EroderSettings settings = new EroderSettings(
p -> 1.0, p -> 0.0,
2.0, 0.5,
(p,h) -> 30.0,
1, 10, 1E-2
); | EroderGeometry eroderGeometry = new EroderGeometryNatural(bounds.toRectD(), 2, 2); | 3 | 2023-12-07 16:29:18+00:00 | 8k |
litongjava/ai-server | paddle-ocr/paddle-ocr-service/src/main/java/com/litongjava/ai/djl/paddle/ocr/v4/recognition/OcrV4Recognition.java | [
{
"identifier": "RotatedBox",
"path": "paddle-ocr/paddle-ocr-service/src/main/java/com/litongjava/ai/djl/paddle/ocr/v4/common/RotatedBox.java",
"snippet": "public class RotatedBox implements Comparable<RotatedBox> {\n private NDArray box;\n private String text;\n\n public RotatedBox(NDArray box, Stri... | import java.awt.image.BufferedImage;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import org.opencv.core.Mat;
import com.litongjava.ai.djl.paddle.ocr.v4.common.RotatedBox;
import com.litongjava.ai.djl.paddle.ocr.v4.opencv.NDArrayUtils;
import com.litongjava.ai.djl.paddle.ocr.v4.opencv.OpenCVUtils;
import ai.djl.Device;
import ai.djl.inference.Predictor;
import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.ImageFactory;
import ai.djl.modality.cv.output.Point;
import ai.djl.modality.cv.util.NDImageUtils;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDList;
import ai.djl.ndarray.NDManager;
import ai.djl.opencv.OpenCVImageFactory;
import ai.djl.repository.zoo.Criteria;
import ai.djl.repository.zoo.Criteria.Builder;
import ai.djl.training.util.ProgressBar;
import ai.djl.translate.TranslateException;
import cn.hutool.core.io.resource.ResourceUtil; | 3,670 | package com.litongjava.ai.djl.paddle.ocr.v4.recognition;
/**
* 文字识别
*/
public final class OcrV4Recognition {
/**
* 中文简体
*
* @return
*/
public Criteria<Image, String> chRecCriteria() {
URL resource = ResourceUtil.getResource("models/ch_PP-OCRv4_rec_infer.zip");
System.out.println("resource:" + resource);
Path modelPath = null;
try {
modelPath = Paths.get(resource.toURI());
} catch (Exception e) {
System.err.println(e.getMessage());
}
Device device = Device.gpu();
Builder<Image, String> builder = Criteria.builder()
// engine
.optEngine("OnnxRuntime")
// .optEngine("PyTorch")
// .optModelName("inference")
// devices
.optDevice(device)
// type
.setTypes(Image.class, String.class).optProgress(new ProgressBar())
.optTranslator(new PpWordRecTranslator(new ConcurrentHashMap<String, String>()));
if (modelPath != null) {
System.out.println("load from file");
builder.optModelPath(modelPath).optModelName("ch_PP-OCRv4_det_infer");
} else {
System.out.println("load from jar");
builder.optModelUrls("jar:///models/ch_PP-OCRv4_rec_infer.zip");
}
return builder.build();
}
/**
* 图像推理
*
* @param manager
* @param image
* @param detector
* @param recognizer
* @return
* @throws TranslateException
*/
public List<RotatedBox> predict(NDManager manager, Image image, Predictor<Image, NDList> detector,
Predictor<Image, String> recognizer) throws TranslateException {
NDList boxes = detector.predict(image);
if (boxes == null) {
return null;
}
// 交给 NDManager自动管理内存
// attach to manager for automatic memory management
boxes.attach(manager);
List<RotatedBox> result = new ArrayList<>();
Mat mat = (Mat) image.getWrappedImage();
for (int i = 0; i < boxes.size(); i++) {
NDArray box = boxes.get(i);
float[] pointsArr = box.toFloatArray();
float[] lt = java.util.Arrays.copyOfRange(pointsArr, 0, 2);
float[] rt = java.util.Arrays.copyOfRange(pointsArr, 2, 4);
float[] rb = java.util.Arrays.copyOfRange(pointsArr, 4, 6);
float[] lb = java.util.Arrays.copyOfRange(pointsArr, 6, 8);
int img_crop_width = (int) Math.max(distance(lt, rt), distance(rb, lb));
int img_crop_height = (int) Math.max(distance(lt, lb), distance(rt, rb));
List<Point> srcPoints = new ArrayList<>();
srcPoints.add(new Point(lt[0], lt[1]));
srcPoints.add(new Point(rt[0], rt[1]));
srcPoints.add(new Point(rb[0], rb[1]));
srcPoints.add(new Point(lb[0], lb[1]));
List<Point> dstPoints = new ArrayList<>();
dstPoints.add(new Point(0, 0));
dstPoints.add(new Point(img_crop_width, 0));
dstPoints.add(new Point(img_crop_width, img_crop_height));
dstPoints.add(new Point(0, img_crop_height));
Mat srcPoint2f = NDArrayUtils.toMat(srcPoints);
Mat dstPoint2f = NDArrayUtils.toMat(dstPoints);
| package com.litongjava.ai.djl.paddle.ocr.v4.recognition;
/**
* 文字识别
*/
public final class OcrV4Recognition {
/**
* 中文简体
*
* @return
*/
public Criteria<Image, String> chRecCriteria() {
URL resource = ResourceUtil.getResource("models/ch_PP-OCRv4_rec_infer.zip");
System.out.println("resource:" + resource);
Path modelPath = null;
try {
modelPath = Paths.get(resource.toURI());
} catch (Exception e) {
System.err.println(e.getMessage());
}
Device device = Device.gpu();
Builder<Image, String> builder = Criteria.builder()
// engine
.optEngine("OnnxRuntime")
// .optEngine("PyTorch")
// .optModelName("inference")
// devices
.optDevice(device)
// type
.setTypes(Image.class, String.class).optProgress(new ProgressBar())
.optTranslator(new PpWordRecTranslator(new ConcurrentHashMap<String, String>()));
if (modelPath != null) {
System.out.println("load from file");
builder.optModelPath(modelPath).optModelName("ch_PP-OCRv4_det_infer");
} else {
System.out.println("load from jar");
builder.optModelUrls("jar:///models/ch_PP-OCRv4_rec_infer.zip");
}
return builder.build();
}
/**
* 图像推理
*
* @param manager
* @param image
* @param detector
* @param recognizer
* @return
* @throws TranslateException
*/
public List<RotatedBox> predict(NDManager manager, Image image, Predictor<Image, NDList> detector,
Predictor<Image, String> recognizer) throws TranslateException {
NDList boxes = detector.predict(image);
if (boxes == null) {
return null;
}
// 交给 NDManager自动管理内存
// attach to manager for automatic memory management
boxes.attach(manager);
List<RotatedBox> result = new ArrayList<>();
Mat mat = (Mat) image.getWrappedImage();
for (int i = 0; i < boxes.size(); i++) {
NDArray box = boxes.get(i);
float[] pointsArr = box.toFloatArray();
float[] lt = java.util.Arrays.copyOfRange(pointsArr, 0, 2);
float[] rt = java.util.Arrays.copyOfRange(pointsArr, 2, 4);
float[] rb = java.util.Arrays.copyOfRange(pointsArr, 4, 6);
float[] lb = java.util.Arrays.copyOfRange(pointsArr, 6, 8);
int img_crop_width = (int) Math.max(distance(lt, rt), distance(rb, lb));
int img_crop_height = (int) Math.max(distance(lt, lb), distance(rt, rb));
List<Point> srcPoints = new ArrayList<>();
srcPoints.add(new Point(lt[0], lt[1]));
srcPoints.add(new Point(rt[0], rt[1]));
srcPoints.add(new Point(rb[0], rb[1]));
srcPoints.add(new Point(lb[0], lb[1]));
List<Point> dstPoints = new ArrayList<>();
dstPoints.add(new Point(0, 0));
dstPoints.add(new Point(img_crop_width, 0));
dstPoints.add(new Point(img_crop_width, img_crop_height));
dstPoints.add(new Point(0, img_crop_height));
Mat srcPoint2f = NDArrayUtils.toMat(srcPoints);
Mat dstPoint2f = NDArrayUtils.toMat(dstPoints);
| Mat cvMat = OpenCVUtils.perspectiveTransform(mat, srcPoint2f, dstPoint2f); | 2 | 2023-12-13 15:12:36+00:00 | 8k |
i-moonlight/Beluga | server/src/main/java/com/amnesica/belugaproject/controllers/Controller.java | [
{
"identifier": "AircraftSuperclass",
"path": "server/src/main/java/com/amnesica/belugaproject/entities/aircraft/AircraftSuperclass.java",
"snippet": "@Data\n@JsonInclude(JsonInclude.Include.NON_NULL)\n@MappedSuperclass\n@TypeDefs({@TypeDef(name = \"string-array\", typeClass = StringArrayType.class),\n ... | import com.amnesica.belugaproject.entities.aircraft.AircraftSuperclass;
import com.amnesica.belugaproject.entities.data.AirportData;
import com.amnesica.belugaproject.entities.data.RangeData;
import com.amnesica.belugaproject.entities.trails.AircraftTrail;
import com.amnesica.belugaproject.entities.trails.SpacecraftTrail;
import com.amnesica.belugaproject.services.aircraft.*;
import com.amnesica.belugaproject.services.data.*;
import com.amnesica.belugaproject.services.helper.DebugService;
import com.amnesica.belugaproject.services.trails.AircraftTrailService;
import com.amnesica.belugaproject.services.trails.SpacecraftTrailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.HashMap;
import java.util.List; | 6,544 | package com.amnesica.belugaproject.controllers;
@RestController
@CrossOrigin
public class Controller {
@Autowired
private FeederService feederService;
@Autowired
private LocalFeederService localFeederService;
@Autowired
private OpenskyService openskyService;
@Autowired
private SpacecraftService spacecraftService;
@Autowired
private AircraftService aircraftService;
@Autowired
private AirportDataService airportDataService;
@Autowired
private RangeDataService rangeDataService;
@Autowired
private HistoryAircraftService historyAircraftService;
@Autowired
private SpacecraftTrailService spacecraftTrailService;
@Autowired
private AircraftTrailService aircraftTrailService;
@Autowired
private ShapeDataService shapeDataService;
@Autowired
private MapCatToShapeDataService mapCatToShapeDataService;
@Autowired
private MapTypeToShapeDataService mapTypeToShapeDataService;
@Autowired
private DebugService debugService;
/**
* Gibt die Konfiguration nur mit den nötigsten Variablen zurück
*
* @return Configuration
*/
@GetMapping(value = "/getConfigurationData", produces = "application/json")
public @ResponseBody
HashMap<String, Object> getConfigurationData(HttpServletRequest httpRequest) {
return feederService.getConfiguration(httpRequest);
}
/**
* Gibt Flugzeuge innerhalb eines Extents zurück
*
* @param lomin lower bound for the longitude in decimal degrees
* @param lamin lower bound for the latitude in decimal degrees
* @param lomax upper bound for the longitude in decimal degrees
* @param lamax upper bound for the latitude in decimal degrees
* @param selectedFeeder Ausgewählter Feeder (oder 'AllFeeder')
* @param fetchFromOpensky Boolean, ob Opensky angefragt werden soll
* @param showIss Boolean, ob ISS abgefragt werden soll
* @return Collection<AircraftSuperclass>
*/
@GetMapping(value = "/getAircraftList", produces = "application/json")
public @ResponseBody | package com.amnesica.belugaproject.controllers;
@RestController
@CrossOrigin
public class Controller {
@Autowired
private FeederService feederService;
@Autowired
private LocalFeederService localFeederService;
@Autowired
private OpenskyService openskyService;
@Autowired
private SpacecraftService spacecraftService;
@Autowired
private AircraftService aircraftService;
@Autowired
private AirportDataService airportDataService;
@Autowired
private RangeDataService rangeDataService;
@Autowired
private HistoryAircraftService historyAircraftService;
@Autowired
private SpacecraftTrailService spacecraftTrailService;
@Autowired
private AircraftTrailService aircraftTrailService;
@Autowired
private ShapeDataService shapeDataService;
@Autowired
private MapCatToShapeDataService mapCatToShapeDataService;
@Autowired
private MapTypeToShapeDataService mapTypeToShapeDataService;
@Autowired
private DebugService debugService;
/**
* Gibt die Konfiguration nur mit den nötigsten Variablen zurück
*
* @return Configuration
*/
@GetMapping(value = "/getConfigurationData", produces = "application/json")
public @ResponseBody
HashMap<String, Object> getConfigurationData(HttpServletRequest httpRequest) {
return feederService.getConfiguration(httpRequest);
}
/**
* Gibt Flugzeuge innerhalb eines Extents zurück
*
* @param lomin lower bound for the longitude in decimal degrees
* @param lamin lower bound for the latitude in decimal degrees
* @param lomax upper bound for the longitude in decimal degrees
* @param lamax upper bound for the latitude in decimal degrees
* @param selectedFeeder Ausgewählter Feeder (oder 'AllFeeder')
* @param fetchFromOpensky Boolean, ob Opensky angefragt werden soll
* @param showIss Boolean, ob ISS abgefragt werden soll
* @return Collection<AircraftSuperclass>
*/
@GetMapping(value = "/getAircraftList", produces = "application/json")
public @ResponseBody | Collection<AircraftSuperclass> getAircraftList(@RequestParam(value = "lomin") double lomin, | 0 | 2023-12-11 11:37:46+00:00 | 8k |
fiber-net-gateway/fiber-net-gateway | fiber-gateway-proxy/src/main/java/io/fiber/net/proxy/lib/ExtensiveHttpLib.java | [
{
"identifier": "Injector",
"path": "fiber-gateway-common/src/main/java/io/fiber/net/common/ioc/Injector.java",
"snippet": "public abstract class Injector {\n public static Injector getRoot() {\n return RootInjector.INSTANCE;\n }\n\n public abstract Injector getParent();\n\n public ab... | import io.fiber.net.common.ioc.Injector;
import io.fiber.net.common.utils.ArrayUtils;
import io.fiber.net.http.HttpClient;
import io.fiber.net.http.HttpHost;
import io.fiber.net.proxy.HttpLibConfigure;
import io.fiber.net.script.ast.Literal;
import io.fiber.net.script.std.StdLibrary;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | 4,669 | package io.fiber.net.proxy.lib;
public class ExtensiveHttpLib extends StdLibrary {
final Injector injector;
final HttpLibConfigure[] configures;
private static Map<String, Function> getFuncMap() {
HashMap<String, Function> map = new HashMap<>();
map.putAll(StdLibrary.getDefFuncMap());
map.putAll(ReqFunc.FC_MAP);
map.putAll(RespFunc.FC_MAP);
return map;
}
public ExtensiveHttpLib(Injector injector, HttpLibConfigure[] configures) {
super(getFuncMap());
this.injector = injector;
this.configures = configures;
}
public void registerFunc(String name, Function fc, boolean override) {
if (override) {
functionMap.put(name, fc);
} else {
functionMap.putIfAbsent(name, fc);
}
}
@Override
public Constant findConstant(String namespace, String key) {
if (ArrayUtils.isNotEmpty(configures)) {
for (HttpLibConfigure configure : configures) {
Constant def = configure.findConst(namespace, key);
if (def != null) {
return def;
}
}
}
return null;
}
@Override
public DirectiveDef findDirectiveDef(String type, String name, List<Literal> literals) {
if (ArrayUtils.isNotEmpty(configures)) {
for (HttpLibConfigure configure : configures) {
DirectiveDef def = configure.findDirectiveDef(type, name, literals);
if (def != null) {
return def;
}
}
}
if ("http".equals(type)) {
HttpHost httpHost = HttpHost.create(literals.get(0).getLiteralValue().textValue()); | package io.fiber.net.proxy.lib;
public class ExtensiveHttpLib extends StdLibrary {
final Injector injector;
final HttpLibConfigure[] configures;
private static Map<String, Function> getFuncMap() {
HashMap<String, Function> map = new HashMap<>();
map.putAll(StdLibrary.getDefFuncMap());
map.putAll(ReqFunc.FC_MAP);
map.putAll(RespFunc.FC_MAP);
return map;
}
public ExtensiveHttpLib(Injector injector, HttpLibConfigure[] configures) {
super(getFuncMap());
this.injector = injector;
this.configures = configures;
}
public void registerFunc(String name, Function fc, boolean override) {
if (override) {
functionMap.put(name, fc);
} else {
functionMap.putIfAbsent(name, fc);
}
}
@Override
public Constant findConstant(String namespace, String key) {
if (ArrayUtils.isNotEmpty(configures)) {
for (HttpLibConfigure configure : configures) {
Constant def = configure.findConst(namespace, key);
if (def != null) {
return def;
}
}
}
return null;
}
@Override
public DirectiveDef findDirectiveDef(String type, String name, List<Literal> literals) {
if (ArrayUtils.isNotEmpty(configures)) {
for (HttpLibConfigure configure : configures) {
DirectiveDef def = configure.findDirectiveDef(type, name, literals);
if (def != null) {
return def;
}
}
}
if ("http".equals(type)) {
HttpHost httpHost = HttpHost.create(literals.get(0).getLiteralValue().textValue()); | return new HttpFunc(httpHost, injector.getInstance(HttpClient.class)); | 2 | 2023-12-08 15:18:05+00:00 | 8k |
sigbla/sigbla-pds | src/main/java/sigbla/app/pds/collection/Vector.java | [
{
"identifier": "AbstractIndexedList",
"path": "src/main/java/sigbla/app/pds/collection/internal/base/AbstractIndexedList.java",
"snippet": "public abstract class AbstractIndexedList<E> extends AbstractList<E> implements IndexedList<E> {\n}"
},
{
"identifier": "AbstractBuilder",
"path": "src... | import sigbla.app.pds.collection.internal.base.AbstractIndexedList;
import sigbla.app.pds.collection.internal.builder.AbstractBuilder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Iterator;
import java.util.NoSuchElementException; | 4,037 | display1[(oldIndex >> 5) & 31] = display0;
display2[(oldIndex >> 10) & 31] = display1;
display3[(oldIndex >> 15) & 31] = display2;
display4[(oldIndex >> 20) & 31] = display3;
display3 = nullSlotAndCopy(display4, (newIndex >> 20) & 31);
display2 = nullSlotAndCopy(display3, (newIndex >> 15) & 31);
display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31);
display0 = nullSlotAndCopy(display1, (newIndex >> 5) & 31);
} else if (xor < (1 << 30)) { // level = 5
display1 = copyOf(display1);
display2 = copyOf(display2);
display3 = copyOf(display3);
display4 = copyOf(display4);
display5 = copyOf(display5);
display1[(oldIndex >> 5) & 31] = display0;
display2[(oldIndex >> 10) & 31] = display1;
display3[(oldIndex >> 15) & 31] = display2;
display4[(oldIndex >> 20) & 31] = display3;
display5[(oldIndex >> 25) & 31] = display4;
display4 = nullSlotAndCopy(display5, (newIndex >> 25) & 31);
display3 = nullSlotAndCopy(display4, (newIndex >> 20) & 31);
display2 = nullSlotAndCopy(display3, (newIndex >> 15) & 31);
display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31);
display0 = nullSlotAndCopy(display1, (newIndex >> 5) & 31);
} else { // level = 6
throw new IllegalArgumentException();
}
}
// USED IN DROP
public Object[] copyRange(Object[] array, int oldLeft, int newLeft) {
Object[] elems = new Object[32];
System.arraycopy(array, oldLeft, elems, newLeft, 32 - Math.max(newLeft, oldLeft));
return elems;
}
// USED IN APPEND
// create a new block at the bottom level (and possibly nodes on its path) and prepares for writing
// requires structure is clean and at pos oldIndex,
// ensures structure is dirty and at pos newIndex and writable at level 0
public void gotoFreshPosWritable0(int oldIndex, int newIndex, int xor) { // goto block start pos
//noinspection StatementWithEmptyBody
if (xor < (1 << 5)) { // level = 0
} else if (xor < (1 << 10)) { // level = 1
if (depth == 1) {
display1 = new Object[32];
display1[(oldIndex >> 5) & 31] = display0;
depth += 1;
}
display0 = new Object[32];
} else if (xor < (1 << 15)) { // level = 2
if (depth == 2) {
display2 = new Object[32];
display2[(oldIndex >> 10) & 31] = display1;
depth += 1;
}
display1 = (Object[]) display2[(newIndex >> 10) & 31];
if (display1 == null) display1 = new Object[32];
display0 = new Object[32];
} else if (xor < (1 << 20)) { // level = 3
if (depth == 3) {
display3 = new Object[32];
display3[(oldIndex >> 15) & 31] = display2;
display2 = new Object[32];
display1 = new Object[32];
depth += 1;
}
display2 = (Object[]) display3[(newIndex >> 15) & 31];
if (display2 == null) display2 = new Object[32];
display1 = (Object[]) display2[(newIndex >> 10) & 31];
if (display1 == null) display1 = new Object[32];
display0 = new Object[32];
} else if (xor < (1 << 25)) { // level = 4
if (depth == 4) {
display4 = new Object[32];
display4[(oldIndex >> 20) & 31] = display3;
display3 = new Object[32];
display2 = new Object[32];
display1 = new Object[32];
depth += 1;
}
display3 = (Object[]) display4[(newIndex >> 20) & 31];
if (display3 == null) display3 = new Object[32];
display2 = (Object[]) display3[(newIndex >> 15) & 31];
if (display2 == null) display2 = new Object[32];
display1 = (Object[]) display2[(newIndex >> 10) & 31];
if (display1 == null) display1 = new Object[32];
display0 = new Object[32];
} else if (xor < (1 << 30)) { // level = 5
if (depth == 5) {
display5 = new Object[32];
display5[(oldIndex >> 25) & 31] = display4;
display4 = new Object[32];
display3 = new Object[32];
display2 = new Object[32];
display1 = new Object[32];
depth += 1;
}
display4 = (Object[]) display5[(newIndex >> 25) & 31];
if (display4 == null) display4 = new Object[32];
display3 = (Object[]) display4[(newIndex >> 20) & 31];
if (display3 == null) display3 = new Object[32];
display2 = (Object[]) display3[(newIndex >> 15) & 31];
if (display2 == null) display2 = new Object[32];
display1 = (Object[]) display2[(newIndex >> 10) & 31];
if (display1 == null) display1 = new Object[32];
display0 = new Object[32];
} else { // level = 6
throw new IllegalArgumentException();
}
}
// requires structure is dirty and at pos oldIndex,
// ensures structure is dirty and at pos newIndex and writable at level 0
public void gotoFreshPosWritable1(int oldIndex, int newIndex, int xor) {
stabilize(oldIndex);
gotoFreshPosWritable0(oldIndex, newIndex, xor);
}
}
| /*
* 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.
*/
/* __ *\
** ________ ___ / / ___ Scala API **
** / __/ __// _ | / / / _ | (c) 2003-2013, LAMP/EPFL **
** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ **
** /____/\___/_/ |_/____/_/ | | **
** |/ **
\* */
package sigbla.app.pds.collection;
/**
* Vector is a general-purpose, immutable data structure.
* <p/>
* <p>It provides random access and updates in effectively constant time, as well as very fast append and prepend.
* <p/>
* <p>It is backed by a little endian bit-mapped vector trie with a branching factor of 32. Locality is very good, but not
* contiguous, which is good for very large sequences.
* <p/>
* <p>See Scala's <a href="http://www.scala-lang.org/docu/files/collections-api/collections_15.html">documentation</a>
* for more information on the implementation.
*/
public class Vector<E> extends AbstractIndexedList<E> {
private static final Vector EMPTY = new Vector(0, 0, 0);
protected final VectorPointer<E> pointer = new VectorPointer<E>();
@NotNull
public static <E> BuilderFactory<E, Vector<E>> factory() {
return new BuilderFactory<E, Vector<E>>() {
@NotNull
@Override
public Builder<E, Vector<E>> newBuilder() {
return new VectorBuilder<E>();
}
};
}
@SuppressWarnings("unchecked")
@NotNull
public static <E> Vector<E> empty() {
return EMPTY;
}
private final int startIndex;
private final int endIndex;
private final int focus;
Vector(int startIndex, int endIndex, int focus) {
this.startIndex = startIndex;
this.endIndex = endIndex;
this.focus = focus;
}
private boolean dirty = false;
@Override
public int size() {
return endIndex - startIndex;
}
private void initIterator(VectorIterator<E> s) {
s.initFrom(pointer);
if (dirty) s.stabilize(focus);
if (s.depth > 1) s.gotoPos(startIndex, startIndex ^ focus);
}
@NotNull
@Override
public Iterator<E> iterator() {
VectorIterator<E> s = new VectorIterator<E>(startIndex, endIndex);
initIterator(s);
return s;
}
// TODO: check performance of foreach/map etc. should override or not?
// Ideally, clients will inline calls to map all the way down, including the iterator/builder methods.
// In principle, escape analysis could even remove the iterator/builder allocations and do it
// with local variables exclusively. But we're not quite there yet ...
@Override
public E get(int index) {
int idx = checkRangeConvert(index);
return pointer.getElem(idx, idx ^ focus);
}
private int checkRangeConvert(int index) {
int idx = index + startIndex;
if (0 <= index && idx < endIndex)
return idx;
else
throw new IndexOutOfBoundsException(String.valueOf(index));
}
@NotNull
@Override
public Vector<E> take(int n) {
if (n <= 0)
return Vector.empty();
else if (startIndex + n < endIndex)
return dropBack0(startIndex + n);
else
return this;
}
@NotNull
@Override
public Vector<E> drop(int n) {
if (n <= 0)
return this;
else if (startIndex + n < endIndex)
return dropFront0(startIndex + n);
else
return Vector.empty();
}
@Override
public boolean isEmpty() {
return size() == 0;
}
@Nullable
@Override
public E first() {
if (isEmpty()) return null;
return get(0);
}
@NotNull
@Override
public Vector<E> tail() {
if (isEmpty()) return this;
return drop(1);
}
@Nullable
@Override
public E last() {
if (isEmpty()) return null;
return get(size() - 1);
}
@NotNull
@Override
public Vector<E> range(int from, boolean fromInclusive, int to, boolean toInclusive) {
return slice(from + (fromInclusive ? 0 : 1), to + (toInclusive ? 1 : 0));
}
@NotNull
private Vector<E> slice(int from, int until) {
return take(until).drop(from);
}
@NotNull
protected Pair<Vector<E>, Vector<E>> splitAt(int n) {
return new Pair<Vector<E>, Vector<E>>(take(n), drop(n));
}
@NotNull
@Override
public Vector<E> set(int index, E elem) {
int idx = checkRangeConvert(index);
Vector<E> s = new Vector<E>(startIndex, endIndex, idx);
s.pointer.initFrom(pointer);
s.dirty = dirty;
s.gotoPosWritable(focus, idx, focus ^ idx); // if dirty commit changes; go to new pos and prepare for writing
s.pointer.display0[idx & 0x1f] = elem;
return s;
}
private void gotoPosWritable(int oldIndex, int newIndex, int xor) {
if (dirty) {
pointer.gotoPosWritable1(oldIndex, newIndex, xor);
} else {
pointer.gotoPosWritable0(newIndex);
dirty = true;
}
}
private void gotoFreshPosWritable(int oldIndex, int newIndex, int xor) {
if (dirty) {
pointer.gotoFreshPosWritable1(oldIndex, newIndex, xor);
} else {
pointer.gotoFreshPosWritable0(oldIndex, newIndex, xor);
dirty = true;
}
}
@NotNull
@Override
public Vector<E> prepend(E value) {
if (endIndex != startIndex) {
int blockIndex = (startIndex - 1) & ~31;
int lo = (startIndex - 1) & 31;
if (startIndex != blockIndex + 32) {
Vector<E> s = new Vector<E>(startIndex - 1, endIndex, blockIndex);
s.pointer.initFrom(pointer);
s.dirty = dirty;
s.gotoPosWritable(focus, blockIndex, focus ^ blockIndex);
s.pointer.display0[lo] = value;
return s;
} else {
int freeSpace = ((1 << 5 * (pointer.depth)) - endIndex); // free space at the right given the current tree-structure depth
int shift = freeSpace & ~((1 << 5 * (pointer.depth - 1)) - 1); // number of elements by which we'll shift right (only move at top level)
int shiftBlocks = freeSpace >>> 5 * (pointer.depth - 1); // number of top-level blocks
if (shift != 0) {
// case A: we can shift right on the top level
if (pointer.depth > 1) {
int newBlockIndex = blockIndex + shift;
int newFocus = focus + shift;
Vector<E> s = new Vector<E>(startIndex - 1 + shift, endIndex + shift, newBlockIndex);
s.pointer.initFrom(pointer);
s.dirty = dirty;
s.shiftTopLevel(0, shiftBlocks); // shift right by n blocks
s.gotoFreshPosWritable(newFocus, newBlockIndex, newFocus ^ newBlockIndex); // maybe create pos; prepare for writing
s.pointer.display0[lo] = value;
return s;
} else {
int newBlockIndex = blockIndex + 32;
int newFocus = focus;
Vector<E> s = new Vector<E>(startIndex - 1 + shift, endIndex + shift, newBlockIndex);
s.pointer.initFrom(pointer);
s.dirty = dirty;
s.shiftTopLevel(0, shiftBlocks); // shift right by n elements
s.gotoPosWritable(newFocus, newBlockIndex, newFocus ^ newBlockIndex); // prepare for writing
s.pointer.display0[shift - 1] = value;
return s;
}
} else if (blockIndex < 0) {
// case B: we need to move the whole structure
int move = (1 << 5 * (pointer.depth + 1)) - (1 << 5 * (pointer.depth));
int newBlockIndex = blockIndex + move;
int newFocus = focus + move;
Vector<E> s = new Vector<E>(startIndex - 1 + move, endIndex + move, newBlockIndex);
s.pointer.initFrom(pointer);
s.dirty = dirty;
s.gotoFreshPosWritable(newFocus, newBlockIndex, newFocus ^ newBlockIndex); // could optimize: we know it will create a whole branch
s.pointer.display0[lo] = value;
return s;
} else {
int newFocus = focus;
Vector<E> s = new Vector<E>(startIndex - 1, endIndex, blockIndex);
s.pointer.initFrom(pointer);
s.dirty = dirty;
s.gotoFreshPosWritable(newFocus, blockIndex, newFocus ^ blockIndex);
s.pointer.display0[lo] = value;
return s;
}
}
} else {
// empty vector, just insert single element at the back
Object[] elems = new Object[32];
elems[31] = value;
Vector<E> s = new Vector<E>(31, 32, 0);
s.pointer.depth = 1;
s.pointer.display0 = elems;
return s;
}
}
@NotNull
@Override
public Vector<E> append(E value) {
if (endIndex != startIndex) {
int blockIndex = endIndex & ~31;
int lo = endIndex & 31;
if (endIndex != blockIndex) {
Vector<E> s = new Vector<E>(startIndex, endIndex + 1, blockIndex);
s.pointer.initFrom(pointer);
s.dirty = dirty;
s.gotoPosWritable(focus, blockIndex, focus ^ blockIndex);
s.pointer.display0[lo] = value;
return s;
} else {
int shift = startIndex & ~((1 << 5 * (pointer.depth - 1)) - 1);
int shiftBlocks = startIndex >>> 5 * (pointer.depth - 1);
if (shift != 0) {
if (pointer.depth > 1) {
int newBlockIndex = blockIndex - shift;
int newFocus = focus - shift;
Vector<E> s = new Vector<E>(startIndex - shift, endIndex + 1 - shift, newBlockIndex);
s.pointer.initFrom(pointer);
s.dirty = dirty;
s.shiftTopLevel(shiftBlocks, 0); // shift left by n blocks
s.gotoFreshPosWritable(newFocus, newBlockIndex, newFocus ^ newBlockIndex);
s.pointer.display0[lo] = value;
return s;
} else {
int newBlockIndex = blockIndex - 32;
int newFocus = focus;
Vector<E> s = new Vector<E>(startIndex - shift, endIndex + 1 - shift, newBlockIndex);
s.pointer.initFrom(pointer);
s.dirty = dirty;
s.shiftTopLevel(shiftBlocks, 0); // shift right by n elements
s.gotoPosWritable(newFocus, newBlockIndex, newFocus ^ newBlockIndex);
s.pointer.display0[32 - shift] = value;
return s;
}
} else {
int newFocus = focus;
Vector<E> s = new Vector<E>(startIndex, endIndex + 1, blockIndex);
s.pointer.initFrom(pointer);
s.dirty = dirty;
s.gotoFreshPosWritable(newFocus, blockIndex, newFocus ^ blockIndex);
s.pointer.display0[lo] = value;
//assert(s.depth == depth+1) might or might not create new level!
return s;
}
}
} else {
Object[] elems = new Object[32];
elems[0] = value;
Vector<E> s = new Vector<E>(0, 1, 0);
s.pointer.depth = 1;
s.pointer.display0 = elems;
return s;
}
}
private void shiftTopLevel(int oldLeft, int newLeft) {
switch (pointer.depth - 1) {
case 0:
pointer.display0 = pointer.copyRange(pointer.display0, oldLeft, newLeft);
break;
case 1:
pointer.display1 = pointer.copyRange(pointer.display1, oldLeft, newLeft);
break;
case 2:
pointer.display2 = pointer.copyRange(pointer.display2, oldLeft, newLeft);
break;
case 3:
pointer.display3 = pointer.copyRange(pointer.display3, oldLeft, newLeft);
break;
case 4:
pointer.display4 = pointer.copyRange(pointer.display4, oldLeft, newLeft);
break;
case 5:
pointer.display5 = pointer.copyRange(pointer.display5, oldLeft, newLeft);
break;
default:
}
}
private void zeroLeft(Object[] array, int index) {
int i = 0;
while (i < index) {
array[i] = null;
i += 1;
}
}
private void zeroRight(Object[] array, int index) {
int i = index;
while (i < array.length) {
array[i] = null;
i += 1;
}
}
private Object[] copyLeft(Object[] array, int right) {
Object[] a2 = new Object[array.length];
System.arraycopy(array, 0, a2, 0, right);
return a2;
}
private Object[] copyRight(Object[] array, int left) {
Object[] a2 = new Object[array.length];
System.arraycopy(array, left, a2, left, a2.length - left);
return a2;
}
private void preClean(int depth) {
pointer.depth = depth;
switch (depth - 1) {
case 0:
pointer.display1 = null;
pointer.display2 = null;
pointer.display3 = null;
pointer.display4 = null;
pointer.display5 = null;
break;
case 1:
pointer.display2 = null;
pointer.display3 = null;
pointer.display4 = null;
pointer.display5 = null;
break;
case 2:
pointer.display3 = null;
pointer.display4 = null;
pointer.display5 = null;
break;
case 3:
pointer.display4 = null;
pointer.display5 = null;
break;
case 4:
pointer.display5 = null;
break;
default:
}
}
// requires structure is at index cutIndex and writable at level 0
private void cleanLeftEdge(int cutIndex) {
if (cutIndex < (1 << 5)) {
zeroLeft(pointer.display0, cutIndex);
} else if (cutIndex < (1 << 10)) {
zeroLeft(pointer.display0, cutIndex & 0x1f);
pointer.display1 = copyRight(pointer.display1, (cutIndex >>> 5));
} else if (cutIndex < (1 << 15)) {
zeroLeft(pointer.display0, cutIndex & 0x1f);
pointer.display1 = copyRight(pointer.display1, (cutIndex >>> 5) & 0x1f);
pointer.display2 = copyRight(pointer.display2, (cutIndex >>> 10));
} else if (cutIndex < (1 << 20)) {
zeroLeft(pointer.display0, cutIndex & 0x1f);
pointer.display1 = copyRight(pointer.display1, (cutIndex >>> 5) & 0x1f);
pointer.display2 = copyRight(pointer.display2, (cutIndex >>> 10) & 0x1f);
pointer.display3 = copyRight(pointer.display3, (cutIndex >>> 15));
} else if (cutIndex < (1 << 25)) {
zeroLeft(pointer.display0, cutIndex & 0x1f);
pointer.display1 = copyRight(pointer.display1, (cutIndex >>> 5) & 0x1f);
pointer.display2 = copyRight(pointer.display2, (cutIndex >>> 10) & 0x1f);
pointer.display3 = copyRight(pointer.display3, (cutIndex >>> 15) & 0x1f);
pointer.display4 = copyRight(pointer.display4, (cutIndex >>> 20));
} else if (cutIndex < (1 << 30)) {
zeroLeft(pointer.display0, cutIndex & 0x1f);
pointer.display1 = copyRight(pointer.display1, (cutIndex >>> 5) & 0x1f);
pointer.display2 = copyRight(pointer.display2, (cutIndex >>> 10) & 0x1f);
pointer.display3 = copyRight(pointer.display3, (cutIndex >>> 15) & 0x1f);
pointer.display4 = copyRight(pointer.display4, (cutIndex >>> 20) & 0x1f);
pointer.display5 = copyRight(pointer.display5, (cutIndex >>> 25));
} else {
throw new IllegalArgumentException();
}
}
// requires structure is writable and at index cutIndex
private void cleanRightEdge(int cutIndex) {
// we're actually sitting one block left if cutIndex lies on a block boundary
// this means that we'll end up erasing the whole block!!
if (cutIndex <= (1 << 5)) {
zeroRight(pointer.display0, cutIndex);
} else if (cutIndex <= (1 << 10)) {
zeroRight(pointer.display0, ((cutIndex - 1) & 0x1f) + 1);
pointer.display1 = copyLeft(pointer.display1, (cutIndex >>> 5));
} else if (cutIndex <= (1 << 15)) {
zeroRight(pointer.display0, ((cutIndex - 1) & 0x1f) + 1);
pointer.display1 = copyLeft(pointer.display1, (((cutIndex - 1) >>> 5) & 0x1f) + 1);
pointer.display2 = copyLeft(pointer.display2, (cutIndex >>> 10));
} else if (cutIndex <= (1 << 20)) {
zeroRight(pointer.display0, ((cutIndex - 1) & 0x1f) + 1);
pointer.display1 = copyLeft(pointer.display1, (((cutIndex - 1) >>> 5) & 0x1f) + 1);
pointer.display2 = copyLeft(pointer.display2, (((cutIndex - 1) >>> 10) & 0x1f) + 1);
pointer.display3 = copyLeft(pointer.display3, (cutIndex >>> 15));
} else if (cutIndex <= (1 << 25)) {
zeroRight(pointer.display0, ((cutIndex - 1) & 0x1f) + 1);
pointer.display1 = copyLeft(pointer.display1, (((cutIndex - 1) >>> 5) & 0x1f) + 1);
pointer.display2 = copyLeft(pointer.display2, (((cutIndex - 1) >>> 10) & 0x1f) + 1);
pointer.display3 = copyLeft(pointer.display3, (((cutIndex - 1) >>> 15) & 0x1f) + 1);
pointer.display4 = copyLeft(pointer.display4, (cutIndex >>> 20));
} else if (cutIndex <= (1 << 30)) {
zeroRight(pointer.display0, ((cutIndex - 1) & 0x1f) + 1);
pointer.display1 = copyLeft(pointer.display1, (((cutIndex - 1) >>> 5) & 0x1f) + 1);
pointer.display2 = copyLeft(pointer.display2, (((cutIndex - 1) >>> 10) & 0x1f) + 1);
pointer.display3 = copyLeft(pointer.display3, (((cutIndex - 1) >>> 15) & 0x1f) + 1);
pointer.display4 = copyLeft(pointer.display4, (((cutIndex - 1) >>> 20) & 0x1f) + 1);
pointer.display5 = copyLeft(pointer.display5, (cutIndex >>> 25));
} else {
throw new IllegalArgumentException();
}
}
private int requiredDepth(int xor) {
if (xor < (1 << 5)) return 1;
else if (xor < (1 << 10)) return 2;
else if (xor < (1 << 15)) return 3;
else if (xor < (1 << 20)) return 4;
else if (xor < (1 << 25)) return 5;
else if (xor < (1 << 30)) return 6;
else throw new IllegalArgumentException();
}
private Vector<E> dropFront0(int cutIndex) {
int blockIndex = cutIndex & ~31;
int xor = cutIndex ^ (endIndex - 1);
int d = requiredDepth(xor);
int shift = (cutIndex & ~((1 << (5 * d)) - 1));
// need to init with full display iff going to cutIndex requires swapping block at level >= d
Vector<E> s = new Vector<E>(cutIndex - shift, endIndex - shift, blockIndex - shift);
s.pointer.initFrom(pointer);
s.dirty = dirty;
s.gotoPosWritable(focus, blockIndex, focus ^ blockIndex);
s.preClean(d);
s.cleanLeftEdge(cutIndex - shift);
return s;
}
private Vector<E> dropBack0(int cutIndex) {
int blockIndex = (cutIndex - 1) & ~31;
int xor = startIndex ^ (cutIndex - 1);
int d = requiredDepth(xor);
int shift = (startIndex & ~((1 << (5 * d)) - 1));
Vector<E> s = new Vector<E>(startIndex - shift, cutIndex - shift, blockIndex - shift);
s.pointer.initFrom(pointer);
s.dirty = dirty;
s.gotoPosWritable(focus, blockIndex, focus ^ blockIndex);
s.preClean(d);
s.cleanRightEdge(cutIndex - shift);
return s;
}
}
class VectorIterator<E> extends VectorPointer<E> implements Iterator<E> {
private int blockIndex;
private int lo;
private final int endIndex;
private int endLo;
private boolean _hasNext;
VectorIterator(int _startIndex, int _endIndex) {
blockIndex = _startIndex & ~31;
lo = _startIndex & 31;
endIndex = _endIndex;
endLo = Math.min(endIndex - blockIndex, 32);
_hasNext = blockIndex + lo < endIndex;
}
@Override
public boolean hasNext() {
return _hasNext;
}
@Override
public E next() {
if (!_hasNext) throw new NoSuchElementException("reached iterator end");
@SuppressWarnings("unchecked")
E res = (E) display0[lo];
lo += 1;
if (lo == endLo) {
if (blockIndex + lo < endIndex) {
int newBlockIndex = blockIndex + 32;
gotoNextBlockStart(newBlockIndex, blockIndex ^ newBlockIndex);
blockIndex = newBlockIndex;
endLo = Math.min(endIndex - blockIndex, 32);
lo = 0;
} else {
_hasNext = false;
}
}
return res;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
class VectorPointer<E> {
int depth = 0;
Object[] display0 = null;
Object[] display1 = null;
Object[] display2 = null;
Object[] display3 = null;
Object[] display4 = null;
Object[] display5 = null;
// used
public void initFrom(VectorPointer<E> that) {
initFrom(that, that.depth);
}
public void initFrom(VectorPointer<E> that, int depth) {
this.depth = depth;
switch (depth - 1) {
case -1:
break;
case 0:
display0 = that.display0;
break;
case 1:
display1 = that.display1;
display0 = that.display0;
break;
case 2:
display2 = that.display2;
display1 = that.display1;
display0 = that.display0;
break;
case 3:
display3 = that.display3;
display2 = that.display2;
display1 = that.display1;
display0 = that.display0;
break;
case 4:
display4 = that.display4;
display3 = that.display3;
display2 = that.display2;
display1 = that.display1;
display0 = that.display0;
break;
case 5:
display5 = that.display5;
display4 = that.display4;
display3 = that.display3;
display2 = that.display2;
display1 = that.display1;
display0 = that.display0;
break;
default:
}
}
// requires structure is at pos oldIndex = xor ^ index
@SuppressWarnings("unchecked")
public E getElem(int index, int xor) {
if (xor < (1 << 5)) { // level = 0
return (E) display0[index & 31];
} else if (xor < (1 << 10)) { // level = 1
return (E) ((Object[]) display1[(index >> 5) & 31])[index & 31];
} else if (xor < (1 << 15)) { // level = 2
return (E) ((Object[]) ((Object[]) display2[(index >> 10) & 31])[(index >> 5) & 31])[index & 31];
} else if (xor < (1 << 20)) { // level = 3
return (E) ((Object[]) ((Object[]) ((Object[]) display3[(index >> 15) & 31])[(index >> 10) & 31])[(index >> 5) & 31])[index & 31];
} else if (xor < (1 << 25)) { // level = 4
return (E) ((Object[]) ((Object[]) ((Object[]) ((Object[]) display4[(index >> 20) & 31])[(index >> 15) & 31])[(index >> 10) & 31])[(index >> 5) & 31])[index & 31];
} else if (xor < (1 << 30)) { // level = 5
return (E) ((Object[]) ((Object[]) ((Object[]) ((Object[]) ((Object[]) display5[(index >> 25) & 31])[(index >> 20) & 31])[(index >> 15) & 31])[(index >> 10) & 31])[(index >> 5) & 31])[index & 31];
} else { // level = 6
throw new IllegalArgumentException();
}
}
// go to specific position
// requires structure is at pos oldIndex = xor ^ index,
// ensures structure is at pos index
public void gotoPos(int index, int xor) {
//noinspection StatementWithEmptyBody
if (xor < (1 << 5)) { // level = 0 (could maybe removed)
} else if (xor < (1 << 10)) { // level = 1
display0 = (Object[]) display1[(index >> 5) & 31];
} else if (xor < (1 << 15)) { // level = 2
display1 = (Object[]) display2[(index >> 10) & 31];
display0 = (Object[]) display1[(index >> 5) & 31];
} else if (xor < (1 << 20)) { // level = 3
display2 = (Object[]) display3[(index >> 15) & 31];
display1 = (Object[]) display2[(index >> 10) & 31];
display0 = (Object[]) display1[(index >> 5) & 31];
} else if (xor < (1 << 25)) { // level = 4
display3 = (Object[]) display4[(index >> 20) & 31];
display2 = (Object[]) display3[(index >> 15) & 31];
display1 = (Object[]) display2[(index >> 10) & 31];
display0 = (Object[]) display1[(index >> 5) & 31];
} else if (xor < (1 << 30)) { // level = 5
display4 = (Object[]) display5[(index >> 25) & 31];
display3 = (Object[]) display4[(index >> 20) & 31];
display2 = (Object[]) display3[(index >> 15) & 31];
display1 = (Object[]) display2[(index >> 10) & 31];
display0 = (Object[]) display1[(index >> 5) & 31];
} else { // level = 6
throw new IllegalArgumentException();
}
}
// USED BY ITERATOR
// xor: oldIndex ^ index
public void gotoNextBlockStart(int index, int xor) { // goto block start pos
if (xor < (1 << 10)) { // level = 1
display0 = (Object[]) display1[(index >> 5) & 31];
} else if (xor < (1 << 15)) { // level = 2
display1 = (Object[]) display2[(index >> 10) & 31];
display0 = (Object[]) display1[0];
} else if (xor < (1 << 20)) { // level = 3
display2 = (Object[]) display3[(index >> 15) & 31];
display1 = (Object[]) display2[0];
display0 = (Object[]) display1[0];
} else if (xor < (1 << 25)) { // level = 4
display3 = (Object[]) display4[(index >> 20) & 31];
display2 = (Object[]) display3[0];
display1 = (Object[]) display2[0];
display0 = (Object[]) display1[0];
} else if (xor < (1 << 30)) { // level = 5
display4 = (Object[]) display5[(index >> 25) & 31];
display3 = (Object[]) display4[0];
display2 = (Object[]) display3[0];
display1 = (Object[]) display2[0];
display0 = (Object[]) display1[0];
} else { // level = 6
throw new IllegalArgumentException();
}
}
// USED BY BUILDER
// xor: oldIndex ^ index
public void gotoNextBlockStartWritable(int index, int xor) { // goto block start pos
if (xor < (1 << 10)) { // level = 1
if (depth == 1) {
display1 = new Object[32];
display1[0] = display0;
depth += 1;
}
display0 = new Object[32];
display1[(index >> 5) & 31] = display0;
} else if (xor < (1 << 15)) { // level = 2
if (depth == 2) {
display2 = new Object[32];
display2[0] = display1;
depth += 1;
}
display0 = new Object[32];
display1 = new Object[32];
display1[(index >> 5) & 31] = display0;
display2[(index >> 10) & 31] = display1;
} else if (xor < (1 << 20)) { // level = 3
if (depth == 3) {
display3 = new Object[32];
display3[0] = display2;
depth += 1;
}
display0 = new Object[32];
display1 = new Object[32];
display2 = new Object[32];
display1[(index >> 5) & 31] = display0;
display2[(index >> 10) & 31] = display1;
display3[(index >> 15) & 31] = display2;
} else if (xor < (1 << 25)) { // level = 4
if (depth == 4) {
display4 = new Object[32];
display4[0] = display3;
depth += 1;
}
display0 = new Object[32];
display1 = new Object[32];
display2 = new Object[32];
display3 = new Object[32];
display1[(index >> 5) & 31] = display0;
display2[(index >> 10) & 31] = display1;
display3[(index >> 15) & 31] = display2;
display4[(index >> 20) & 31] = display3;
} else if (xor < (1 << 30)) { // level = 5
if (depth == 5) {
display5 = new Object[32];
display5[0] = display4;
depth += 1;
}
display0 = new Object[32];
display1 = new Object[32];
display2 = new Object[32];
display3 = new Object[32];
display4 = new Object[32];
display1[(index >> 5) & 31] = display0;
display2[(index >> 10) & 31] = display1;
display3[(index >> 15) & 31] = display2;
display4[(index >> 20) & 31] = display3;
display5[(index >> 25) & 31] = display4;
} else { // level = 6
throw new IllegalArgumentException();
}
}
// STUFF BELOW USED BY APPEND / UPDATE
public Object[] copyOf(Object[] a) {
Object[] b = new Object[a.length];
System.arraycopy(a, 0, b, 0, a.length);
return b;
}
public Object[] nullSlotAndCopy(Object[] array, int index) {
Object x = array[index];
array[index] = null;
return copyOf((Object[]) x);
}
// make sure there is no aliasing
// requires structure is at pos index
// ensures structure is clean and at pos index and writable at all levels except 0
public void stabilize(int index) {
switch (depth - 1) {
case 5:
display5 = copyOf(display5);
display4 = copyOf(display4);
display3 = copyOf(display3);
display2 = copyOf(display2);
display1 = copyOf(display1);
display5[(index >> 25) & 31] = display4;
display4[(index >> 20) & 31] = display3;
display3[(index >> 15) & 31] = display2;
display2[(index >> 10) & 31] = display1;
display1[(index >> 5) & 31] = display0;
break;
case 4:
display4 = copyOf(display4);
display3 = copyOf(display3);
display2 = copyOf(display2);
display1 = copyOf(display1);
display4[(index >> 20) & 31] = display3;
display3[(index >> 15) & 31] = display2;
display2[(index >> 10) & 31] = display1;
display1[(index >> 5) & 31] = display0;
break;
case 3:
display3 = copyOf(display3);
display2 = copyOf(display2);
display1 = copyOf(display1);
display3[(index >> 15) & 31] = display2;
display2[(index >> 10) & 31] = display1;
display1[(index >> 5) & 31] = display0;
break;
case 2:
display2 = copyOf(display2);
display1 = copyOf(display1);
display2[(index >> 10) & 31] = display1;
display1[(index >> 5) & 31] = display0;
break;
case 1:
display1 = copyOf(display1);
display1[(index >> 5) & 31] = display0;
break;
case 0:
break;
}
}
/// USED IN UPDATE AND APPEND BACK
// prepare for writing at an existing position
// requires structure is clean and at pos oldIndex = xor ^ newIndex,
// ensures structure is dirty and at pos newIndex and writable at level 0
public void gotoPosWritable0(int newIndex) {
switch (depth - 1) {
case 5:
display5 = copyOf(display5);
display4 = nullSlotAndCopy(display5, (newIndex >> 25) & 31);
display3 = nullSlotAndCopy(display4, (newIndex >> 20) & 31);
display2 = nullSlotAndCopy(display3, (newIndex >> 15) & 31);
display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31);
display0 = nullSlotAndCopy(display1, (newIndex >> 5) & 31);
break;
case 4:
display4 = copyOf(display4);
display3 = nullSlotAndCopy(display4, (newIndex >> 20) & 31);
display2 = nullSlotAndCopy(display3, (newIndex >> 15) & 31);
display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31);
display0 = nullSlotAndCopy(display1, (newIndex >> 5) & 31);
break;
case 3:
display3 = copyOf(display3);
display2 = nullSlotAndCopy(display3, (newIndex >> 15) & 31);
display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31);
display0 = nullSlotAndCopy(display1, (newIndex >> 5) & 31);
break;
case 2:
display2 = copyOf(display2);
display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31);
display0 = nullSlotAndCopy(display1, (newIndex >> 5) & 31);
break;
case 1:
display1 = copyOf(display1);
display0 = nullSlotAndCopy(display1, (newIndex >> 5) & 31);
break;
case 0:
display0 = copyOf(display0);
break;
default:
}
}
// requires structure is dirty and at pos oldIndex,
// ensures structure is dirty and at pos newIndex and writable at level 0
public void gotoPosWritable1(int oldIndex, int newIndex, int xor) {
if (xor < (1 << 5)) { // level = 0
display0 = copyOf(display0);
} else if (xor < (1 << 10)) { // level = 1
display1 = copyOf(display1);
display1[(oldIndex >> 5) & 31] = display0;
display0 = nullSlotAndCopy(display1, (newIndex >> 5) & 31);
} else if (xor < (1 << 15)) { // level = 2
display1 = copyOf(display1);
display2 = copyOf(display2);
display1[(oldIndex >> 5) & 31] = display0;
display2[(oldIndex >> 10) & 31] = display1;
display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31);
display0 = nullSlotAndCopy(display1, (newIndex >> 5) & 31);
} else if (xor < (1 << 20)) { // level = 3
display1 = copyOf(display1);
display2 = copyOf(display2);
display3 = copyOf(display3);
display1[(oldIndex >> 5) & 31] = display0;
display2[(oldIndex >> 10) & 31] = display1;
display3[(oldIndex >> 15) & 31] = display2;
display2 = nullSlotAndCopy(display3, (newIndex >> 15) & 31);
display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31);
display0 = nullSlotAndCopy(display1, (newIndex >> 5) & 31);
} else if (xor < (1 << 25)) { // level = 4
display1 = copyOf(display1);
display2 = copyOf(display2);
display3 = copyOf(display3);
display4 = copyOf(display4);
display1[(oldIndex >> 5) & 31] = display0;
display2[(oldIndex >> 10) & 31] = display1;
display3[(oldIndex >> 15) & 31] = display2;
display4[(oldIndex >> 20) & 31] = display3;
display3 = nullSlotAndCopy(display4, (newIndex >> 20) & 31);
display2 = nullSlotAndCopy(display3, (newIndex >> 15) & 31);
display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31);
display0 = nullSlotAndCopy(display1, (newIndex >> 5) & 31);
} else if (xor < (1 << 30)) { // level = 5
display1 = copyOf(display1);
display2 = copyOf(display2);
display3 = copyOf(display3);
display4 = copyOf(display4);
display5 = copyOf(display5);
display1[(oldIndex >> 5) & 31] = display0;
display2[(oldIndex >> 10) & 31] = display1;
display3[(oldIndex >> 15) & 31] = display2;
display4[(oldIndex >> 20) & 31] = display3;
display5[(oldIndex >> 25) & 31] = display4;
display4 = nullSlotAndCopy(display5, (newIndex >> 25) & 31);
display3 = nullSlotAndCopy(display4, (newIndex >> 20) & 31);
display2 = nullSlotAndCopy(display3, (newIndex >> 15) & 31);
display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31);
display0 = nullSlotAndCopy(display1, (newIndex >> 5) & 31);
} else { // level = 6
throw new IllegalArgumentException();
}
}
// USED IN DROP
public Object[] copyRange(Object[] array, int oldLeft, int newLeft) {
Object[] elems = new Object[32];
System.arraycopy(array, oldLeft, elems, newLeft, 32 - Math.max(newLeft, oldLeft));
return elems;
}
// USED IN APPEND
// create a new block at the bottom level (and possibly nodes on its path) and prepares for writing
// requires structure is clean and at pos oldIndex,
// ensures structure is dirty and at pos newIndex and writable at level 0
public void gotoFreshPosWritable0(int oldIndex, int newIndex, int xor) { // goto block start pos
//noinspection StatementWithEmptyBody
if (xor < (1 << 5)) { // level = 0
} else if (xor < (1 << 10)) { // level = 1
if (depth == 1) {
display1 = new Object[32];
display1[(oldIndex >> 5) & 31] = display0;
depth += 1;
}
display0 = new Object[32];
} else if (xor < (1 << 15)) { // level = 2
if (depth == 2) {
display2 = new Object[32];
display2[(oldIndex >> 10) & 31] = display1;
depth += 1;
}
display1 = (Object[]) display2[(newIndex >> 10) & 31];
if (display1 == null) display1 = new Object[32];
display0 = new Object[32];
} else if (xor < (1 << 20)) { // level = 3
if (depth == 3) {
display3 = new Object[32];
display3[(oldIndex >> 15) & 31] = display2;
display2 = new Object[32];
display1 = new Object[32];
depth += 1;
}
display2 = (Object[]) display3[(newIndex >> 15) & 31];
if (display2 == null) display2 = new Object[32];
display1 = (Object[]) display2[(newIndex >> 10) & 31];
if (display1 == null) display1 = new Object[32];
display0 = new Object[32];
} else if (xor < (1 << 25)) { // level = 4
if (depth == 4) {
display4 = new Object[32];
display4[(oldIndex >> 20) & 31] = display3;
display3 = new Object[32];
display2 = new Object[32];
display1 = new Object[32];
depth += 1;
}
display3 = (Object[]) display4[(newIndex >> 20) & 31];
if (display3 == null) display3 = new Object[32];
display2 = (Object[]) display3[(newIndex >> 15) & 31];
if (display2 == null) display2 = new Object[32];
display1 = (Object[]) display2[(newIndex >> 10) & 31];
if (display1 == null) display1 = new Object[32];
display0 = new Object[32];
} else if (xor < (1 << 30)) { // level = 5
if (depth == 5) {
display5 = new Object[32];
display5[(oldIndex >> 25) & 31] = display4;
display4 = new Object[32];
display3 = new Object[32];
display2 = new Object[32];
display1 = new Object[32];
depth += 1;
}
display4 = (Object[]) display5[(newIndex >> 25) & 31];
if (display4 == null) display4 = new Object[32];
display3 = (Object[]) display4[(newIndex >> 20) & 31];
if (display3 == null) display3 = new Object[32];
display2 = (Object[]) display3[(newIndex >> 15) & 31];
if (display2 == null) display2 = new Object[32];
display1 = (Object[]) display2[(newIndex >> 10) & 31];
if (display1 == null) display1 = new Object[32];
display0 = new Object[32];
} else { // level = 6
throw new IllegalArgumentException();
}
}
// requires structure is dirty and at pos oldIndex,
// ensures structure is dirty and at pos newIndex and writable at level 0
public void gotoFreshPosWritable1(int oldIndex, int newIndex, int xor) {
stabilize(oldIndex);
gotoFreshPosWritable0(oldIndex, newIndex, xor);
}
}
| class VectorBuilder<E> extends AbstractBuilder<E, Vector<E>> { | 1 | 2023-12-10 15:10:13+00:00 | 8k |
netty/netty-incubator-codec-ohttp | codec-ohttp-hpke-classes-boringssl/src/main/java/io/netty/incubator/codec/hpke/boringssl/BoringSSLOHttpCryptoProvider.java | [
{
"identifier": "AEAD",
"path": "codec-ohttp-hpke/src/main/java/io/netty/incubator/codec/hpke/AEAD.java",
"snippet": "public enum AEAD {\n AES_GCM128((short) 0x0001, 16, 12),\n AES_GCM256((short) 0x0002, 32, 12),\n CHACHA20_POLY1305((short) 0x0003, 32, 12);\n\n public static AEAD forId(short... | import io.netty.incubator.codec.hpke.AEAD;
import io.netty.incubator.codec.hpke.AEADContext;
import io.netty.incubator.codec.hpke.AsymmetricCipherKeyPair;
import io.netty.incubator.codec.hpke.AsymmetricKeyParameter;
import io.netty.incubator.codec.hpke.HPKERecipientContext;
import io.netty.incubator.codec.hpke.HPKESenderContext;
import io.netty.incubator.codec.hpke.KDF;
import io.netty.incubator.codec.hpke.KEM;
import io.netty.incubator.codec.hpke.OHttpCryptoProvider;
import java.util.Arrays; | 3,854 | /*
* 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.hpke.boringssl;
/**
* BoringSSL based {@link OHttpCryptoProvider}. {@link BoringSSLHPKE#ensureAvailability()} or
* {@link BoringSSLHPKE#isAvailable()} should be used before accessing {@link #INSTANCE} to ensure
* the native library can be loaded on the used platform.
*/
public final class BoringSSLOHttpCryptoProvider implements OHttpCryptoProvider {
/**
* {@link BoringSSLOHttpCryptoProvider} instance.
*/
public static final BoringSSLOHttpCryptoProvider INSTANCE = new BoringSSLOHttpCryptoProvider();
private BoringSSLOHttpCryptoProvider() {
}
@Override
public AEADContext setupAEAD(AEAD aead, byte[] key, byte[] baseNonce) {
long boringSSLAead = boringSSLAEAD(aead);
int keyLength = BoringSSL.EVP_AEAD_key_length(boringSSLAead);
if (keyLength != key.length) {
throw new IllegalArgumentException("key length must be " + keyLength + ": " + key.length);
}
int nounceLength = BoringSSL.EVP_AEAD_nonce_length(boringSSLAead);
if (nounceLength != baseNonce.length) {
throw new IllegalArgumentException("baseNonce length must be " + nounceLength + ": " + baseNonce.length);
}
int maxOverhead = BoringSSL.EVP_AEAD_max_overhead(boringSSLAead);
long ctx = BoringSSL.EVP_AEAD_CTX_new_or_throw(boringSSLAead, key, BoringSSL.EVP_AEAD_DEFAULT_TAG_LENGTH);
try {
BoringSSLAEADContext aeadCtx = new BoringSSLAEADContext(ctx, maxOverhead, baseNonce);
ctx = -1;
return aeadCtx;
} finally {
if (ctx != -1) {
BoringSSL.EVP_AEAD_CTX_cleanup_and_free(ctx);
}
}
}
private static long boringSSLAEAD(AEAD aead) {
switch (aead) {
case AES_GCM128:
return BoringSSL.EVP_aead_aes_128_gcm;
case AES_GCM256:
return BoringSSL.EVP_aead_aes_256_gcm;
case CHACHA20_POLY1305:
return BoringSSL.EVP_aead_chacha20_poly1305;
default:
throw new IllegalArgumentException("AEAD not supported: " + aead);
}
}
private static long boringSSLKDF(KDF kdf) {
if (kdf != KDF.HKDF_SHA256) {
throw new IllegalArgumentException("KDF not supported: " + kdf);
}
return BoringSSL.EVP_hpke_hkdf_sha256;
}
private static long boringSSLKEM(KEM kem) {
if (kem != KEM.X25519_SHA256) {
throw new IllegalArgumentException("KEM not supported: " + kem);
}
return BoringSSL.EVP_hpke_x25519_hkdf_sha256;
}
private static long boringSSLHPKEAEAD(AEAD aead) {
switch (aead) {
case AES_GCM128:
return BoringSSL.EVP_hpke_aes_128_gcm;
case AES_GCM256:
return BoringSSL.EVP_hpke_aes_256_gcm;
case CHACHA20_POLY1305:
return BoringSSL.EVP_hpke_chacha20_poly1305;
default:
throw new IllegalArgumentException("AEAD not supported: " + aead);
}
}
@Override
public HPKESenderContext setupHPKEBaseS(KEM kem, KDF kdf, AEAD aead, AsymmetricKeyParameter pkR,
byte[] info, AsymmetricCipherKeyPair kpE) {
long boringSSLKem = boringSSLKEM(kem);
long boringSSLKdf = boringSSLKDF(kdf);
long boringSSLAead = boringSSLHPKEAEAD(aead);
final byte[] pkRBytes = encodedAsymmetricKeyParameter(pkR);
final byte[] encapsulation;
long ctx = BoringSSL.EVP_HPKE_CTX_new_or_throw();
try {
if (kpE == null) {
encapsulation = BoringSSL.EVP_HPKE_CTX_setup_sender(
ctx, boringSSLKem, boringSSLKdf, boringSSLAead, pkRBytes, info);
} else {
encapsulation = BoringSSL.EVP_HPKE_CTX_setup_sender_with_seed_for_testing(
ctx, boringSSLKem, boringSSLKdf, boringSSLAead, pkRBytes, info,
// As we only support X25519 it is the right thing to just use the private key as seed.
// See https://github.com/google/boringssl/blob/master/include/openssl/hpke.h#L235C44-L235C50
encodedAsymmetricKeyParameter(kpE.privateParameters()));
}
if (encapsulation == null) {
throw new IllegalStateException("Unable to setup EVP_HPKE_CTX");
}
BoringSSLHPKESenderContext hpkeCtx =
new BoringSSLHPKESenderContext(ctx, encapsulation);
ctx = -1;
return hpkeCtx;
} finally {
if (ctx != -1) {
BoringSSL.EVP_HPKE_CTX_cleanup_and_free(ctx);
}
}
}
private static byte[] encodedAsymmetricKeyParameter(AsymmetricKeyParameter parameter) {
if (parameter instanceof BoringSSLAsymmetricKeyParameter) {
// No copy needed.
return ((BoringSSLAsymmetricKeyParameter) parameter).bytes;
}
return parameter.encoded();
}
@Override | /*
* 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.hpke.boringssl;
/**
* BoringSSL based {@link OHttpCryptoProvider}. {@link BoringSSLHPKE#ensureAvailability()} or
* {@link BoringSSLHPKE#isAvailable()} should be used before accessing {@link #INSTANCE} to ensure
* the native library can be loaded on the used platform.
*/
public final class BoringSSLOHttpCryptoProvider implements OHttpCryptoProvider {
/**
* {@link BoringSSLOHttpCryptoProvider} instance.
*/
public static final BoringSSLOHttpCryptoProvider INSTANCE = new BoringSSLOHttpCryptoProvider();
private BoringSSLOHttpCryptoProvider() {
}
@Override
public AEADContext setupAEAD(AEAD aead, byte[] key, byte[] baseNonce) {
long boringSSLAead = boringSSLAEAD(aead);
int keyLength = BoringSSL.EVP_AEAD_key_length(boringSSLAead);
if (keyLength != key.length) {
throw new IllegalArgumentException("key length must be " + keyLength + ": " + key.length);
}
int nounceLength = BoringSSL.EVP_AEAD_nonce_length(boringSSLAead);
if (nounceLength != baseNonce.length) {
throw new IllegalArgumentException("baseNonce length must be " + nounceLength + ": " + baseNonce.length);
}
int maxOverhead = BoringSSL.EVP_AEAD_max_overhead(boringSSLAead);
long ctx = BoringSSL.EVP_AEAD_CTX_new_or_throw(boringSSLAead, key, BoringSSL.EVP_AEAD_DEFAULT_TAG_LENGTH);
try {
BoringSSLAEADContext aeadCtx = new BoringSSLAEADContext(ctx, maxOverhead, baseNonce);
ctx = -1;
return aeadCtx;
} finally {
if (ctx != -1) {
BoringSSL.EVP_AEAD_CTX_cleanup_and_free(ctx);
}
}
}
private static long boringSSLAEAD(AEAD aead) {
switch (aead) {
case AES_GCM128:
return BoringSSL.EVP_aead_aes_128_gcm;
case AES_GCM256:
return BoringSSL.EVP_aead_aes_256_gcm;
case CHACHA20_POLY1305:
return BoringSSL.EVP_aead_chacha20_poly1305;
default:
throw new IllegalArgumentException("AEAD not supported: " + aead);
}
}
private static long boringSSLKDF(KDF kdf) {
if (kdf != KDF.HKDF_SHA256) {
throw new IllegalArgumentException("KDF not supported: " + kdf);
}
return BoringSSL.EVP_hpke_hkdf_sha256;
}
private static long boringSSLKEM(KEM kem) {
if (kem != KEM.X25519_SHA256) {
throw new IllegalArgumentException("KEM not supported: " + kem);
}
return BoringSSL.EVP_hpke_x25519_hkdf_sha256;
}
private static long boringSSLHPKEAEAD(AEAD aead) {
switch (aead) {
case AES_GCM128:
return BoringSSL.EVP_hpke_aes_128_gcm;
case AES_GCM256:
return BoringSSL.EVP_hpke_aes_256_gcm;
case CHACHA20_POLY1305:
return BoringSSL.EVP_hpke_chacha20_poly1305;
default:
throw new IllegalArgumentException("AEAD not supported: " + aead);
}
}
@Override
public HPKESenderContext setupHPKEBaseS(KEM kem, KDF kdf, AEAD aead, AsymmetricKeyParameter pkR,
byte[] info, AsymmetricCipherKeyPair kpE) {
long boringSSLKem = boringSSLKEM(kem);
long boringSSLKdf = boringSSLKDF(kdf);
long boringSSLAead = boringSSLHPKEAEAD(aead);
final byte[] pkRBytes = encodedAsymmetricKeyParameter(pkR);
final byte[] encapsulation;
long ctx = BoringSSL.EVP_HPKE_CTX_new_or_throw();
try {
if (kpE == null) {
encapsulation = BoringSSL.EVP_HPKE_CTX_setup_sender(
ctx, boringSSLKem, boringSSLKdf, boringSSLAead, pkRBytes, info);
} else {
encapsulation = BoringSSL.EVP_HPKE_CTX_setup_sender_with_seed_for_testing(
ctx, boringSSLKem, boringSSLKdf, boringSSLAead, pkRBytes, info,
// As we only support X25519 it is the right thing to just use the private key as seed.
// See https://github.com/google/boringssl/blob/master/include/openssl/hpke.h#L235C44-L235C50
encodedAsymmetricKeyParameter(kpE.privateParameters()));
}
if (encapsulation == null) {
throw new IllegalStateException("Unable to setup EVP_HPKE_CTX");
}
BoringSSLHPKESenderContext hpkeCtx =
new BoringSSLHPKESenderContext(ctx, encapsulation);
ctx = -1;
return hpkeCtx;
} finally {
if (ctx != -1) {
BoringSSL.EVP_HPKE_CTX_cleanup_and_free(ctx);
}
}
}
private static byte[] encodedAsymmetricKeyParameter(AsymmetricKeyParameter parameter) {
if (parameter instanceof BoringSSLAsymmetricKeyParameter) {
// No copy needed.
return ((BoringSSLAsymmetricKeyParameter) parameter).bytes;
}
return parameter.encoded();
}
@Override | public HPKERecipientContext setupHPKEBaseR(KEM kem, KDF kdf, AEAD aead, byte[] enc, | 4 | 2023-12-06 09:14:09+00:00 | 8k |
lyswhut/react-native-local-media-metadata | android/src/main/java/org/jaudiotagger/tag/datatype/Lyrics3TimeStamp.java | [
{
"identifier": "StandardCharsets",
"path": "android/src/main/java/org/jaudiotagger/StandardCharsets.java",
"snippet": "public final class StandardCharsets {\n\n private StandardCharsets() {\n throw new AssertionError(\"No org.jaudiotagger.StandardCharsets instances for you!\");\n }\n /*... | import org.jaudiotagger.StandardCharsets;
import org.jaudiotagger.tag.InvalidDataTypeException;
import org.jaudiotagger.tag.id3.AbstractTagFrameBody; | 3,763 | /**
* @todo convert both types of formats
*/
timeStamp = timeStamp / 1000;
minute = timeStamp / 60;
second = timeStamp % 60;
}
/**
* @param obj
* @return
*/
public boolean equals(Object obj)
{
if (!(obj instanceof Lyrics3TimeStamp))
{
return false;
}
Lyrics3TimeStamp object = (Lyrics3TimeStamp) obj;
if (this.minute != object.minute)
{
return false;
}
return this.second == object.second && super.equals(obj);
}
/**
* @param timeStamp
* @param offset
* @throws NullPointerException
* @throws IndexOutOfBoundsException
*/
public void readString(String timeStamp, int offset)
{
if (timeStamp == null)
{
throw new NullPointerException("Image is null");
}
if ((offset < 0) || (offset >= timeStamp.length()))
{
throw new IndexOutOfBoundsException("Offset to timeStamp is out of bounds: offset = " + offset + ", timeStamp.length()" + timeStamp.length());
}
timeStamp = timeStamp.substring(offset);
if (timeStamp.length() == 7)
{
minute = Integer.parseInt(timeStamp.substring(1, 3));
second = Integer.parseInt(timeStamp.substring(4, 6));
}
else
{
minute = 0;
second = 0;
}
}
/**
* @return
*/
public String toString()
{
return writeString();
}
/**
* @return
*/
public String writeString()
{
String str;
str = "[";
if (minute < 0)
{
str += "00";
}
else
{
if (minute < 10)
{
str += '0';
}
str += Long.toString(minute);
}
str += ':';
if (second < 0)
{
str += "00";
}
else
{
if (second < 10)
{
str += '0';
}
str += Long.toString(second);
}
str += ']';
return str;
}
public void readByteArray(byte[] arr, int offset) throws InvalidDataTypeException
{
readString(arr.toString(), offset);
}
public byte[] writeByteArray()
{ | /**
* @author : Paul Taylor
* @author : Eric Farng
*
* Version @version:$Id$
*
* MusicTag Copyright (C)2003,2004
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser
* General Public License as published by the Free Software Foundation; either version 2.1 of the License,
* or (at your option) any later version.
*
* This library 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library; if not,
* you can get a copy from http://www.opensource.org/licenses/lgpl-license.php or write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Description:
*
*/
package org.jaudiotagger.tag.datatype;
public class Lyrics3TimeStamp extends AbstractDataType
{
/**
*
*/
private long minute = 0;
/**
*
*/
private long second = 0;
/**
* Todo this is wrong
* @param s
*/
public void readString(String s)
{
}
/**
* Creates a new ObjectLyrics3TimeStamp datatype.
*
* @param identifier
* @param frameBody
*/
public Lyrics3TimeStamp(String identifier, AbstractTagFrameBody frameBody)
{
super(identifier, frameBody);
}
public Lyrics3TimeStamp(String identifier)
{
super(identifier, null);
}
public Lyrics3TimeStamp(Lyrics3TimeStamp copy)
{
super(copy);
this.minute = copy.minute;
this.second = copy.second;
}
public void setMinute(long minute)
{
this.minute = minute;
}
/**
* @return
*/
public long getMinute()
{
return minute;
}
public void setSecond(long second)
{
this.second = second;
}
/**
* @return
*/
public long getSecond()
{
return second;
}
/**
* @return
*/
public int getSize()
{
return 7;
}
/**
* Creates a new ObjectLyrics3TimeStamp datatype.
*
* @param timeStamp
* @param timeStampFormat
*/
public void setTimeStamp(long timeStamp, byte timeStampFormat)
{
/**
* @todo convert both types of formats
*/
timeStamp = timeStamp / 1000;
minute = timeStamp / 60;
second = timeStamp % 60;
}
/**
* @param obj
* @return
*/
public boolean equals(Object obj)
{
if (!(obj instanceof Lyrics3TimeStamp))
{
return false;
}
Lyrics3TimeStamp object = (Lyrics3TimeStamp) obj;
if (this.minute != object.minute)
{
return false;
}
return this.second == object.second && super.equals(obj);
}
/**
* @param timeStamp
* @param offset
* @throws NullPointerException
* @throws IndexOutOfBoundsException
*/
public void readString(String timeStamp, int offset)
{
if (timeStamp == null)
{
throw new NullPointerException("Image is null");
}
if ((offset < 0) || (offset >= timeStamp.length()))
{
throw new IndexOutOfBoundsException("Offset to timeStamp is out of bounds: offset = " + offset + ", timeStamp.length()" + timeStamp.length());
}
timeStamp = timeStamp.substring(offset);
if (timeStamp.length() == 7)
{
minute = Integer.parseInt(timeStamp.substring(1, 3));
second = Integer.parseInt(timeStamp.substring(4, 6));
}
else
{
minute = 0;
second = 0;
}
}
/**
* @return
*/
public String toString()
{
return writeString();
}
/**
* @return
*/
public String writeString()
{
String str;
str = "[";
if (minute < 0)
{
str += "00";
}
else
{
if (minute < 10)
{
str += '0';
}
str += Long.toString(minute);
}
str += ':';
if (second < 0)
{
str += "00";
}
else
{
if (second < 10)
{
str += '0';
}
str += Long.toString(second);
}
str += ']';
return str;
}
public void readByteArray(byte[] arr, int offset) throws InvalidDataTypeException
{
readString(arr.toString(), offset);
}
public byte[] writeByteArray()
{ | return writeString().getBytes(StandardCharsets.ISO_8859_1); | 0 | 2023-12-11 05:58:19+00:00 | 8k |
Ender-Cube/Endercube | Parkour/src/main/java/net/endercube/Parkour/listeners/PlayerMove.java | [
{
"identifier": "EndercubePlayer",
"path": "Common/src/main/java/net/endercube/Common/players/EndercubePlayer.java",
"snippet": "public class EndercubePlayer extends Player {\n public EndercubePlayer(@NotNull UUID uuid, @NotNull String username, @NotNull PlayerConnection playerConnection) {\n ... | import net.endercube.Common.players.EndercubePlayer;
import net.endercube.Parkour.ParkourMinigame;
import net.endercube.Parkour.inventories.ParkourMapInventory;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.sound.Sound;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.event.ClickEvent;
import net.kyori.adventure.text.event.HoverEvent;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextDecoration;
import net.kyori.adventure.title.Title;
import net.minestom.server.coordinate.Pos;
import net.minestom.server.event.EventListener;
import net.minestom.server.event.player.PlayerMoveEvent;
import net.minestom.server.instance.Instance;
import net.minestom.server.network.packet.server.play.EntityStatusPacket;
import net.minestom.server.sound.SoundEvent;
import net.minestom.server.tag.Tag;
import net.minestom.server.timer.Scheduler;
import net.minestom.server.timer.Task;
import net.minestom.server.timer.TaskSchedule;
import org.jetbrains.annotations.NotNull;
import java.time.Duration;
import java.util.Objects;
import static net.endercube.Common.EndercubeMinigame.logger;
import static net.endercube.Common.utils.ComponentUtils.toHumanReadableTime;
import static net.endercube.Parkour.ParkourMinigame.database;
import static net.endercube.Parkour.ParkourMinigame.parkourMinigame; | 4,522 | package net.endercube.Parkour.listeners;
/**
* Most of the logic for the game is in here... I should really clean this code up
*/
public class PlayerMove implements EventListener<PlayerMoveEvent> {
private EndercubePlayer player;
private Pos playerPosition;
private Instance instance;
private Pos[] checkpoints;
private int currentCheckpoint;
private String mapName;
private Scheduler scheduler;
@Override
public @NotNull Class<PlayerMoveEvent> eventType() {
return PlayerMoveEvent.class;
}
@Override
public @NotNull Result run(@NotNull PlayerMoveEvent event) {
player = (EndercubePlayer) event.getPlayer();
playerPosition = player.getPosition();
instance = player.getInstance();
checkpoints = instance.getTag(Tag.Transient("checkpointsPosArray"));
currentCheckpoint = player.getTag(Tag.Integer("parkour_checkpoint"));
mapName = instance.getTag(Tag.String("name"));
scheduler = player.scheduler();
// See if player is below the death barrier and if so, teleport them to current checkpoint
if (player.getPosition().y() < instance.getTag(Tag.Integer("death-y"))) {
this.handleDeath();
return Result.SUCCESS;
}
// Start timer on player move
if (!player.getTag(Tag.Boolean("parkour_timerStarted"))) {
startTimer();
return Result.SUCCESS;
}
// Deal with completing checkpoints
if (currentCheckpoint < checkpoints.length - 1) { // Stop IndexOutOfBounds errors
if (player.getPosition().sameBlock(checkpoints[currentCheckpoint + 1])) { // Actually check the checkpoint
handleCheckpoint();
return Result.SUCCESS;
}
}
// Deal with finish
if (playerPosition.sameBlock(instance.getTag(Tag.Transient("finishPos")))) {
if (currentCheckpoint == checkpoints.length - 1) {
handleFinish();
} else {
player.sendMessage(parkourMinigame.getChatPrefix()
.append(Component.text("You've missed some checkpoints! Go back and grab them or use the"))
.append(Component.text(" blaze powder ")
.hoverEvent(HoverEvent.showItem(HoverEvent.ShowItem.showItem(Key.key("minecraft:blaze_powder"), 1)))
.decorate(TextDecoration.BOLD)
)
.append(Component.text("to restart the course"))
);
}
return Result.SUCCESS;
}
return Result.SUCCESS;
}
private void handleDeath() {
player.sendMessage(parkourMinigame.getChatPrefix().append(Component.text("Ya died :("))); // TODO: Random death message
ParkourMinigame.sendToCheckpoint(player); | package net.endercube.Parkour.listeners;
/**
* Most of the logic for the game is in here... I should really clean this code up
*/
public class PlayerMove implements EventListener<PlayerMoveEvent> {
private EndercubePlayer player;
private Pos playerPosition;
private Instance instance;
private Pos[] checkpoints;
private int currentCheckpoint;
private String mapName;
private Scheduler scheduler;
@Override
public @NotNull Class<PlayerMoveEvent> eventType() {
return PlayerMoveEvent.class;
}
@Override
public @NotNull Result run(@NotNull PlayerMoveEvent event) {
player = (EndercubePlayer) event.getPlayer();
playerPosition = player.getPosition();
instance = player.getInstance();
checkpoints = instance.getTag(Tag.Transient("checkpointsPosArray"));
currentCheckpoint = player.getTag(Tag.Integer("parkour_checkpoint"));
mapName = instance.getTag(Tag.String("name"));
scheduler = player.scheduler();
// See if player is below the death barrier and if so, teleport them to current checkpoint
if (player.getPosition().y() < instance.getTag(Tag.Integer("death-y"))) {
this.handleDeath();
return Result.SUCCESS;
}
// Start timer on player move
if (!player.getTag(Tag.Boolean("parkour_timerStarted"))) {
startTimer();
return Result.SUCCESS;
}
// Deal with completing checkpoints
if (currentCheckpoint < checkpoints.length - 1) { // Stop IndexOutOfBounds errors
if (player.getPosition().sameBlock(checkpoints[currentCheckpoint + 1])) { // Actually check the checkpoint
handleCheckpoint();
return Result.SUCCESS;
}
}
// Deal with finish
if (playerPosition.sameBlock(instance.getTag(Tag.Transient("finishPos")))) {
if (currentCheckpoint == checkpoints.length - 1) {
handleFinish();
} else {
player.sendMessage(parkourMinigame.getChatPrefix()
.append(Component.text("You've missed some checkpoints! Go back and grab them or use the"))
.append(Component.text(" blaze powder ")
.hoverEvent(HoverEvent.showItem(HoverEvent.ShowItem.showItem(Key.key("minecraft:blaze_powder"), 1)))
.decorate(TextDecoration.BOLD)
)
.append(Component.text("to restart the course"))
);
}
return Result.SUCCESS;
}
return Result.SUCCESS;
}
private void handleDeath() {
player.sendMessage(parkourMinigame.getChatPrefix().append(Component.text("Ya died :("))); // TODO: Random death message
ParkourMinigame.sendToCheckpoint(player); | logger.debug(player.getUsername() + " died on " + mapName); | 3 | 2023-12-10 12:08:18+00:00 | 8k |
lukebemishprojects/Tempest | fabriquilt/src/main/java/dev/lukebemish/tempest/impl/fabriquilt/mixin/client/RebuildTaskMixin.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 com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import com.llamalad7.mixinextras.sugar.Share;
import com.llamalad7.mixinextras.sugar.ref.LocalRef;
import com.mojang.blaze3d.vertex.BufferBuilder;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import dev.lukebemish.tempest.impl.Services;
import dev.lukebemish.tempest.impl.client.LevelChunkHolder;
import dev.lukebemish.tempest.impl.client.OverlaySpriteListener;
import dev.lukebemish.tempest.impl.client.QuadHelper;
import dev.lukebemish.tempest.impl.mixin.client.DispatchRenderChunkAccessor;
import net.minecraft.client.renderer.ChunkBufferBuilderPack;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.block.BlockRenderDispatcher;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.chunk.ChunkRenderDispatcher;
import net.minecraft.client.renderer.chunk.RenderChunkRegion;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.util.RandomSource;
import net.minecraft.world.level.BlockAndTintGetter;
import net.minecraft.world.level.block.state.BlockState;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.List;
import java.util.Set;
import java.util.function.Function; | 3,629 | package dev.lukebemish.tempest.impl.fabriquilt.mixin.client;
@Mixin(targets = "net.minecraft.client.renderer.chunk.ChunkRenderDispatcher$RenderChunk$RebuildTask")
public class RebuildTaskMixin {
@Shadow
@Nullable
protected RenderChunkRegion region;
@Unique
private ChunkRenderDispatcher.RenderChunk renderChunk;
@Inject(
method = "<init>(Lnet/minecraft/client/renderer/chunk/ChunkRenderDispatcher$RenderChunk;DLnet/minecraft/client/renderer/chunk/RenderChunkRegion;Z)V",
at = @At("RETURN")
)
private void tempest$init(ChunkRenderDispatcher.RenderChunk renderChunk, double distAtCreation, @Nullable RenderChunkRegion region, boolean isHighPriority, CallbackInfo ci) {
this.renderChunk = renderChunk;
}
@ModifyVariable(
method = "compile(FFFLnet/minecraft/client/renderer/ChunkBufferBuilderPack;)Lnet/minecraft/client/renderer/chunk/ChunkRenderDispatcher$RenderChunk$RebuildTask$CompileResults;",
at = @At("STORE")
)
private Set<RenderType> tempest$captureSet(Set<RenderType> set, @Share("set") LocalRef<Set<RenderType>> setRef) {
setRef.set(set);
return set;
}
@Inject(
method = "compile(FFFLnet/minecraft/client/renderer/ChunkBufferBuilderPack;)Lnet/minecraft/client/renderer/chunk/ChunkRenderDispatcher$RenderChunk$RebuildTask$CompileResults;",
at = @At("HEAD")
)
private void tempest$clearSet(float x, float y, float z, ChunkBufferBuilderPack buffers, CallbackInfoReturnable<?> ci, @Share("region") LocalRef<RenderChunkRegion> regionRef) {
regionRef.set(region);
}
@WrapOperation(
method = "compile(FFFLnet/minecraft/client/renderer/ChunkBufferBuilderPack;)Lnet/minecraft/client/renderer/chunk/ChunkRenderDispatcher$RenderChunk$RebuildTask$CompileResults;",
at = @At(
value = "INVOKE",
target = "Lnet/minecraft/client/renderer/block/BlockRenderDispatcher;renderBatched(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/BlockAndTintGetter;Lcom/mojang/blaze3d/vertex/PoseStack;Lcom/mojang/blaze3d/vertex/VertexConsumer;ZLnet/minecraft/util/RandomSource;)V"
)
)
private void tempest$addBlackIceQuads(
BlockRenderDispatcher blockRenderDispatcher,
BlockState state,
BlockPos pos,
BlockAndTintGetter blockAndTintGetter,
PoseStack poseStack,
VertexConsumer vertexConsumer,
boolean checkSides,
RandomSource random,
Operation<Void> operation,
float x, float y, float z, ChunkBufferBuilderPack buffers,
@Share("set") LocalRef<Set<RenderType>> setRef,
@Share("region") LocalRef<RenderChunkRegion> regionRef
) {
operation.call(blockRenderDispatcher, state, pos, blockAndTintGetter, poseStack, vertexConsumer, checkSides, random);
var re = regionRef.get();
if (re != null) {
TextureAtlasSprite sprite;
var level = ((LevelChunkHolder) re).tempest$level();
var chunk = LevelChunkHolder.tempest$chunkAt(re, pos); | package dev.lukebemish.tempest.impl.fabriquilt.mixin.client;
@Mixin(targets = "net.minecraft.client.renderer.chunk.ChunkRenderDispatcher$RenderChunk$RebuildTask")
public class RebuildTaskMixin {
@Shadow
@Nullable
protected RenderChunkRegion region;
@Unique
private ChunkRenderDispatcher.RenderChunk renderChunk;
@Inject(
method = "<init>(Lnet/minecraft/client/renderer/chunk/ChunkRenderDispatcher$RenderChunk;DLnet/minecraft/client/renderer/chunk/RenderChunkRegion;Z)V",
at = @At("RETURN")
)
private void tempest$init(ChunkRenderDispatcher.RenderChunk renderChunk, double distAtCreation, @Nullable RenderChunkRegion region, boolean isHighPriority, CallbackInfo ci) {
this.renderChunk = renderChunk;
}
@ModifyVariable(
method = "compile(FFFLnet/minecraft/client/renderer/ChunkBufferBuilderPack;)Lnet/minecraft/client/renderer/chunk/ChunkRenderDispatcher$RenderChunk$RebuildTask$CompileResults;",
at = @At("STORE")
)
private Set<RenderType> tempest$captureSet(Set<RenderType> set, @Share("set") LocalRef<Set<RenderType>> setRef) {
setRef.set(set);
return set;
}
@Inject(
method = "compile(FFFLnet/minecraft/client/renderer/ChunkBufferBuilderPack;)Lnet/minecraft/client/renderer/chunk/ChunkRenderDispatcher$RenderChunk$RebuildTask$CompileResults;",
at = @At("HEAD")
)
private void tempest$clearSet(float x, float y, float z, ChunkBufferBuilderPack buffers, CallbackInfoReturnable<?> ci, @Share("region") LocalRef<RenderChunkRegion> regionRef) {
regionRef.set(region);
}
@WrapOperation(
method = "compile(FFFLnet/minecraft/client/renderer/ChunkBufferBuilderPack;)Lnet/minecraft/client/renderer/chunk/ChunkRenderDispatcher$RenderChunk$RebuildTask$CompileResults;",
at = @At(
value = "INVOKE",
target = "Lnet/minecraft/client/renderer/block/BlockRenderDispatcher;renderBatched(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/BlockAndTintGetter;Lcom/mojang/blaze3d/vertex/PoseStack;Lcom/mojang/blaze3d/vertex/VertexConsumer;ZLnet/minecraft/util/RandomSource;)V"
)
)
private void tempest$addBlackIceQuads(
BlockRenderDispatcher blockRenderDispatcher,
BlockState state,
BlockPos pos,
BlockAndTintGetter blockAndTintGetter,
PoseStack poseStack,
VertexConsumer vertexConsumer,
boolean checkSides,
RandomSource random,
Operation<Void> operation,
float x, float y, float z, ChunkBufferBuilderPack buffers,
@Share("set") LocalRef<Set<RenderType>> setRef,
@Share("region") LocalRef<RenderChunkRegion> regionRef
) {
operation.call(blockRenderDispatcher, state, pos, blockAndTintGetter, poseStack, vertexConsumer, checkSides, random);
var re = regionRef.get();
if (re != null) {
TextureAtlasSprite sprite;
var level = ((LevelChunkHolder) re).tempest$level();
var chunk = LevelChunkHolder.tempest$chunkAt(re, pos); | var data = Services.PLATFORM.getChunkData(chunk); | 0 | 2023-12-06 23:23:31+00:00 | 8k |
dractical/InventoryPagesModified | src/main/java/org/aidan/inventorypages/InventoryPages.java | [
{
"identifier": "InventoryStringDeSerializer",
"path": "src/main/java/org/aidan/inventorypages/InventoryStringDeSerializer.java",
"snippet": "public class InventoryStringDeSerializer {\n public static String toBase64(Inventory inventory) {\n return toBase64(inventory.getContents());\n }\n\n... | import org.aidan.inventorypages.InventoryStringDeSerializer;
import org.aidan.inventorypages.MetricsLite;
import org.aidan.inventorypages.MySQLConnector;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.event.player.*;
import org.bukkit.inventory.*;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
import java.io.File;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;
import java.util.Map.Entry; | 5,368 | package org.aidan.inventorypages;
public class InventoryPages extends JavaPlugin implements Listener {
File crashedFile = new File(getDataFolder() + "/backups/crashed.yml");
FileConfiguration crashedData = YamlConfiguration.loadConfiguration(crashedFile);
private HashMap<String, org.aidan.inventorypages.CustomInventory> playerInvs = new HashMap<String, org.aidan.inventorypages.CustomInventory>();
org.aidan.inventorypages.ColorConverter colorConv = new org.aidan.inventorypages.ColorConverter(this);
private ItemStack nextItem, prevItem, noPageItem;
private Integer prevPos, nextPos;
private List<String> clearCommands;
private String noPermission, clear, clearAll, itemsMerged, itemsDropped;
private Boolean logSavesEnabled;
private String logSavesMessage;
private MySQLConnector mySQLConnector;
private HashMap<UUID, List<ItemStack>> pickupStash;
private org.aidan.inventorypages.DatabaseManager databaseManager;
// ======================================
// Enable
// ======================================
public void onEnable() {
saveDefaultConfig();
Bukkit.getServer().getLogger().info("[InventoryPages] Registering events.");
Bukkit.getServer().getPluginManager().registerEvents(this, this);
if (getConfig().getBoolean("mysql.enabled")) {
// MySQL Connections
this.mySQLConnector = new MySQLConnector(this);
this.mySQLConnector.connect();
this.mySQLConnector.checkAndCreateTable(); // Check and create table if necessary
// Initialize and setup database
this.databaseManager = new org.aidan.inventorypages.DatabaseManager(this);
this.databaseManager.initializeDatabase();
}
if (getConfig().getBoolean("metrics")) {
try { | package org.aidan.inventorypages;
public class InventoryPages extends JavaPlugin implements Listener {
File crashedFile = new File(getDataFolder() + "/backups/crashed.yml");
FileConfiguration crashedData = YamlConfiguration.loadConfiguration(crashedFile);
private HashMap<String, org.aidan.inventorypages.CustomInventory> playerInvs = new HashMap<String, org.aidan.inventorypages.CustomInventory>();
org.aidan.inventorypages.ColorConverter colorConv = new org.aidan.inventorypages.ColorConverter(this);
private ItemStack nextItem, prevItem, noPageItem;
private Integer prevPos, nextPos;
private List<String> clearCommands;
private String noPermission, clear, clearAll, itemsMerged, itemsDropped;
private Boolean logSavesEnabled;
private String logSavesMessage;
private MySQLConnector mySQLConnector;
private HashMap<UUID, List<ItemStack>> pickupStash;
private org.aidan.inventorypages.DatabaseManager databaseManager;
// ======================================
// Enable
// ======================================
public void onEnable() {
saveDefaultConfig();
Bukkit.getServer().getLogger().info("[InventoryPages] Registering events.");
Bukkit.getServer().getPluginManager().registerEvents(this, this);
if (getConfig().getBoolean("mysql.enabled")) {
// MySQL Connections
this.mySQLConnector = new MySQLConnector(this);
this.mySQLConnector.connect();
this.mySQLConnector.checkAndCreateTable(); // Check and create table if necessary
// Initialize and setup database
this.databaseManager = new org.aidan.inventorypages.DatabaseManager(this);
this.databaseManager.initializeDatabase();
}
if (getConfig().getBoolean("metrics")) {
try { | MetricsLite metrics = new MetricsLite(this); | 1 | 2023-12-13 03:39:32+00:00 | 8k |
xhtcode/xht-cloud-parent | xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/dept/service/impl/SysPositionServiceImpl.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.baomidou.mybatisplus.core.metadata.IPage;
import com.xht.cloud.framework.core.api.response.PageResponse;
import com.xht.cloud.framework.exception.business.BizException;
import com.xht.cloud.framework.mybatis.tool.PageTool;
import com.xht.cloud.system.module.dept.controller.request.SysPositionAddRequest;
import com.xht.cloud.system.module.dept.controller.request.SysPositionQueryRequest;
import com.xht.cloud.system.module.dept.controller.request.SysPositionUpdateRequest;
import com.xht.cloud.system.module.dept.controller.response.SysPositionResponse;
import com.xht.cloud.system.module.dept.convert.SysPositionConvert;
import com.xht.cloud.system.module.dept.dao.dataobject.SysPositionDO;
import com.xht.cloud.system.module.dept.dao.mapper.SysPositionMapper;
import com.xht.cloud.system.module.dept.dao.wrapper.SysPositionWrapper;
import com.xht.cloud.system.module.dept.service.ISysPositionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Objects; | 4,714 | package com.xht.cloud.system.module.dept.service.impl;
/**
* 描述 :岗位信息
*
* @author : xht
**/
@Slf4j
@Service
@RequiredArgsConstructor
public class SysPositionServiceImpl implements ISysPositionService {
private final SysPositionMapper sysPositionMapper;
private final SysPositionConvert sysPositionConvert;
/**
* 创建
*
* @param addRequest {@link SysPositionAddRequest}
* @return {@link String} 主键
*/
@Override
@Transactional(rollbackFor = Exception.class)
public String create(SysPositionAddRequest addRequest) {
SysPositionDO entity = sysPositionConvert.toDO(addRequest);
sysPositionMapper.insert(entity);
return entity.getId();
}
/**
* 根据id修改
*
* @param updateRequest SysPositionUpdateRequest
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void update(SysPositionUpdateRequest updateRequest) {
if (Objects.isNull(findById(updateRequest.getId()))) {
throw new BizException("修改的对象不存在!");
}
sysPositionMapper.updateById(sysPositionConvert.toDO(updateRequest));
}
/**
* 删除
*
* @param ids {@link List<String>} id集合
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void remove(List<String> ids) {
sysPositionMapper.deleteBatchIds(ids);
}
/**
* 根据id查询详细
*
* @param id {@link String} 数据库主键
* @return {@link SysPositionResponse}
*/
@Override
public SysPositionResponse findById(String id) {
return sysPositionConvert.toResponse(sysPositionMapper.findById(id).orElse(null));
}
/**
* 分页查询
*
* @param queryRequest {@link SysPositionQueryRequest}
* @return {@link PageResponse<SysPositionResponse>} 分页详情
*/
@Override | package com.xht.cloud.system.module.dept.service.impl;
/**
* 描述 :岗位信息
*
* @author : xht
**/
@Slf4j
@Service
@RequiredArgsConstructor
public class SysPositionServiceImpl implements ISysPositionService {
private final SysPositionMapper sysPositionMapper;
private final SysPositionConvert sysPositionConvert;
/**
* 创建
*
* @param addRequest {@link SysPositionAddRequest}
* @return {@link String} 主键
*/
@Override
@Transactional(rollbackFor = Exception.class)
public String create(SysPositionAddRequest addRequest) {
SysPositionDO entity = sysPositionConvert.toDO(addRequest);
sysPositionMapper.insert(entity);
return entity.getId();
}
/**
* 根据id修改
*
* @param updateRequest SysPositionUpdateRequest
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void update(SysPositionUpdateRequest updateRequest) {
if (Objects.isNull(findById(updateRequest.getId()))) {
throw new BizException("修改的对象不存在!");
}
sysPositionMapper.updateById(sysPositionConvert.toDO(updateRequest));
}
/**
* 删除
*
* @param ids {@link List<String>} id集合
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void remove(List<String> ids) {
sysPositionMapper.deleteBatchIds(ids);
}
/**
* 根据id查询详细
*
* @param id {@link String} 数据库主键
* @return {@link SysPositionResponse}
*/
@Override
public SysPositionResponse findById(String id) {
return sysPositionConvert.toResponse(sysPositionMapper.findById(id).orElse(null));
}
/**
* 分页查询
*
* @param queryRequest {@link SysPositionQueryRequest}
* @return {@link PageResponse<SysPositionResponse>} 分页详情
*/
@Override | public PageResponse<SysPositionResponse> findPage(SysPositionQueryRequest queryRequest) { | 4 | 2023-12-12 08:16:30+00:00 | 8k |
Utils4J/JavaUtils | src/main/java/de/mineking/javautils/database/TypeMapper.java | [
{
"identifier": "ID",
"path": "src/main/java/de/mineking/javautils/ID.java",
"snippet": "public class ID {\n\tprivate final static Base62 base62 = Base62.createInstance();\n\tpublic final static int size = Long.BYTES + Byte.BYTES; //Timestamp + Serial\n\n\tprivate static long lastTime = 0;\n\tprivate st... | import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.ToNumberStrategy;
import de.mineking.javautils.ID;
import de.mineking.javautils.database.type.DataType;
import de.mineking.javautils.database.type.PostgresType;
import de.mineking.javautils.reflection.ReflectionUtils;
import org.jdbi.v3.core.argument.Argument;
import org.jdbi.v3.core.statement.StatementContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger; | 3,940 |
@Nullable
@Override
public Integer extract(@NotNull ResultSet set, @NotNull String name, @NotNull Type target) throws SQLException {
return (Integer) set.getObject(name);
}
};
TypeMapper<Long, Long> LONG = new TypeMapper<>() {
@Override
public boolean accepts(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f) {
return type.equals(long.class) || type.equals(Long.class);
}
@NotNull
@Override
public DataType getType(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f) {
return PostgresType.BIG_INT;
}
@Nullable
@Override
public Long extract(@NotNull ResultSet set, @NotNull String name, @NotNull Type target) throws SQLException {
return (Long) set.getObject(name);
}
};
TypeMapper<Double, Double> DOUBLE = new TypeMapper<>() {
@Override
public boolean accepts(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f) {
return type.equals(double.class) || type.equals(Double.class);
}
@NotNull
@Override
public DataType getType(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f) {
return PostgresType.NUMERIC;
}
@Nullable
@Override
public Double extract(@NotNull ResultSet set, @NotNull String name, @NotNull Type target) throws SQLException {
return (Double) set.getObject(name);
}
};
TypeMapper<Boolean, Boolean> BOOLEAN = new TypeMapper<>() {
@Override
public boolean accepts(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f) {
return type.equals(boolean.class) || type.equals(Boolean.class);
}
@NotNull
@Override
public DataType getType(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f) {
return PostgresType.BOOLEAN;
}
@Nullable
@Override
public Boolean extract(@NotNull ResultSet set, @NotNull String name, @NotNull Type target) throws SQLException {
return (Boolean) set.getObject(name);
}
};
TypeMapper<String, String> STRING = new TypeMapper<>() {
@Override
public boolean accepts(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f) {
return ReflectionUtils.getClass(type).isAssignableFrom(String.class);
}
@NotNull
@Override
public DataType getType(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f) {
return PostgresType.TEXT;
}
@Nullable
@Override
public String extract(@NotNull ResultSet set, @NotNull String name, @NotNull Type target) throws SQLException {
return set.getString(name);
}
};
TypeMapper<Instant, Instant> TIMESTAMP = new TypeMapper<>() {
@Override
public boolean accepts(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f) {
return ReflectionUtils.getClass(type).isAssignableFrom(Instant.class);
}
@NotNull
@Override
public Argument createArgument(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f, @Nullable Instant value) {
return new Argument() {
@Override
public void apply(int position, PreparedStatement statement, StatementContext ctx) throws SQLException {
statement.setTimestamp(position, value == null ? null : Timestamp.from(value));
}
@Override
public String toString() {
return Objects.toString(value);
}
};
}
@NotNull
@Override
public DataType getType(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f) {
return PostgresType.TIMESTAMP;
}
@Nullable
@Override
public Instant extract(@NotNull ResultSet set, @NotNull String name, @NotNull Type target) throws SQLException {
var timestamp = set.getTimestamp(name);
return timestamp == null ? null : timestamp.toInstant();
}
};
| package de.mineking.javautils.database;
public interface TypeMapper<T, R> {
boolean accepts(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f);
@NotNull
DataType getType(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f);
@NotNull
default Argument createArgument(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f, @Nullable T value) {
return new Argument() {
@Override
public void apply(int position, PreparedStatement statement, StatementContext ctx) throws SQLException {
statement.setObject(position, value);
}
@Override
public String toString() {
return Objects.toString(value);
}
};
}
@Nullable
@SuppressWarnings("unchecked")
default T format(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f, @Nullable R value) {
return (T) value;
}
@Nullable
T extract(@NotNull ResultSet set, @NotNull String name, @NotNull Type target) throws SQLException;
@SuppressWarnings("unchecked")
@Nullable
default R parse(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field field, @Nullable T value) {
return (R) value;
}
TypeMapper<Integer, Integer> SERIAL = new TypeMapper<>() {
@Override
public boolean accepts(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f) {
return f.getAnnotation(Column.class).autoincrement() && (type.equals(int.class) || type.equals(long.class));
}
@NotNull
@Override
public DataType getType(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f) {
return type.equals(int.class) ? PostgresType.SERIAL : PostgresType.BIG_SERIAL;
}
@Nullable
@Override
public Integer extract(@NotNull ResultSet set, @NotNull String name, @NotNull Type target) throws SQLException {
return (Integer) set.getObject(name);
}
};
TypeMapper<Integer, Integer> INTEGER = new TypeMapper<>() {
@Override
public boolean accepts(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f) {
return type.equals(int.class) || type.equals(Integer.class);
}
@NotNull
@Override
public DataType getType(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f) {
return PostgresType.INTEGER;
}
@Nullable
@Override
public Integer extract(@NotNull ResultSet set, @NotNull String name, @NotNull Type target) throws SQLException {
return (Integer) set.getObject(name);
}
};
TypeMapper<Long, Long> LONG = new TypeMapper<>() {
@Override
public boolean accepts(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f) {
return type.equals(long.class) || type.equals(Long.class);
}
@NotNull
@Override
public DataType getType(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f) {
return PostgresType.BIG_INT;
}
@Nullable
@Override
public Long extract(@NotNull ResultSet set, @NotNull String name, @NotNull Type target) throws SQLException {
return (Long) set.getObject(name);
}
};
TypeMapper<Double, Double> DOUBLE = new TypeMapper<>() {
@Override
public boolean accepts(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f) {
return type.equals(double.class) || type.equals(Double.class);
}
@NotNull
@Override
public DataType getType(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f) {
return PostgresType.NUMERIC;
}
@Nullable
@Override
public Double extract(@NotNull ResultSet set, @NotNull String name, @NotNull Type target) throws SQLException {
return (Double) set.getObject(name);
}
};
TypeMapper<Boolean, Boolean> BOOLEAN = new TypeMapper<>() {
@Override
public boolean accepts(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f) {
return type.equals(boolean.class) || type.equals(Boolean.class);
}
@NotNull
@Override
public DataType getType(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f) {
return PostgresType.BOOLEAN;
}
@Nullable
@Override
public Boolean extract(@NotNull ResultSet set, @NotNull String name, @NotNull Type target) throws SQLException {
return (Boolean) set.getObject(name);
}
};
TypeMapper<String, String> STRING = new TypeMapper<>() {
@Override
public boolean accepts(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f) {
return ReflectionUtils.getClass(type).isAssignableFrom(String.class);
}
@NotNull
@Override
public DataType getType(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f) {
return PostgresType.TEXT;
}
@Nullable
@Override
public String extract(@NotNull ResultSet set, @NotNull String name, @NotNull Type target) throws SQLException {
return set.getString(name);
}
};
TypeMapper<Instant, Instant> TIMESTAMP = new TypeMapper<>() {
@Override
public boolean accepts(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f) {
return ReflectionUtils.getClass(type).isAssignableFrom(Instant.class);
}
@NotNull
@Override
public Argument createArgument(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f, @Nullable Instant value) {
return new Argument() {
@Override
public void apply(int position, PreparedStatement statement, StatementContext ctx) throws SQLException {
statement.setTimestamp(position, value == null ? null : Timestamp.from(value));
}
@Override
public String toString() {
return Objects.toString(value);
}
};
}
@NotNull
@Override
public DataType getType(@NotNull DatabaseManager manager, @NotNull Type type, @NotNull Field f) {
return PostgresType.TIMESTAMP;
}
@Nullable
@Override
public Instant extract(@NotNull ResultSet set, @NotNull String name, @NotNull Type target) throws SQLException {
var timestamp = set.getTimestamp(name);
return timestamp == null ? null : timestamp.toInstant();
}
};
| TypeMapper<String, ID> MKID = new TypeMapper<>() { | 0 | 2023-12-13 14:05:17+00:00 | 8k |
serendipitk/LunarCore | src/main/java/emu/lunarcore/data/ResourceLoader.java | [
{
"identifier": "LunarCore",
"path": "src/main/java/emu/lunarcore/LunarCore.java",
"snippet": "public class LunarCore {\n private static final Logger log = LoggerFactory.getLogger(LunarCore.class);\n private static File configFile = new File(\"./config.json\");\n @Getter private static Config c... | import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
import org.reflections.Reflections;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import emu.lunarcore.LunarCore;
import emu.lunarcore.data.ResourceDeserializers.LunarCoreDoubleDeserializer;
import emu.lunarcore.data.ResourceDeserializers.LunarCoreHashDeserializer;
import emu.lunarcore.data.config.FloorInfo;
import emu.lunarcore.data.config.FloorInfo.FloorGroupSimpleInfo;
import emu.lunarcore.data.config.GroupInfo;
import emu.lunarcore.data.config.SkillAbilityInfo;
import emu.lunarcore.data.config.SummonUnitInfo;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap; | 6,379 | package emu.lunarcore.data;
public class ResourceLoader {
private static boolean loaded = false;
// Special gson factory we create for loading resources
private static final Gson gson = new GsonBuilder()
.registerTypeAdapter(double.class, new LunarCoreDoubleDeserializer())
.registerTypeAdapter(long.class, new LunarCoreHashDeserializer())
.create();
// Load all resources
public static void loadAll() {
// Make sure we don't load more than once
if (loaded) return;
// Start loading resources
loadResources();
// Load floor infos after resources
loadFloorInfos();
// Load maze abilities
loadMazeAbilities();
// Load rogue maps
loadRogueMapGen();
// Done
loaded = true;
LunarCore.getLogger().info("Resource loading complete");
}
private static List<Class<?>> getResourceDefClasses() {
Reflections reflections = new Reflections(ResourceLoader.class.getPackage().getName());
Set<?> classes = reflections.getSubTypesOf(GameResource.class);
List<Class<?>> classList = new ArrayList<>(classes.size());
classes.forEach(o -> {
Class<?> c = (Class<?>) o;
if (c.getAnnotation(ResourceType.class) != null) {
classList.add(c);
}
});
classList.sort((a, b) -> b.getAnnotation(ResourceType.class).loadPriority().value() - a.getAnnotation(ResourceType.class).loadPriority().value());
return classList;
}
private static void loadResources() {
for (Class<?> resourceDefinition : getResourceDefClasses()) {
ResourceType type = resourceDefinition.getAnnotation(ResourceType.class);
if (type == null) {
continue;
}
@SuppressWarnings("rawtypes")
Int2ObjectMap map = GameData.getMapForExcel(resourceDefinition);
try {
loadFromResource(resourceDefinition, type, map);
} catch (FileNotFoundException e) {
LunarCore.getLogger().error("Resource file not found: {}.", Arrays.toString(type.name()));
} catch (Exception e) {
LunarCore.getLogger().error("Error loading resource file: " + Arrays.toString(type.name()), e);
}
}
}
@SuppressWarnings("rawtypes")
private static void loadFromResource(Class<?> c, ResourceType type, Int2ObjectMap map) throws Exception {
int count = 0;
for (String name : type.name()) {
count += loadFromResource(c, type, name, map);
}
LunarCore.getLogger().info("Loaded " + count + " " + c.getSimpleName() + "s.");
}
@SuppressWarnings({"rawtypes", "unchecked"})
private static <T> int loadFromResource(Class<T> c, ResourceType type, String fileName, Int2ObjectMap map) throws Exception {
String file = LunarCore.getConfig().getResourceDir() + "/ExcelOutput/" + fileName;
// Load reader from file
try (InputStreamReader fileReader = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)) {
// Setup variables
Stream<T> stream = null;
// Determine format of json
JsonElement json = JsonParser.parseReader(fileReader);
if (json.isJsonArray()) {
// Parse list
List<T> excels = gson.fromJson(json, TypeToken.getParameterized(List.class, c).getType());
stream = excels.stream();
} else if (json.isJsonObject()) {
// Check if object is map or a nested map
boolean isMap = true;
var it = json.getAsJsonObject().asMap().entrySet().iterator();
if (it.hasNext()) {
var it2 = it.next().getValue().getAsJsonObject().asMap().entrySet().iterator();
String key = it2.next().getKey();
try {
Integer.parseInt(key);
isMap = false;
} catch (Exception ex) {
}
}
// Parse json
if (isMap) {
// Map
Map<Integer, T> excels = gson.fromJson(json, TypeToken.getParameterized(Map.class, Integer.class, c).getType());
stream = excels.values().stream();
} else {
// Nested Map
Map<Integer, Map<Integer, T>> excels = gson.fromJson(json, TypeToken.getParameterized(Map.class, Integer.class, TypeToken.getParameterized(Map.class, Integer.class, c).getType()).getType());
stream = excels.values().stream().flatMap(m -> m.values().stream());
}
} else {
throw new Exception("Invalid excel file: " + fileName);
}
// Sanity check
if (stream == null) return 0;
// Mutable integer
AtomicInteger count = new AtomicInteger();
stream.forEach(o -> {
GameResource res = (GameResource) o;
res.onLoad();
count.getAndIncrement();
if (map != null) {
map.put(res.getId(), res);
}
});
return count.get();
}
}
// Might be better to cache
private static void loadFloorInfos() {
// Load floor infos
LunarCore.getLogger().info("Loading floor infos... this may take a while.");
File floorDir = new File(LunarCore.getConfig().getResourceDir() + "/Config/LevelOutput/Floor/");
boolean missingGroupInfos = false;
if (!floorDir.exists()) {
LunarCore.getLogger().warn("Floor infos are missing, please check your resources folder: {resources}/Config/LevelOutput/Floor. Teleports and natural world spawns may not work!");
return;
}
// Load floor infos
for (File file : floorDir.listFiles()) {
try (FileReader reader = new FileReader(file)) {
FloorInfo floor = gson.fromJson(reader, FloorInfo.class);
String name = file.getName().substring(0, file.getName().indexOf('.'));
GameData.getFloorInfos().put(name, floor);
} catch (Exception e) {
e.printStackTrace();
}
}
// Load group infos
for (FloorInfo floor : GameData.getFloorInfos().values()) {
for (FloorGroupSimpleInfo simpleGroup : floor.getSimpleGroupList()) {
File file = new File(LunarCore.getConfig().getResourceDir() + "/" + simpleGroup.getGroupPath());
if (!file.exists()) continue;
// TODO optimize
try (FileReader reader = new FileReader(file)) { | package emu.lunarcore.data;
public class ResourceLoader {
private static boolean loaded = false;
// Special gson factory we create for loading resources
private static final Gson gson = new GsonBuilder()
.registerTypeAdapter(double.class, new LunarCoreDoubleDeserializer())
.registerTypeAdapter(long.class, new LunarCoreHashDeserializer())
.create();
// Load all resources
public static void loadAll() {
// Make sure we don't load more than once
if (loaded) return;
// Start loading resources
loadResources();
// Load floor infos after resources
loadFloorInfos();
// Load maze abilities
loadMazeAbilities();
// Load rogue maps
loadRogueMapGen();
// Done
loaded = true;
LunarCore.getLogger().info("Resource loading complete");
}
private static List<Class<?>> getResourceDefClasses() {
Reflections reflections = new Reflections(ResourceLoader.class.getPackage().getName());
Set<?> classes = reflections.getSubTypesOf(GameResource.class);
List<Class<?>> classList = new ArrayList<>(classes.size());
classes.forEach(o -> {
Class<?> c = (Class<?>) o;
if (c.getAnnotation(ResourceType.class) != null) {
classList.add(c);
}
});
classList.sort((a, b) -> b.getAnnotation(ResourceType.class).loadPriority().value() - a.getAnnotation(ResourceType.class).loadPriority().value());
return classList;
}
private static void loadResources() {
for (Class<?> resourceDefinition : getResourceDefClasses()) {
ResourceType type = resourceDefinition.getAnnotation(ResourceType.class);
if (type == null) {
continue;
}
@SuppressWarnings("rawtypes")
Int2ObjectMap map = GameData.getMapForExcel(resourceDefinition);
try {
loadFromResource(resourceDefinition, type, map);
} catch (FileNotFoundException e) {
LunarCore.getLogger().error("Resource file not found: {}.", Arrays.toString(type.name()));
} catch (Exception e) {
LunarCore.getLogger().error("Error loading resource file: " + Arrays.toString(type.name()), e);
}
}
}
@SuppressWarnings("rawtypes")
private static void loadFromResource(Class<?> c, ResourceType type, Int2ObjectMap map) throws Exception {
int count = 0;
for (String name : type.name()) {
count += loadFromResource(c, type, name, map);
}
LunarCore.getLogger().info("Loaded " + count + " " + c.getSimpleName() + "s.");
}
@SuppressWarnings({"rawtypes", "unchecked"})
private static <T> int loadFromResource(Class<T> c, ResourceType type, String fileName, Int2ObjectMap map) throws Exception {
String file = LunarCore.getConfig().getResourceDir() + "/ExcelOutput/" + fileName;
// Load reader from file
try (InputStreamReader fileReader = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)) {
// Setup variables
Stream<T> stream = null;
// Determine format of json
JsonElement json = JsonParser.parseReader(fileReader);
if (json.isJsonArray()) {
// Parse list
List<T> excels = gson.fromJson(json, TypeToken.getParameterized(List.class, c).getType());
stream = excels.stream();
} else if (json.isJsonObject()) {
// Check if object is map or a nested map
boolean isMap = true;
var it = json.getAsJsonObject().asMap().entrySet().iterator();
if (it.hasNext()) {
var it2 = it.next().getValue().getAsJsonObject().asMap().entrySet().iterator();
String key = it2.next().getKey();
try {
Integer.parseInt(key);
isMap = false;
} catch (Exception ex) {
}
}
// Parse json
if (isMap) {
// Map
Map<Integer, T> excels = gson.fromJson(json, TypeToken.getParameterized(Map.class, Integer.class, c).getType());
stream = excels.values().stream();
} else {
// Nested Map
Map<Integer, Map<Integer, T>> excels = gson.fromJson(json, TypeToken.getParameterized(Map.class, Integer.class, TypeToken.getParameterized(Map.class, Integer.class, c).getType()).getType());
stream = excels.values().stream().flatMap(m -> m.values().stream());
}
} else {
throw new Exception("Invalid excel file: " + fileName);
}
// Sanity check
if (stream == null) return 0;
// Mutable integer
AtomicInteger count = new AtomicInteger();
stream.forEach(o -> {
GameResource res = (GameResource) o;
res.onLoad();
count.getAndIncrement();
if (map != null) {
map.put(res.getId(), res);
}
});
return count.get();
}
}
// Might be better to cache
private static void loadFloorInfos() {
// Load floor infos
LunarCore.getLogger().info("Loading floor infos... this may take a while.");
File floorDir = new File(LunarCore.getConfig().getResourceDir() + "/Config/LevelOutput/Floor/");
boolean missingGroupInfos = false;
if (!floorDir.exists()) {
LunarCore.getLogger().warn("Floor infos are missing, please check your resources folder: {resources}/Config/LevelOutput/Floor. Teleports and natural world spawns may not work!");
return;
}
// Load floor infos
for (File file : floorDir.listFiles()) {
try (FileReader reader = new FileReader(file)) {
FloorInfo floor = gson.fromJson(reader, FloorInfo.class);
String name = file.getName().substring(0, file.getName().indexOf('.'));
GameData.getFloorInfos().put(name, floor);
} catch (Exception e) {
e.printStackTrace();
}
}
// Load group infos
for (FloorInfo floor : GameData.getFloorInfos().values()) {
for (FloorGroupSimpleInfo simpleGroup : floor.getSimpleGroupList()) {
File file = new File(LunarCore.getConfig().getResourceDir() + "/" + simpleGroup.getGroupPath());
if (!file.exists()) continue;
// TODO optimize
try (FileReader reader = new FileReader(file)) { | GroupInfo group = gson.fromJson(reader, GroupInfo.class); | 5 | 2023-12-08 14:13:04+00:00 | 8k |
adabox-aio/dextreme-sdk | src/main/java/io/adabox/dextreme/dex/Minswap.java | [
{
"identifier": "MinSwapApi",
"path": "src/main/java/io/adabox/dextreme/dex/api/MinSwapApi.java",
"snippet": "@Slf4j\n@Getter\npublic class MinSwapApi extends Api {\n\n private final String marketOrderAddress = \"addr1wxn9efv2f6w82hagxqtn62ju4m293tqvw0uhmdl64ch8uwc0h43gt\";\n private final String ... | import co.nstant.in.cbor.model.ByteString;
import com.bloxbean.cardano.client.address.Address;
import com.bloxbean.cardano.client.address.AddressProvider;
import com.bloxbean.cardano.client.common.CardanoConstants;
import com.bloxbean.cardano.client.plutus.spec.*;
import com.bloxbean.cardano.client.util.HexUtil;
import io.adabox.dextreme.dex.api.MinSwapApi;
import io.adabox.dextreme.dex.base.Dex;
import io.adabox.dextreme.dex.base.DexType;
import io.adabox.dextreme.model.UTxO;
import io.adabox.dextreme.provider.ApiProvider;
import io.adabox.dextreme.provider.base.BaseProvider;
import org.apache.commons.lang3.StringUtils;
import java.math.BigInteger;
import java.util.List; | 4,880 | package io.adabox.dextreme.dex;
/**
* Minswap DEX
*/
public class Minswap extends Dex {
public static final String FACTORY_TOKEN = "13aa2accf2e1561723aa26871e071fdf32c867cff7e7d50ad470d62f4d494e53574150";
public static final String LP_TOKEN_POLICY_ID = "e4214b7cce62ac6fbba385d164df48e157eae5863521b4b67ca71d86";
public static final List<String> POOL_NFT_POLICY_IDs = List.of("0be55d262b29f564998ff81efe21bdc0022621c12f15af08d0f2ddb1");
public static final String MARKET_ORDER_ADDRESS = "addr1wxn9efv2f6w82hagxqtn62ju4m293tqvw0uhmdl64ch8uwc0h43gt";
public static final String LIMIT_ORDER_ADDRESS = "addr1zxn9efv2f6w82hagxqtn62ju4m293tqvw0uhmdl64ch8uw6j2c79gy9l76sdg0xwhd7r0c0kna0tycz4y5s6mlenh8pq6s3z70";
/**
* {@link Minswap}
* Default Constructor
*/
public Minswap() {
this(new ApiProvider());
}
/**
* {@link Minswap}
* @param provider provider
*/
public Minswap(BaseProvider provider) {
super(DexType.Minswap, provider, new MinSwapApi());
}
@Override
public String getFactoryToken() {
return FACTORY_TOKEN;
}
@Override
public List<String> getPoolNFTPolicyIds() {
return POOL_NFT_POLICY_IDs;
}
@Override
public String getLPTokenPolicyId() {
return LP_TOKEN_POLICY_ID;
}
@Override
public String getMarketOrderAddress() {
return MARKET_ORDER_ADDRESS;
}
@Override
public String getLimitOrderAddress() {
return LIMIT_ORDER_ADDRESS;
}
@Override | package io.adabox.dextreme.dex;
/**
* Minswap DEX
*/
public class Minswap extends Dex {
public static final String FACTORY_TOKEN = "13aa2accf2e1561723aa26871e071fdf32c867cff7e7d50ad470d62f4d494e53574150";
public static final String LP_TOKEN_POLICY_ID = "e4214b7cce62ac6fbba385d164df48e157eae5863521b4b67ca71d86";
public static final List<String> POOL_NFT_POLICY_IDs = List.of("0be55d262b29f564998ff81efe21bdc0022621c12f15af08d0f2ddb1");
public static final String MARKET_ORDER_ADDRESS = "addr1wxn9efv2f6w82hagxqtn62ju4m293tqvw0uhmdl64ch8uwc0h43gt";
public static final String LIMIT_ORDER_ADDRESS = "addr1zxn9efv2f6w82hagxqtn62ju4m293tqvw0uhmdl64ch8uw6j2c79gy9l76sdg0xwhd7r0c0kna0tycz4y5s6mlenh8pq6s3z70";
/**
* {@link Minswap}
* Default Constructor
*/
public Minswap() {
this(new ApiProvider());
}
/**
* {@link Minswap}
* @param provider provider
*/
public Minswap(BaseProvider provider) {
super(DexType.Minswap, provider, new MinSwapApi());
}
@Override
public String getFactoryToken() {
return FACTORY_TOKEN;
}
@Override
public List<String> getPoolNFTPolicyIds() {
return POOL_NFT_POLICY_IDs;
}
@Override
public String getLPTokenPolicyId() {
return LP_TOKEN_POLICY_ID;
}
@Override
public String getMarketOrderAddress() {
return MARKET_ORDER_ADDRESS;
}
@Override
public String getLimitOrderAddress() {
return LIMIT_ORDER_ADDRESS;
}
@Override | public double getPoolFeePercent(UTxO uTxO) { | 3 | 2023-12-10 12:14:48+00:00 | 8k |
zhaw-iwi/promise | src/test/java/ch/zhaw/statefulconversation/bots/SimpleBot.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.List;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ch.zhaw.statefulconversation.model.Agent;
import ch.zhaw.statefulconversation.model.Decision;
import ch.zhaw.statefulconversation.model.Final;
import ch.zhaw.statefulconversation.model.State;
import ch.zhaw.statefulconversation.model.Transition;
import ch.zhaw.statefulconversation.model.commons.decisions.StaticDecision;
import ch.zhaw.statefulconversation.repositories.AgentRepository; | 3,822 | package ch.zhaw.statefulconversation.bots;
@SpringBootTest
class SimpleBot {
@Autowired | package ch.zhaw.statefulconversation.bots;
@SpringBootTest
class SimpleBot {
@Autowired | private AgentRepository repository; | 6 | 2023-12-06 09:36:58+00:00 | 8k |
SkyDynamic/QuickBackupM-Fabric | src/main/java/dev/skydynamic/quickbackupmulti/command/QuickBackupMultiCommand.java | [
{
"identifier": "RestoreTask",
"path": "src/main/java/dev/skydynamic/quickbackupmulti/backup/RestoreTask.java",
"snippet": "public class RestoreTask extends TimerTask {\n\n private final EnvType env;\n private final List<ServerPlayerEntity> playerList;\n private final int slot;\n\n public Re... | import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.tree.LiteralCommandNode;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.arguments.StringArgumentType;
import dev.skydynamic.quickbackupmulti.backup.RestoreTask;
import dev.skydynamic.quickbackupmulti.i18n.LangSuggestionProvider;
import dev.skydynamic.quickbackupmulti.i18n.Translate;
import dev.skydynamic.quickbackupmulti.utils.Messenger;
import net.fabricmc.api.EnvType;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.command.CommandManager;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.ClickEvent;
import net.minecraft.text.HoverEvent;
import net.minecraft.text.MutableText;
import net.minecraft.text.Text;
import dev.skydynamic.quickbackupmulti.utils.config.Config;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Timer;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import static dev.skydynamic.quickbackupmulti.utils.QbmManager.*;
import static dev.skydynamic.quickbackupmulti.i18n.Translate.tr;
import static dev.skydynamic.quickbackupmulti.utils.schedule.CronUtil.*;
import static net.minecraft.server.command.CommandManager.literal; | 5,802 | package dev.skydynamic.quickbackupmulti.command;
//#if MC<11900
//$$ import com.mojang.brigadier.exceptions.CommandSyntaxException;
//#endif
public class QuickBackupMultiCommand {
private static final Logger logger = LoggerFactory.getLogger("Command");
public static void RegisterCommand(CommandDispatcher<ServerCommandSource> dispatcher) {
LiteralCommandNode<ServerCommandSource> QuickBackupMultiShortCommand = dispatcher.register(literal("qb")
.then(literal("list").executes(it -> listSaveBackups(it.getSource())))
.then(literal("make").requires(me -> me.hasPermissionLevel(2))
.executes(it -> makeSaveBackup(it.getSource(), -1, ""))
.then(CommandManager.argument("slot", IntegerArgumentType.integer(1))
.executes(it -> makeSaveBackup(it.getSource(), IntegerArgumentType.getInteger(it, "slot"), ""))
.then(CommandManager.argument("desc", StringArgumentType.string())
.executes(it -> makeSaveBackup(it.getSource(), IntegerArgumentType.getInteger(it, "slot"), StringArgumentType.getString(it, "desc"))))
)
.then(CommandManager.argument("desc", StringArgumentType.string())
.executes(it -> makeSaveBackup(it.getSource(), -1, StringArgumentType.getString(it, "desc"))))
)
.then(literal("back").requires(me -> me.hasPermissionLevel(2))
.executes(it -> restoreSaveBackup(it.getSource(), 1))
.then(CommandManager.argument("slot", IntegerArgumentType.integer(1))
.executes(it -> restoreSaveBackup(it.getSource(), IntegerArgumentType.getInteger(it, "slot")))))
.then(literal("confirm").requires(me -> me.hasPermissionLevel(2))
.executes(it -> {
try {
executeRestore(it.getSource());
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}))
.then(literal("cancel").requires(me -> me.hasPermissionLevel(2))
.executes(it -> cancelRestore(it.getSource())))
.then(literal("delete").requires(me -> me.hasPermissionLevel(2))
.then(CommandManager.argument("slot", IntegerArgumentType.integer(1))
.executes(it -> deleteSaveBackup(it.getSource(), IntegerArgumentType.getInteger(it, "slot")))))
.then(literal("setting").requires(me -> me.hasPermissionLevel(2))
.then(literal("lang")
.then(literal("get").executes(it -> getLang(it.getSource())))
.then(literal("set").requires(me -> me.hasPermissionLevel(2))
.then(CommandManager.argument("lang", StringArgumentType.string())
.suggests(new LangSuggestionProvider())
.executes(it -> setLang(it.getSource(), StringArgumentType.getString(it, "lang"))))))
.then(literal("schedule")
.then(literal("enable").executes(it -> enableScheduleBackup(it.getSource())))
.then(literal("disable").executes(it -> disableScheduleBackup(it.getSource())))
.then(literal("set")
.then(literal("interval")
.then(literal("second")
.then(CommandManager.argument("second", IntegerArgumentType.integer(1))
.executes(it -> setScheduleInterval(it.getSource(), IntegerArgumentType.getInteger(it, "second"), "s"))
)
).then(literal("minute")
.then(CommandManager.argument("minute", IntegerArgumentType.integer(1))
.executes(it -> setScheduleInterval(it.getSource(), IntegerArgumentType.getInteger(it, "minute"), "m"))
)
).then(literal("hour")
.then(CommandManager.argument("hour", IntegerArgumentType.integer(1))
.executes(it -> setScheduleInterval(it.getSource(), IntegerArgumentType.getInteger(it, "hour"), "h"))
)
).then(literal("day")
.then(CommandManager.argument("day", IntegerArgumentType.integer(1))
.executes(it -> setScheduleInterval(it.getSource(), IntegerArgumentType.getInteger(it, "day"), "d"))
)
)
)
.then(literal("cron")
.then(CommandManager.argument("cron", StringArgumentType.string())
.executes(it -> setScheduleCron(it.getSource(), StringArgumentType.getString(it, "cron")))))
.then(literal("mode")
.then(literal("switch")
.then(literal("interval")
.executes(it -> switchMode(it.getSource(), "interval")))
.then(literal("cron")
.executes(it -> switchMode(it.getSource(), "cron"))))
.then(literal("get").executes(it -> getScheduleMode(it.getSource()))))
)
.then(literal("get")
.executes(it -> getNextBackupTime(it.getSource())))
)
)
);
dispatcher.register(literal("quickbackupm").redirect(QuickBackupMultiShortCommand));
}
public static final ConcurrentHashMap<String, ConcurrentHashMap<String, Object>> QbDataHashMap = new ConcurrentHashMap<>();
private static int switchMode(ServerCommandSource commandSource, String mode) { | package dev.skydynamic.quickbackupmulti.command;
//#if MC<11900
//$$ import com.mojang.brigadier.exceptions.CommandSyntaxException;
//#endif
public class QuickBackupMultiCommand {
private static final Logger logger = LoggerFactory.getLogger("Command");
public static void RegisterCommand(CommandDispatcher<ServerCommandSource> dispatcher) {
LiteralCommandNode<ServerCommandSource> QuickBackupMultiShortCommand = dispatcher.register(literal("qb")
.then(literal("list").executes(it -> listSaveBackups(it.getSource())))
.then(literal("make").requires(me -> me.hasPermissionLevel(2))
.executes(it -> makeSaveBackup(it.getSource(), -1, ""))
.then(CommandManager.argument("slot", IntegerArgumentType.integer(1))
.executes(it -> makeSaveBackup(it.getSource(), IntegerArgumentType.getInteger(it, "slot"), ""))
.then(CommandManager.argument("desc", StringArgumentType.string())
.executes(it -> makeSaveBackup(it.getSource(), IntegerArgumentType.getInteger(it, "slot"), StringArgumentType.getString(it, "desc"))))
)
.then(CommandManager.argument("desc", StringArgumentType.string())
.executes(it -> makeSaveBackup(it.getSource(), -1, StringArgumentType.getString(it, "desc"))))
)
.then(literal("back").requires(me -> me.hasPermissionLevel(2))
.executes(it -> restoreSaveBackup(it.getSource(), 1))
.then(CommandManager.argument("slot", IntegerArgumentType.integer(1))
.executes(it -> restoreSaveBackup(it.getSource(), IntegerArgumentType.getInteger(it, "slot")))))
.then(literal("confirm").requires(me -> me.hasPermissionLevel(2))
.executes(it -> {
try {
executeRestore(it.getSource());
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}))
.then(literal("cancel").requires(me -> me.hasPermissionLevel(2))
.executes(it -> cancelRestore(it.getSource())))
.then(literal("delete").requires(me -> me.hasPermissionLevel(2))
.then(CommandManager.argument("slot", IntegerArgumentType.integer(1))
.executes(it -> deleteSaveBackup(it.getSource(), IntegerArgumentType.getInteger(it, "slot")))))
.then(literal("setting").requires(me -> me.hasPermissionLevel(2))
.then(literal("lang")
.then(literal("get").executes(it -> getLang(it.getSource())))
.then(literal("set").requires(me -> me.hasPermissionLevel(2))
.then(CommandManager.argument("lang", StringArgumentType.string())
.suggests(new LangSuggestionProvider())
.executes(it -> setLang(it.getSource(), StringArgumentType.getString(it, "lang"))))))
.then(literal("schedule")
.then(literal("enable").executes(it -> enableScheduleBackup(it.getSource())))
.then(literal("disable").executes(it -> disableScheduleBackup(it.getSource())))
.then(literal("set")
.then(literal("interval")
.then(literal("second")
.then(CommandManager.argument("second", IntegerArgumentType.integer(1))
.executes(it -> setScheduleInterval(it.getSource(), IntegerArgumentType.getInteger(it, "second"), "s"))
)
).then(literal("minute")
.then(CommandManager.argument("minute", IntegerArgumentType.integer(1))
.executes(it -> setScheduleInterval(it.getSource(), IntegerArgumentType.getInteger(it, "minute"), "m"))
)
).then(literal("hour")
.then(CommandManager.argument("hour", IntegerArgumentType.integer(1))
.executes(it -> setScheduleInterval(it.getSource(), IntegerArgumentType.getInteger(it, "hour"), "h"))
)
).then(literal("day")
.then(CommandManager.argument("day", IntegerArgumentType.integer(1))
.executes(it -> setScheduleInterval(it.getSource(), IntegerArgumentType.getInteger(it, "day"), "d"))
)
)
)
.then(literal("cron")
.then(CommandManager.argument("cron", StringArgumentType.string())
.executes(it -> setScheduleCron(it.getSource(), StringArgumentType.getString(it, "cron")))))
.then(literal("mode")
.then(literal("switch")
.then(literal("interval")
.executes(it -> switchMode(it.getSource(), "interval")))
.then(literal("cron")
.executes(it -> switchMode(it.getSource(), "cron"))))
.then(literal("get").executes(it -> getScheduleMode(it.getSource()))))
)
.then(literal("get")
.executes(it -> getNextBackupTime(it.getSource())))
)
)
);
dispatcher.register(literal("quickbackupm").redirect(QuickBackupMultiShortCommand));
}
public static final ConcurrentHashMap<String, ConcurrentHashMap<String, Object>> QbDataHashMap = new ConcurrentHashMap<>();
private static int switchMode(ServerCommandSource commandSource, String mode) { | Config.INSTANCE.setScheduleMode(mode); | 4 | 2023-12-09 13:51:17+00:00 | 8k |
quentin452/Garden-Stuff-Continuation | src/main/java/com/jaquadro/minecraft/gardencore/core/ModBlocks.java | [
{
"identifier": "TileEntityCompostBin",
"path": "src/main/java/com/jaquadro/minecraft/gardencore/block/tile/TileEntityCompostBin.java",
"snippet": "public class TileEntityCompostBin extends TileEntity implements ISidedInventory {\n\n private ItemStack[] compostItemStacks = new ItemStack[10];\n pub... | import com.jaquadro.minecraft.gardencore.block.*;
import com.jaquadro.minecraft.gardencore.block.tile.TileEntityCompostBin;
import com.jaquadro.minecraft.gardencore.block.tile.TileEntityGardenFarmland;
import com.jaquadro.minecraft.gardencore.block.tile.TileEntityGardenSoil;
import com.jaquadro.minecraft.gardencore.util.UniqueMetaIdentifier;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.registry.GameData;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.block.Block;
import org.apache.logging.log4j.Level; | 4,811 | package com.jaquadro.minecraft.gardencore.core;
public class ModBlocks {
public static BlockGardenSoil gardenSoil;
public static BlockGardenFarmland gardenFarmland;
public static BlockGardenProxy gardenProxy;
public static BlockSmallFire smallFire;
public static BlockCompostBin compostBin;
public void init() {
gardenSoil = new BlockGardenSoil(makeName("gardenSoil"));
gardenFarmland = new BlockGardenFarmland(makeName("gardenFarmland"));
gardenProxy = new BlockGardenProxy(makeName("gardenProxy"));
smallFire = new BlockSmallFire(makeName("smallFire"));
compostBin = new BlockCompostBin(makeName("compostBin"));
GameRegistry.registerBlock(gardenSoil, "garden_soil");
GameRegistry.registerBlock(gardenFarmland, "garden_farmland");
GameRegistry.registerBlock(gardenProxy, "garden_proxy");
GameRegistry.registerBlock(smallFire, "small_fire");
GameRegistry.registerBlock(compostBin, "compost_bin");
GameRegistry.registerTileEntity(TileEntityGardenSoil.class, getQualifiedName(gardenSoil));
GameRegistry.registerTileEntity(TileEntityGardenFarmland.class, getQualifiedName(gardenFarmland));
GameRegistry.registerTileEntity(TileEntityCompostBin.class, getQualifiedName(compostBin));
}
public static String makeName(String name) {
return "GardenCore".toLowerCase() + "." + name;
}
public static Block get(String name) {
return GameRegistry.findBlock("GardenCore", name);
}
public static String getQualifiedName(Block block) {
return GameData.getBlockRegistry()
.getNameForObject(block);
}
| package com.jaquadro.minecraft.gardencore.core;
public class ModBlocks {
public static BlockGardenSoil gardenSoil;
public static BlockGardenFarmland gardenFarmland;
public static BlockGardenProxy gardenProxy;
public static BlockSmallFire smallFire;
public static BlockCompostBin compostBin;
public void init() {
gardenSoil = new BlockGardenSoil(makeName("gardenSoil"));
gardenFarmland = new BlockGardenFarmland(makeName("gardenFarmland"));
gardenProxy = new BlockGardenProxy(makeName("gardenProxy"));
smallFire = new BlockSmallFire(makeName("smallFire"));
compostBin = new BlockCompostBin(makeName("compostBin"));
GameRegistry.registerBlock(gardenSoil, "garden_soil");
GameRegistry.registerBlock(gardenFarmland, "garden_farmland");
GameRegistry.registerBlock(gardenProxy, "garden_proxy");
GameRegistry.registerBlock(smallFire, "small_fire");
GameRegistry.registerBlock(compostBin, "compost_bin");
GameRegistry.registerTileEntity(TileEntityGardenSoil.class, getQualifiedName(gardenSoil));
GameRegistry.registerTileEntity(TileEntityGardenFarmland.class, getQualifiedName(gardenFarmland));
GameRegistry.registerTileEntity(TileEntityCompostBin.class, getQualifiedName(compostBin));
}
public static String makeName(String name) {
return "GardenCore".toLowerCase() + "." + name;
}
public static Block get(String name) {
return GameRegistry.findBlock("GardenCore", name);
}
public static String getQualifiedName(Block block) {
return GameData.getBlockRegistry()
.getNameForObject(block);
}
| public static UniqueMetaIdentifier getUniqueMetaID(Block block, int meta) { | 3 | 2023-12-12 08:13:16+00:00 | 8k |
joyheros/realworld | app-article/src/main/java/io/zhifou/realworld/article/application/service/impl/ArticleServiceImpl.java | [
{
"identifier": "ProfileService",
"path": "app-permission/src/main/java/io/zhifou/realworld/auth/application/service/ProfileService.java",
"snippet": "public interface ProfileService {\r\n\tProfileData getProfile(User me, Long userId);\r\n\r\n\tProfileData getProfile(User me, String username);\r\n\r\n\t... | import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import io.zhifou.realworld.auth.application.data.ProfileData;
import io.zhifou.realworld.auth.application.service.ProfileService;
import io.zhifou.realworld.auth.domain.User;
import io.zhifou.realworld.exception.ResourceNotFoundException;
import io.zhifou.realworld.article.application.data.ArticleData;
import io.zhifou.realworld.article.application.data.ArticleFacets;
import io.zhifou.realworld.article.application.data.ArticlePageSet;
import io.zhifou.realworld.article.application.data.ArticleParam;
import io.zhifou.realworld.article.application.data.Pagination;
import io.zhifou.realworld.article.application.data.UpdateArticleParam;
import io.zhifou.realworld.article.application.service.ArticleService;
import io.zhifou.realworld.article.domain.Article;
import io.zhifou.realworld.article.domain.ArticleFavorite;
import io.zhifou.realworld.article.domain.support.ArticleFavoriteProvider;
import io.zhifou.realworld.article.domain.support.ArticleProvider;
| 5,620 | package io.zhifou.realworld.article.application.service.impl;
@Service
public class ArticleServiceImpl implements ArticleService {
private final ArticleProvider articleProvider;
private final ArticleFavoriteProvider favoriteProvider;
private final ProfileService profileService;
@Autowired
public ArticleServiceImpl(ArticleProvider articleProvider, ArticleFavoriteProvider favoriteProvider,
ProfileService profileService) {
this.articleProvider = articleProvider;
this.favoriteProvider = favoriteProvider;
this.profileService = profileService;
}
@Override
@Transactional(readOnly = true)
| package io.zhifou.realworld.article.application.service.impl;
@Service
public class ArticleServiceImpl implements ArticleService {
private final ArticleProvider articleProvider;
private final ArticleFavoriteProvider favoriteProvider;
private final ProfileService profileService;
@Autowired
public ArticleServiceImpl(ArticleProvider articleProvider, ArticleFavoriteProvider favoriteProvider,
ProfileService profileService) {
this.articleProvider = articleProvider;
this.favoriteProvider = favoriteProvider;
this.profileService = profileService;
}
@Override
@Transactional(readOnly = true)
| public ArticleData findById(User me, Long id) {
| 3 | 2023-12-14 07:28:49+00:00 | 8k |
Zergatul/java-scripting-language | src/main/java/com/zergatul/scripting/compiler/types/SBoolean.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.operations.BinaryOperation;
import com.zergatul.scripting.compiler.operations.UnaryOperation;
import static org.objectweb.asm.Opcodes.*;
| 5,018 | package com.zergatul.scripting.compiler.types;
public class SBoolean extends SPrimitiveType {
public static final SBoolean instance = new SBoolean();
private SBoolean() {
super(boolean.class);
}
@Override
public boolean isReference() {
return false;
}
@Override
public int getLoadInst() {
return ILOAD;
}
@Override
public int getStoreInst() {
return ISTORE;
}
@Override
| package com.zergatul.scripting.compiler.types;
public class SBoolean extends SPrimitiveType {
public static final SBoolean instance = new SBoolean();
private SBoolean() {
super(boolean.class);
}
@Override
public boolean isReference() {
return false;
}
@Override
public int getLoadInst() {
return ILOAD;
}
@Override
public int getStoreInst() {
return ISTORE;
}
@Override
| public void storeDefaultValue(CompilerMethodVisitor visitor) {
| 0 | 2023-12-10 00:37:27+00:00 | 8k |
Pigalala/TrackExchange | src/main/java/me/pigalala/trackexchange/processes/ProcessSave.java | [
{
"identifier": "TrackExchange",
"path": "src/main/java/me/pigalala/trackexchange/TrackExchange.java",
"snippet": "public final class TrackExchange extends JavaPlugin {\n public static final int TRACK_VERSION = 4;\n\n public static TrackExchange instance;\n private static TaskChainFactory taskC... | import co.aikar.taskchain.TaskChain;
import com.fastasyncworldedit.core.Fawe;
import com.fastasyncworldedit.core.FaweAPI;
import com.sk89q.worldedit.*;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard;
import com.sk89q.worldedit.function.operation.ForwardExtentCopy;
import com.sk89q.worldedit.function.operation.Operation;
import com.sk89q.worldedit.function.operation.Operations;
import com.sk89q.worldedit.regions.Region;
import me.makkuusen.timing.system.track.Track;
import me.pigalala.trackexchange.TrackExchange;
import me.pigalala.trackexchange.trackcomponents.TrackExchangeFile;
import me.pigalala.trackexchange.trackcomponents.TrackExchangeSchematic;
import me.pigalala.trackexchange.trackcomponents.TrackExchangeTrack;
import me.pigalala.trackexchange.trackcomponents.SimpleLocation;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CompletableFuture; | 3,762 | package me.pigalala.trackexchange.processes;
public class ProcessSave extends Process {
private final Track track;
private final String saveAs;
private final TaskChain<?> chain;
private final Location origin;
public ProcessSave(Player player, Track track, String saveAs) {
super(player, "SAVE");
this.track = track;
this.saveAs = saveAs;
| package me.pigalala.trackexchange.processes;
public class ProcessSave extends Process {
private final Track track;
private final String saveAs;
private final TaskChain<?> chain;
private final Location origin;
public ProcessSave(Player player, Track track, String saveAs) {
super(player, "SAVE");
this.track = track;
this.saveAs = saveAs;
| this.chain = TrackExchange.newChain(); | 0 | 2023-12-06 12:43:51+00:00 | 8k |
Lampadina17/MorpheusLauncher | src/team/morpheus/launcher/instance/Vanilla.java | [
{
"identifier": "Launcher",
"path": "src/team/morpheus/launcher/Launcher.java",
"snippet": "public class Launcher {\r\n\r\n private static final MyLogger log = new MyLogger(Launcher.class);\r\n public JSONParser jsonParser = new JSONParser();\r\n private File gameFolder, assetsFolder;\r\n\r\n ... | import team.morpheus.launcher.Launcher;
import team.morpheus.launcher.logging.MyLogger;
| 7,104 | package team.morpheus.launcher.instance;
public class Vanilla {
private static final MyLogger log = new MyLogger(Vanilla.class);
String mcVersion;
public Vanilla(String mcVersion) {
this.mcVersion = mcVersion;
}
public void prepareLaunch() throws Exception {
boolean modded = mcVersion.toLowerCase().contains("fabric")
|| mcVersion.toLowerCase().contains("forge")
|| mcVersion.toLowerCase().contains("quilt")
|| mcVersion.toLowerCase().contains("optifine")
|| mcVersion.toLowerCase().contains("liteloader");
log.info(String.format("Launching %s instance (%s)", !modded ? "Vanilla" : "Modded", mcVersion));
| package team.morpheus.launcher.instance;
public class Vanilla {
private static final MyLogger log = new MyLogger(Vanilla.class);
String mcVersion;
public Vanilla(String mcVersion) {
this.mcVersion = mcVersion;
}
public void prepareLaunch() throws Exception {
boolean modded = mcVersion.toLowerCase().contains("fabric")
|| mcVersion.toLowerCase().contains("forge")
|| mcVersion.toLowerCase().contains("quilt")
|| mcVersion.toLowerCase().contains("optifine")
|| mcVersion.toLowerCase().contains("liteloader");
log.info(String.format("Launching %s instance (%s)", !modded ? "Vanilla" : "Modded", mcVersion));
| new Launcher(mcVersion, null, modded);
| 0 | 2023-12-07 14:34:54+00:00 | 8k |
ranizouaoui/CANalyzer | Controllers/UserOption2.java | [
{
"identifier": "CANFrameTransmission",
"path": "Classes/CANFrameTransmission.java",
"snippet": "public class CANFrameTransmission {\n\n private static final int MAX_DATA_POINTS = 500;\n private static final double TIME_PERIOD_PER_BIT = 1; // Adjust as needed\n private int xSeriesData = 0;\n ... | import java.util.logging.Level;
import java.util.logging.Logger;
import java.math.BigInteger;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.ResourceBundle;
import Classes.CANFrameTransmission;
import Classes.FrameModel;
import helpers.DataBase;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import jssc.SerialPort;
import jssc.SerialPortException;
import jssc.SerialPortList; | 3,748 | serialPort.openPort();
serialPort.setParams(
SerialPort.BAUDRATE_115200,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE
);
// Define CAN message data
String stdId = BinaryToHexadecimal(identifier1);
String dlc = BinaryToHexadecimal(dlc1);
String data = BinaryToHexadecimal(data1);
String rtr;
if(selectedFrameType1.equals("Remote Frame")) {
rtr="1";
}else {
rtr="0";
}
// Send CAN message
sendCANMessage(serialPort, stdId, dlc, data,rtr);
// Wait and check for received data
int timeout = 4000; // Timeout in milliseconds
long startTime = System.currentTimeMillis();
// Create an instance of Database
DataBase database = new DataBase();
while (System.currentTimeMillis() - startTime < timeout) {
if (serialPort.getInputBufferBytesCount() > 0) {
// Read the received data
String receivedData = serialPort.readString();
System.out.println("Received: " + receivedData);
// Call the insertFrame method
database.insertFrame(identifier1,convertDecimalToBinary(receivedData.length()) , DecimalToBinaryConverter(receivedData), "RECEIVED_Data Frame");
loadDate();
break; // Exit the loop after receiving data
}
// Add a small delay to avoid excessive CPU usage
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Close the serial port when done
serialPort.closePort();
} catch (SerialPortException e) {
e.printStackTrace();
}
}
private static void sendCANMessage(SerialPort serialPort, String stdId, String dlc, String data,String rtr) throws SerialPortException {
// Construct the CAN message as a string (adjust as needed)
String message = rtr+dlc+stdId+data;
message =FormatCanMessage(message);
System.out.println("Sending: " + message);
// Send the message over the serial port
serialPort.writeString(message);
}
private String BinaryToHexadecimal(String binaryNumber) {
// Convertir la chaîne binaire en nombre BigInteger
BigInteger decimalNumber = new BigInteger(binaryNumber, 2);
// Convertir le nombre décimal en représentation hexadécimale
String hexadecimalString = decimalNumber.toString(16);
return hexadecimalString;
}
private static String FormatCanMessage(String message) {
if (message.length() < 8) {
int paddingLength = 8 - message.length();
String padding = "0".repeat(paddingLength);
message = message+padding ;
}
return message;
}
private static String convertDecimalToBinary(int decimalNumber) {
// Utiliser Integer.toBinaryString() pour la conversion
String BinNum= Integer.toBinaryString(decimalNumber);
if(BinNum.length()<4) {
int paddingLength = 4 - BinNum.length();
String padding = "0".repeat(paddingLength);
BinNum=padding+BinNum;
}
return BinNum;
}
private static String DecimalToBinaryConverter(String decimalString) {
// Parse the decimal string to an integer
int decimalNumber = Integer.parseInt(decimalString);
// Convert the decimal number to binary
String binaryRepresentation = Integer.toBinaryString(decimalNumber);
return binaryRepresentation;
}
public static String calculateDLC(String data) {
// Calculate the number of bytes needed to represent the binary data
int bytesNeeded = (int) Math.ceil((double) data.length() / 8);
// Convert the number of bytes to a 4-bit binary string (DLC)
String dlcBinary = String.format("%04d", Integer.parseInt(Integer.toBinaryString(bytesNeeded)));
return dlcBinary;
}
private boolean isValidBinary(String input) {
// Check if the input consists only of binary digits (0s and 1s)
return input.matches("[01]*");
}
@FXML
private void showChart() {
handleSendButtonAction();
// Create an instance of CANFrameTransmission | package Controllers;
public class UserOption2 implements Initializable {
@FXML
private Label noFrameTypeLabel;
@FXML
private Label errorLabel;
@FXML
private ComboBox<String> serialPortComboBox;
@FXML
private ComboBox<String> frameTypeComboBox;
@FXML
private Label noPortLabel;
@FXML
private TextField dataTextField;
@FXML
private TextField rtrTextField;
@FXML
private TextField IDENTIFIERTextField;
@FXML
private TextField DLCTextField;
@FXML
private TextField frameNameTextField;
@FXML
private Button sendButton;
// Assuming FrameTable is a TableView<FrameModel>
@FXML
TableView<FrameModel> frameTable;
@FXML
TableColumn<FrameModel, String> indexColumn;
@FXML
TableColumn<FrameModel, String> identifierColumn;
@FXML
TableColumn<FrameModel, String> dlcColumn;
@FXML
TableColumn<FrameModel, String> dataColumn;
@FXML
TableColumn<FrameModel, String> frameNameColumn;
FrameModel Frame = null;
String query = null;
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
ObservableList<FrameModel> FrametList = FXCollections.observableArrayList();
private String selectedFrameType;
private String selectedSerialPort;
@Override
public void initialize(URL location, ResourceBundle resources) {
// Call the method to populate the table with frames
loadDate();
initializeFrameTypeComboBox(frameTypeComboBox, noFrameTypeLabel);
// Initialize the ComboBox for serial ports
initializeComboBox(serialPortComboBox, noPortLabel);
updateSerialPorts() ;
// Add a listener to dataField to update dlcField on change
dataTextField.textProperty().addListener((observable, oldValue, newValue) -> {
if (isValidBinary(newValue)) {
errorLabel.setVisible(false); // hide error message
String dlc = calculateDLC(newValue);
DLCTextField.setText(dlc);
} else {
errorLabel.setText("Invalid binary input. Please enter only 0s and 1s.");
errorLabel.setVisible(true); // Show error message
// Reset DLC field if input is not a valid binary
DLCTextField.clear();
}
});
}
private void initializeFrameTypeComboBox(ComboBox<String> comboBox, Label noFrameTypeLabel) {
// Initialize the ComboBox with frame types (Data Frame and Remote Frame)
ObservableList<String> frameTypeItems = FXCollections.observableArrayList("Data Frame", "Remote Frame");
comboBox.setItems(frameTypeItems);
// Set a listener to update the selectedFrameType variable
comboBox.valueProperty().addListener((observable, oldValue, newValue) -> {
selectedFrameType = newValue;
// System.out.println(selectedFrameType);
noFrameTypeLabel.setVisible(newValue == null);
if (newValue != null && newValue.equals("Remote Frame")) {
// If "Remote Frame" is selected, hide the dataTextField
dataTextField.setText("0");
dataTextField.setVisible(false);
rtrTextField.setText("1");
DLCTextField.setText("0000");
} else {
// If anything else is selected (e.g., "Data Frame"), show the dataTextField
dataTextField.setText("01010101");
dataTextField.setVisible(true);
rtrTextField.setText("0");
DLCTextField.setText("0001");
}
});
}
private void initializeComboBox(ComboBox<String> comboBox, Label noPortLabel) {
// Get a list of available serial ports using JSSC
String[] portNames = SerialPortList.getPortNames();
// Update the ComboBox with the available ports
ObservableList<String> portItems = FXCollections.observableArrayList(portNames);
comboBox.setItems(portItems);
// Set a listener to update the selectedSerialPort variable
comboBox.valueProperty().addListener((observable, oldValue, newValue) -> {
selectedSerialPort = newValue;
// System.out.println(selectedSerialPort);
noPortLabel.setVisible(newValue == null);
// You can add any other actions you want to perform when the user selects a port here
});
if(portNames.length<=0) {
noPortLabel.setVisible(true);
}
}
private void updateSerialPorts() {
Task<Void> task = new Task<Void>() {
@Override
protected Void call() {
while (true) {
// Get a list of available serial ports using JSSC
String[] portNames = SerialPortList.getPortNames();
Platform.runLater(() -> {
initializeComboBox(serialPortComboBox, noPortLabel);
});
try {
Thread.sleep(2000); // Sleep for 2 seconds
} catch (InterruptedException e) {
// Handle the exception
}
}
}
};
Thread thread = new Thread(task);
thread.setDaemon(true);
thread.start();
}
@FXML
private void handleSendButtonAction() {
// Retrieve values from text fields
String identifier = IDENTIFIERTextField.getText();
String dlc = DLCTextField.getText();
String data = dataTextField.getText();
String frameName = "SEND_"+selectedFrameType;
// Create an instance of Database
DataBase database = new DataBase();
if (selectedSerialPort != null && !selectedSerialPort.isEmpty() && selectedFrameType !=null ) {
errorLabel.setVisible(false); // Show error message
// Call the insertFrame method
database.insertFrame(identifier, dlc, data, frameName);
SendFromSerial(selectedSerialPort,identifier,dlc,data,selectedFrameType);
} else {
errorLabel.setText("Verify the chosen port and the frame type.");
errorLabel.setVisible(true); // Show error message
}
loadDate();
}
void refreshTable() {
try {
FrametList.clear();
query = "SELECT * FROM `can_frames`";
preparedStatement = connection.prepareStatement(query);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
FrametList.add(new FrameModel(resultSet.getInt("index"), resultSet.getString("IDENTIFIER"),
resultSet.getString("DLC"), resultSet.getString("DATA"), resultSet.getString("Frame_Name")));
frameTable.setItems(FrametList);
}
} catch (SQLException ex) {
Logger.getLogger(UserOption2.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void loadDate() {
connection = DataBase.connecterBase();
refreshTable();
indexColumn.setCellValueFactory(new PropertyValueFactory<>("index"));
identifierColumn.setCellValueFactory(new PropertyValueFactory<>("identifier"));
dlcColumn.setCellValueFactory(new PropertyValueFactory<>("dlc"));
dataColumn.setCellValueFactory(new PropertyValueFactory<>("data"));
frameNameColumn.setCellValueFactory(new PropertyValueFactory<>("frameName"));
// add cell of button edit
frameTable.setItems(FrametList);
}
private void SendFromSerial(String SelectedportName,String identifier1,String dlc1,String data1,String selectedFrameType1) {
// Replace "COMx" with the actual port name on your system
String portName = SelectedportName;
SerialPort serialPort = new SerialPort(portName);
try {
serialPort.openPort();
serialPort.setParams(
SerialPort.BAUDRATE_115200,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE
);
// Define CAN message data
String stdId = BinaryToHexadecimal(identifier1);
String dlc = BinaryToHexadecimal(dlc1);
String data = BinaryToHexadecimal(data1);
String rtr;
if(selectedFrameType1.equals("Remote Frame")) {
rtr="1";
}else {
rtr="0";
}
// Send CAN message
sendCANMessage(serialPort, stdId, dlc, data,rtr);
// Wait and check for received data
int timeout = 4000; // Timeout in milliseconds
long startTime = System.currentTimeMillis();
// Create an instance of Database
DataBase database = new DataBase();
while (System.currentTimeMillis() - startTime < timeout) {
if (serialPort.getInputBufferBytesCount() > 0) {
// Read the received data
String receivedData = serialPort.readString();
System.out.println("Received: " + receivedData);
// Call the insertFrame method
database.insertFrame(identifier1,convertDecimalToBinary(receivedData.length()) , DecimalToBinaryConverter(receivedData), "RECEIVED_Data Frame");
loadDate();
break; // Exit the loop after receiving data
}
// Add a small delay to avoid excessive CPU usage
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Close the serial port when done
serialPort.closePort();
} catch (SerialPortException e) {
e.printStackTrace();
}
}
private static void sendCANMessage(SerialPort serialPort, String stdId, String dlc, String data,String rtr) throws SerialPortException {
// Construct the CAN message as a string (adjust as needed)
String message = rtr+dlc+stdId+data;
message =FormatCanMessage(message);
System.out.println("Sending: " + message);
// Send the message over the serial port
serialPort.writeString(message);
}
private String BinaryToHexadecimal(String binaryNumber) {
// Convertir la chaîne binaire en nombre BigInteger
BigInteger decimalNumber = new BigInteger(binaryNumber, 2);
// Convertir le nombre décimal en représentation hexadécimale
String hexadecimalString = decimalNumber.toString(16);
return hexadecimalString;
}
private static String FormatCanMessage(String message) {
if (message.length() < 8) {
int paddingLength = 8 - message.length();
String padding = "0".repeat(paddingLength);
message = message+padding ;
}
return message;
}
private static String convertDecimalToBinary(int decimalNumber) {
// Utiliser Integer.toBinaryString() pour la conversion
String BinNum= Integer.toBinaryString(decimalNumber);
if(BinNum.length()<4) {
int paddingLength = 4 - BinNum.length();
String padding = "0".repeat(paddingLength);
BinNum=padding+BinNum;
}
return BinNum;
}
private static String DecimalToBinaryConverter(String decimalString) {
// Parse the decimal string to an integer
int decimalNumber = Integer.parseInt(decimalString);
// Convert the decimal number to binary
String binaryRepresentation = Integer.toBinaryString(decimalNumber);
return binaryRepresentation;
}
public static String calculateDLC(String data) {
// Calculate the number of bytes needed to represent the binary data
int bytesNeeded = (int) Math.ceil((double) data.length() / 8);
// Convert the number of bytes to a 4-bit binary string (DLC)
String dlcBinary = String.format("%04d", Integer.parseInt(Integer.toBinaryString(bytesNeeded)));
return dlcBinary;
}
private boolean isValidBinary(String input) {
// Check if the input consists only of binary digits (0s and 1s)
return input.matches("[01]*");
}
@FXML
private void showChart() {
handleSendButtonAction();
// Create an instance of CANFrameTransmission | CANFrameTransmission chart = new CANFrameTransmission(); | 0 | 2023-12-13 22:00:14+00:00 | 8k |
Serilum/Collective | Fabric/src/main/java/com/natamus/collective/CollectiveFabric.java | [
{
"identifier": "RegisterMod",
"path": "Common/src/main/java/com/natamus/collective/check/RegisterMod.java",
"snippet": "public class RegisterMod {\n\tprivate static final CopyOnWriteArrayList<String> jarlist = new CopyOnWriteArrayList<String>();\n\tprivate static final HashMap<String, String> jartoname... | import com.natamus.collective.check.RegisterMod;
import com.natamus.collective.config.GenerateJSONFiles;
import com.natamus.collective.events.CollectiveEvents;
import com.natamus.collective.util.CollectiveReference;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerEntityEvents;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.Entity; | 3,826 | package com.natamus.collective;
public class CollectiveFabric implements ModInitializer {
@Override
public void onInitialize() {
setGlobalConstants();
CollectiveCommon.init();
ServerLifecycleEvents.SERVER_STARTING.register((MinecraftServer minecraftServer) -> {
GenerateJSONFiles.initGeneration(minecraftServer);
});
ServerTickEvents.START_WORLD_TICK.register((ServerLevel world) -> { | package com.natamus.collective;
public class CollectiveFabric implements ModInitializer {
@Override
public void onInitialize() {
setGlobalConstants();
CollectiveCommon.init();
ServerLifecycleEvents.SERVER_STARTING.register((MinecraftServer minecraftServer) -> {
GenerateJSONFiles.initGeneration(minecraftServer);
});
ServerTickEvents.START_WORLD_TICK.register((ServerLevel world) -> { | CollectiveEvents.onWorldTick(world); | 2 | 2023-12-11 22:37:15+00:00 | 8k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.