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
emtee40/ApkSignatureKill-pc
app/src/main/java/org/jf/dexlib2/dexbacked/DexBackedClassDef.java
[ { "identifier": "BaseTypeReference", "path": "app/src/main/java/org/jf/dexlib2/base/reference/BaseTypeReference.java", "snippet": "public abstract class BaseTypeReference implements TypeReference {\n @Override\n public int hashCode() {\n return getType().hashCode();\n }\n\n @Override\...
import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import org.jf.dexlib2.base.reference.BaseTypeReference; import org.jf.dexlib2.dexbacked.raw.ClassDefItem; import org.jf.dexlib2.dexbacked.raw.TypeIdItem; import org.jf.dexlib2.dexbacked.util.AnnotationsDirectory; import org.jf.dexlib2.dexbacked.util.StaticInitialValueIterator; import org.jf.dexlib2.dexbacked.util.VariableSizeLookaheadIterator; import org.jf.dexlib2.iface.ClassDef; import org.jf.dexlib2.iface.reference.FieldReference; import org.jf.dexlib2.iface.reference.MethodReference; import org.jf.dexlib2.immutable.reference.ImmutableFieldReference; import org.jf.dexlib2.immutable.reference.ImmutableMethodReference; import java.util.AbstractList; import java.util.Iterator; import java.util.List; import java.util.Set;
9,229
/* * Copyright 2012, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib2.dexbacked; public class DexBackedClassDef extends BaseTypeReference implements ClassDef { @NonNull public final DexBackedDexFile dexFile; private final int classDefOffset; private final int staticFieldsOffset; private final int staticFieldCount; private final int instanceFieldCount; private final int directMethodCount; private final int virtualMethodCount; private int instanceFieldsOffset = 0; private int directMethodsOffset = 0; private int virtualMethodsOffset = 0; @Nullable private AnnotationsDirectory annotationsDirectory; public DexBackedClassDef(@NonNull DexBackedDexFile dexFile, int classDefOffset) { this.dexFile = dexFile; this.classDefOffset = classDefOffset; int classDataOffset = dexFile.readSmallUint(classDefOffset + ClassDefItem.CLASS_DATA_OFFSET); if (classDataOffset == 0) { staticFieldsOffset = -1; staticFieldCount = 0; instanceFieldCount = 0; directMethodCount = 0; virtualMethodCount = 0; } else { DexReader reader = dexFile.readerAt(classDataOffset); staticFieldCount = reader.readSmallUleb128(); instanceFieldCount = reader.readSmallUleb128(); directMethodCount = reader.readSmallUleb128(); virtualMethodCount = reader.readSmallUleb128(); staticFieldsOffset = reader.getOffset(); } } @NonNull @Override public String getType() { return dexFile.getType(dexFile.readSmallUint(classDefOffset + ClassDefItem.CLASS_OFFSET)); } @Nullable @Override public String getSuperclass() { return dexFile.getOptionalType(dexFile.readOptionalUint(classDefOffset + ClassDefItem.SUPERCLASS_OFFSET)); } @Override public int getAccessFlags() { return dexFile.readSmallUint(classDefOffset + ClassDefItem.ACCESS_FLAGS_OFFSET); } @Nullable @Override public String getSourceFile() { return dexFile.getOptionalString(dexFile.readOptionalUint(classDefOffset + ClassDefItem.SOURCE_FILE_OFFSET)); } @NonNull @Override public List<String> getInterfaces() { final int interfacesOffset = dexFile.readSmallUint(classDefOffset + ClassDefItem.INTERFACES_OFFSET); if (interfacesOffset > 0) { final int size = dexFile.readSmallUint(interfacesOffset); return new AbstractList<String>() { @Override @NonNull public String get(int index) { return dexFile.getType(dexFile.readUshort(interfacesOffset + 4 + (2 * index))); } @Override public int size() { return size; } }; } return ImmutableList.of(); } @NonNull @Override public Set<? extends DexBackedAnnotation> getAnnotations() { return getAnnotationsDirectory().getClassAnnotations(); } @NonNull @Override public Iterable<? extends DexBackedField> getStaticFields() { return getStaticFields(true); } @NonNull public Iterable<? extends DexBackedField> getStaticFields(final boolean skipDuplicates) { if (staticFieldCount > 0) { DexReader reader = dexFile.readerAt(staticFieldsOffset); final AnnotationsDirectory annotationsDirectory = getAnnotationsDirectory(); final int staticInitialValuesOffset = dexFile.readSmallUint(classDefOffset + ClassDefItem.STATIC_VALUES_OFFSET); final int fieldsStartOffset = reader.getOffset(); return new Iterable<DexBackedField>() { @NonNull @Override public Iterator<DexBackedField> iterator() { final AnnotationsDirectory.AnnotationIterator annotationIterator = annotationsDirectory.getFieldAnnotationIterator(); final StaticInitialValueIterator staticInitialValueIterator = StaticInitialValueIterator.newOrEmpty(dexFile, staticInitialValuesOffset); return new VariableSizeLookaheadIterator<DexBackedField>(dexFile, fieldsStartOffset) { private int count; @Nullable private FieldReference previousField; private int previousIndex; @Nullable @Override protected DexBackedField readNextItem(@NonNull DexReader reader) { while (true) { if (++count > staticFieldCount) { instanceFieldsOffset = reader.getOffset(); return endOfData(); } DexBackedField item = new DexBackedField(reader, DexBackedClassDef.this, previousIndex, staticInitialValueIterator, annotationIterator); FieldReference currentField = previousField;
/* * Copyright 2012, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib2.dexbacked; public class DexBackedClassDef extends BaseTypeReference implements ClassDef { @NonNull public final DexBackedDexFile dexFile; private final int classDefOffset; private final int staticFieldsOffset; private final int staticFieldCount; private final int instanceFieldCount; private final int directMethodCount; private final int virtualMethodCount; private int instanceFieldsOffset = 0; private int directMethodsOffset = 0; private int virtualMethodsOffset = 0; @Nullable private AnnotationsDirectory annotationsDirectory; public DexBackedClassDef(@NonNull DexBackedDexFile dexFile, int classDefOffset) { this.dexFile = dexFile; this.classDefOffset = classDefOffset; int classDataOffset = dexFile.readSmallUint(classDefOffset + ClassDefItem.CLASS_DATA_OFFSET); if (classDataOffset == 0) { staticFieldsOffset = -1; staticFieldCount = 0; instanceFieldCount = 0; directMethodCount = 0; virtualMethodCount = 0; } else { DexReader reader = dexFile.readerAt(classDataOffset); staticFieldCount = reader.readSmallUleb128(); instanceFieldCount = reader.readSmallUleb128(); directMethodCount = reader.readSmallUleb128(); virtualMethodCount = reader.readSmallUleb128(); staticFieldsOffset = reader.getOffset(); } } @NonNull @Override public String getType() { return dexFile.getType(dexFile.readSmallUint(classDefOffset + ClassDefItem.CLASS_OFFSET)); } @Nullable @Override public String getSuperclass() { return dexFile.getOptionalType(dexFile.readOptionalUint(classDefOffset + ClassDefItem.SUPERCLASS_OFFSET)); } @Override public int getAccessFlags() { return dexFile.readSmallUint(classDefOffset + ClassDefItem.ACCESS_FLAGS_OFFSET); } @Nullable @Override public String getSourceFile() { return dexFile.getOptionalString(dexFile.readOptionalUint(classDefOffset + ClassDefItem.SOURCE_FILE_OFFSET)); } @NonNull @Override public List<String> getInterfaces() { final int interfacesOffset = dexFile.readSmallUint(classDefOffset + ClassDefItem.INTERFACES_OFFSET); if (interfacesOffset > 0) { final int size = dexFile.readSmallUint(interfacesOffset); return new AbstractList<String>() { @Override @NonNull public String get(int index) { return dexFile.getType(dexFile.readUshort(interfacesOffset + 4 + (2 * index))); } @Override public int size() { return size; } }; } return ImmutableList.of(); } @NonNull @Override public Set<? extends DexBackedAnnotation> getAnnotations() { return getAnnotationsDirectory().getClassAnnotations(); } @NonNull @Override public Iterable<? extends DexBackedField> getStaticFields() { return getStaticFields(true); } @NonNull public Iterable<? extends DexBackedField> getStaticFields(final boolean skipDuplicates) { if (staticFieldCount > 0) { DexReader reader = dexFile.readerAt(staticFieldsOffset); final AnnotationsDirectory annotationsDirectory = getAnnotationsDirectory(); final int staticInitialValuesOffset = dexFile.readSmallUint(classDefOffset + ClassDefItem.STATIC_VALUES_OFFSET); final int fieldsStartOffset = reader.getOffset(); return new Iterable<DexBackedField>() { @NonNull @Override public Iterator<DexBackedField> iterator() { final AnnotationsDirectory.AnnotationIterator annotationIterator = annotationsDirectory.getFieldAnnotationIterator(); final StaticInitialValueIterator staticInitialValueIterator = StaticInitialValueIterator.newOrEmpty(dexFile, staticInitialValuesOffset); return new VariableSizeLookaheadIterator<DexBackedField>(dexFile, fieldsStartOffset) { private int count; @Nullable private FieldReference previousField; private int previousIndex; @Nullable @Override protected DexBackedField readNextItem(@NonNull DexReader reader) { while (true) { if (++count > staticFieldCount) { instanceFieldsOffset = reader.getOffset(); return endOfData(); } DexBackedField item = new DexBackedField(reader, DexBackedClassDef.this, previousIndex, staticInitialValueIterator, annotationIterator); FieldReference currentField = previousField;
FieldReference nextField = ImmutableFieldReference.of(item);
9
2023-12-16 11:11:16+00:00
12k
IzanagiCraft/IzanagiWorldGuard
worldguard-plugin-bukkit/src/main/java/com/izanagicraft/guard/events/listener/InventoryItemChangeListener.java
[ { "identifier": "GuardConstants", "path": "worldguard-api/src/main/java/com/izanagicraft/guard/GuardConstants.java", "snippet": "public class GuardConstants {\n\n /**\n * The main prefix used for plugin-related messages.\n */\n public static final String PREFIX = \"&#CB2D3EG&#D4343Du&#DD3A...
import org.bukkit.event.player.PlayerAttemptPickupItemEvent; import org.bukkit.event.player.PlayerDropItemEvent; import com.izanagicraft.guard.GuardConstants; import com.izanagicraft.guard.IzanagiWorldGuardPlugin; import com.izanagicraft.guard.commands.BuildModeCommand; import com.izanagicraft.guard.events.GuardListener; import com.izanagicraft.guard.flags.GuardFlag; import com.izanagicraft.guard.permissions.GuardPermission; import com.izanagicraft.guard.utils.MessageUtils; import io.papermc.paper.event.player.PlayerPickItemEvent; import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Item; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.inventory.InventoryPickupItemEvent;
7,218
/* * ▪ ·▄▄▄▄• ▄▄▄· ▐ ▄ ▄▄▄· ▄▄ • ▪ ▄▄· ▄▄▄ ▄▄▄· ·▄▄▄▄▄▄▄▄ * ██ ▪▀·.█▌▐█ ▀█ •█▌▐█▐█ ▀█ ▐█ ▀ ▪██ ▐█ ▌▪▀▄ █·▐█ ▀█ ▐▄▄·•██ * ▐█·▄█▀▀▀•▄█▀▀█ ▐█▐▐▌▄█▀▀█ ▄█ ▀█▄▐█·██ ▄▄▐▀▀▄ ▄█▀▀█ ██▪ ▐█.▪ * ▐█▌█▌▪▄█▀▐█ ▪▐▌██▐█▌▐█ ▪▐▌▐█▄▪▐█▐█▌▐███▌▐█•█▌▐█ ▪▐▌██▌. ▐█▌· * ▀▀▀·▀▀▀ • ▀ ▀ ▀▀ █▪ ▀ ▀ ·▀▀▀▀ ▀▀▀·▀▀▀ .▀ ▀ ▀ ▀ ▀▀▀ ▀▀▀ * * * @@@@@ * @@* *@@ * @@@ @@@ * @@@ @@ @@@ @@@@@@@@@@@ * @@@@@@@@ @@@@@@@@@@@@@@@@@@@@@ * @@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * #@@@ @@ @@ @@@@ @@@@ * @@@@ @@@ @@@@ @@@@ @@@ * @@@@@@ @@@@@@ @@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@ * * Copyright (c) 2023 - present | sanguine6660 <sanguine6660@gmail.com> * Copyright (c) 2023 - present | izanagicraft.com <contact@izanagicraft.com> * Copyright (c) 2023 - present | izanagicraft.com team and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.izanagicraft.guard.events.listener; /** * IzanagiWorldGuard; com.izanagicraft.guard.events.listener:InventoryItemChangeListener * <p> * Handles inventory-related events for IzanagiWorldGuard. * This listener checks and enforces item drop and pickup permissions within protected regions. * * @author <a href="https://github.com/sanguine6660">@sanguine6660</a> * @since 18.12.2023 */ public class InventoryItemChangeListener extends GuardListener { /** * Constructs a new GuardListener with the specified IzanagiWorldGuardPlugin. * * @param plugin The IzanagiWorldGuardPlugin instance. */ public InventoryItemChangeListener(IzanagiWorldGuardPlugin plugin) { super(plugin); } /** * Handles the PlayerDropItemEvent to enforce item drop permissions within protected regions. * * @param event The PlayerDropItemEvent. */ @EventHandler public void onItemDrop(PlayerDropItemEvent event) { Player player = event.getPlayer(); Item item = event.getItemDrop(); if (player == null || item == null) { event.setCancelled(true); return; } if (event.isCancelled()) return; if (player.hasPermission(GuardPermission.GROUPS_ADMIN.getName()) || player.hasPermission(GuardPermission.PLAYER_ITEM_DROP.getName())) { return; } if (BuildModeCommand.isBuildMode(player)) return; Location target = item.getLocation(); YamlConfiguration worldConfig = getPlugin().getWorldConfigs().get(target.getWorld().getName()); if (worldConfig == null) return; boolean allowItem = true; String allow = worldConfig.getString("flags." + GuardFlag.ITEM_DROP.getFlagName(), "false"); // System.out.println("Drop Allow: '" + allow + "'"); if (allow.isEmpty() || allow.equalsIgnoreCase("empty") || allow.equalsIgnoreCase("false") || allow.equalsIgnoreCase("deny")) { allowItem = false; } // TODO: region based checks. // System.out.println("Final Drop Allow: '" + allowItem + "'"); if (!allowItem) { event.setCancelled(true); // TODO: translations by player locale || fire event cancelled item drop instead player.sendActionBar(MessageUtils.getComponentSerializer().deserialize(
/* * ▪ ·▄▄▄▄• ▄▄▄· ▐ ▄ ▄▄▄· ▄▄ • ▪ ▄▄· ▄▄▄ ▄▄▄· ·▄▄▄▄▄▄▄▄ * ██ ▪▀·.█▌▐█ ▀█ •█▌▐█▐█ ▀█ ▐█ ▀ ▪██ ▐█ ▌▪▀▄ █·▐█ ▀█ ▐▄▄·•██ * ▐█·▄█▀▀▀•▄█▀▀█ ▐█▐▐▌▄█▀▀█ ▄█ ▀█▄▐█·██ ▄▄▐▀▀▄ ▄█▀▀█ ██▪ ▐█.▪ * ▐█▌█▌▪▄█▀▐█ ▪▐▌██▐█▌▐█ ▪▐▌▐█▄▪▐█▐█▌▐███▌▐█•█▌▐█ ▪▐▌██▌. ▐█▌· * ▀▀▀·▀▀▀ • ▀ ▀ ▀▀ █▪ ▀ ▀ ·▀▀▀▀ ▀▀▀·▀▀▀ .▀ ▀ ▀ ▀ ▀▀▀ ▀▀▀ * * * @@@@@ * @@* *@@ * @@@ @@@ * @@@ @@ @@@ @@@@@@@@@@@ * @@@@@@@@ @@@@@@@@@@@@@@@@@@@@@ * @@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * #@@@ @@ @@ @@@@ @@@@ * @@@@ @@@ @@@@ @@@@ @@@ * @@@@@@ @@@@@@ @@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@ * * Copyright (c) 2023 - present | sanguine6660 <sanguine6660@gmail.com> * Copyright (c) 2023 - present | izanagicraft.com <contact@izanagicraft.com> * Copyright (c) 2023 - present | izanagicraft.com team and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.izanagicraft.guard.events.listener; /** * IzanagiWorldGuard; com.izanagicraft.guard.events.listener:InventoryItemChangeListener * <p> * Handles inventory-related events for IzanagiWorldGuard. * This listener checks and enforces item drop and pickup permissions within protected regions. * * @author <a href="https://github.com/sanguine6660">@sanguine6660</a> * @since 18.12.2023 */ public class InventoryItemChangeListener extends GuardListener { /** * Constructs a new GuardListener with the specified IzanagiWorldGuardPlugin. * * @param plugin The IzanagiWorldGuardPlugin instance. */ public InventoryItemChangeListener(IzanagiWorldGuardPlugin plugin) { super(plugin); } /** * Handles the PlayerDropItemEvent to enforce item drop permissions within protected regions. * * @param event The PlayerDropItemEvent. */ @EventHandler public void onItemDrop(PlayerDropItemEvent event) { Player player = event.getPlayer(); Item item = event.getItemDrop(); if (player == null || item == null) { event.setCancelled(true); return; } if (event.isCancelled()) return; if (player.hasPermission(GuardPermission.GROUPS_ADMIN.getName()) || player.hasPermission(GuardPermission.PLAYER_ITEM_DROP.getName())) { return; } if (BuildModeCommand.isBuildMode(player)) return; Location target = item.getLocation(); YamlConfiguration worldConfig = getPlugin().getWorldConfigs().get(target.getWorld().getName()); if (worldConfig == null) return; boolean allowItem = true; String allow = worldConfig.getString("flags." + GuardFlag.ITEM_DROP.getFlagName(), "false"); // System.out.println("Drop Allow: '" + allow + "'"); if (allow.isEmpty() || allow.equalsIgnoreCase("empty") || allow.equalsIgnoreCase("false") || allow.equalsIgnoreCase("deny")) { allowItem = false; } // TODO: region based checks. // System.out.println("Final Drop Allow: '" + allowItem + "'"); if (!allowItem) { event.setCancelled(true); // TODO: translations by player locale || fire event cancelled item drop instead player.sendActionBar(MessageUtils.getComponentSerializer().deserialize(
GuardConstants.CHAT_PREFIX + "&cYou're not allowed to drop items here. &e(TODO translation)"
0
2023-12-17 14:18:31+00:00
12k
123yyh123/xiaofanshu
xfs-job-server/src/main/java/com/yyh/xfs/job/jobhandler/SampleXxlJob.java
[ { "identifier": "RedisConstant", "path": "xfs-common/common-redis/src/main/java/com/yyh/xfs/common/redis/constant/RedisConstant.java", "snippet": "public class RedisConstant {\n /**\n * redis key 用户登录过期前缀\n */\n public static final String REDIS_KEY_USER_LOGIN_EXPIRE = \"user:login:expire:\...
import com.xxl.job.core.context.XxlJobHelper; import com.xxl.job.core.handler.annotation.XxlJob; import com.yyh.xfs.common.redis.constant.RedisConstant; import com.yyh.xfs.common.redis.utils.RedisCache; import com.yyh.xfs.common.redis.utils.RedisKey; import com.yyh.xfs.job.service.UserService; import com.yyh.xfs.user.domain.UserDO; import com.yyh.xfs.user.vo.UserVO; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.BoundZSetOperations; import org.springframework.stereotype.Component; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Executor; import java.util.stream.Collectors;
8,354
package com.yyh.xfs.job.jobhandler; /** * @author yyh * @date 2023-12-23 * @desc xfs-job */ @Component @Slf4j public class SampleXxlJob {
package com.yyh.xfs.job.jobhandler; /** * @author yyh * @date 2023-12-23 * @desc xfs-job */ @Component @Slf4j public class SampleXxlJob {
private final UserService userService;
3
2023-12-15 08:13:42+00:00
12k
premiering/permad-game
src/main/java/club/premiering/permad/world/WorldImpl.java
[ { "identifier": "PermaGlobals", "path": "src/main/java/club/premiering/permad/PermaGlobals.java", "snippet": "public class PermaGlobals {\n public static final float TICKS_PER_SECOND = 60f;\n public static int WS_PORT = 6661;\n public static PermaConfig CONFIG;\n}" }, { "identifier": "P...
import club.premiering.permad.PermaGlobals; import club.premiering.permad.PermaServer; import club.premiering.permad.entity.Entity; import club.premiering.permad.entity.EntityPlayer; import club.premiering.permad.math.Vector2; import club.premiering.permad.math.Vector4; import club.premiering.permad.networking.NetworkManager; import club.premiering.permad.networking.GameSession; import club.premiering.permad.networking.packet.*; import club.premiering.permad.protocol.gameplay.*; import club.premiering.permad.room.Room; import club.premiering.permad.tick.TickScheduler; import com.google.common.collect.Queues; import lombok.Getter; import lombok.Setter; import java.util.ArrayList; import java.util.Collection; import java.util.Queue; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutorService;
7,237
package club.premiering.permad.world; public class WorldImpl implements World { private NetworkManager networkManager = PermaServer.getServer().getNetworkServer(); @Getter private Room room; @Getter private int worldId; @Getter private TickScheduler tickScheduler; @Getter private PacketQueue incomingPacketQueue; @Getter private PacketQueue outgoingPacketQueue; @Getter @Setter private Vector4 worldSize = new Vector4(-512, -512, 512, 512); @Getter @Setter private Vector2 worldSpawn = new Vector2(0, 0); @Getter @Setter private String worldName = "Unnamed world"; private Collection<Entity> entities = new CopyOnWriteArrayList<>(); private Queue<Runnable> scheduledActions = Queues.newConcurrentLinkedQueue(); public WorldImpl(Room room, int worldId) { this.room = room; this.worldId = worldId; this.tickScheduler = new TickScheduler(this); this.incomingPacketQueue = new PacketQueueBlockingImpl(); this.outgoingPacketQueue = new PacketQueueBlockingImpl(); } @Override public void start() { this.tickScheduler.startTicking(); } @Override public void end() { this.tickScheduler.stopTicking(); } @Override public void doTick() { for (int i = 0; i < this.scheduledActions.size(); i++) { var action = this.scheduledActions.poll(); try { action.run(); } catch (Exception e) { throw new RuntimeException(e); } } var packetQueue = getIncomingPacketQueue().fetchQueue(); for (QueuedPacket packet : packetQueue) { var handler = this.networkManager.getHandler(packet.packet); this.handlePacket(handler, packet); } for (var entity : this.entities) { //entity.lastRot = entity.rot; entity.doTick(); this.broadcastPacket(new EntityPositionPacketOut(entity)); entity.lastPos = entity.pos.clone(); entity.lastSize = entity.size.clone(); entity.lastRot = entity.rot; } // Process outgoing packets this.networkManager.sendAsyncQueue(this.outgoingPacketQueue); } @Override public void submitPacket(GameSession session, BasePacket packet) { this.outgoingPacketQueue.enqueue(session, packet); } @Override public void broadcastPacket(BasePacket packet) { for (Entity entity : this.entities) {
package club.premiering.permad.world; public class WorldImpl implements World { private NetworkManager networkManager = PermaServer.getServer().getNetworkServer(); @Getter private Room room; @Getter private int worldId; @Getter private TickScheduler tickScheduler; @Getter private PacketQueue incomingPacketQueue; @Getter private PacketQueue outgoingPacketQueue; @Getter @Setter private Vector4 worldSize = new Vector4(-512, -512, 512, 512); @Getter @Setter private Vector2 worldSpawn = new Vector2(0, 0); @Getter @Setter private String worldName = "Unnamed world"; private Collection<Entity> entities = new CopyOnWriteArrayList<>(); private Queue<Runnable> scheduledActions = Queues.newConcurrentLinkedQueue(); public WorldImpl(Room room, int worldId) { this.room = room; this.worldId = worldId; this.tickScheduler = new TickScheduler(this); this.incomingPacketQueue = new PacketQueueBlockingImpl(); this.outgoingPacketQueue = new PacketQueueBlockingImpl(); } @Override public void start() { this.tickScheduler.startTicking(); } @Override public void end() { this.tickScheduler.stopTicking(); } @Override public void doTick() { for (int i = 0; i < this.scheduledActions.size(); i++) { var action = this.scheduledActions.poll(); try { action.run(); } catch (Exception e) { throw new RuntimeException(e); } } var packetQueue = getIncomingPacketQueue().fetchQueue(); for (QueuedPacket packet : packetQueue) { var handler = this.networkManager.getHandler(packet.packet); this.handlePacket(handler, packet); } for (var entity : this.entities) { //entity.lastRot = entity.rot; entity.doTick(); this.broadcastPacket(new EntityPositionPacketOut(entity)); entity.lastPos = entity.pos.clone(); entity.lastSize = entity.size.clone(); entity.lastRot = entity.rot; } // Process outgoing packets this.networkManager.sendAsyncQueue(this.outgoingPacketQueue); } @Override public void submitPacket(GameSession session, BasePacket packet) { this.outgoingPacketQueue.enqueue(session, packet); } @Override public void broadcastPacket(BasePacket packet) { for (Entity entity : this.entities) {
if (entity instanceof EntityPlayer) {
3
2023-12-20 03:13:05+00:00
12k
egisac/ethicalvoting
src/main/java/net/egis/ethicalvoting/EthicalVoting.java
[ { "identifier": "EthicalVotingCommand", "path": "src/main/java/net/egis/ethicalvoting/commands/EthicalVotingCommand.java", "snippet": "public class EthicalVotingCommand implements CommandExecutor, TabCompleter {\n @Override\n public boolean onCommand(CommandSender sender, Command command, String l...
import lombok.Getter; import mc.obliviate.inventory.InventoryAPI; import net.egis.ethicalvoting.commands.EthicalVotingCommand; import net.egis.ethicalvoting.commands.VoteCommand; import net.egis.ethicalvoting.data.ProfileManager; import net.egis.ethicalvoting.data.StorageInterface; import net.egis.ethicalvoting.data.interfaces.MySQLInterface; import net.egis.ethicalvoting.data.interfaces.YamlInterface; import net.egis.ethicalvoting.https.UpdateChecker; import net.egis.ethicalvoting.integrations.EthicalPAPI; import net.egis.ethicalvoting.listeners.FireworkDamageListener; import net.egis.ethicalvoting.listeners.PlayerConnectionListener; import net.egis.ethicalvoting.listeners.VotifierVoteListener; import net.egis.ethicalvoting.rewards.VoteRewardHandler; import net.egis.ethicalvoting.utils.Translate; import net.egis.ethicalvoting.voteparty.VotePartyHandler; import net.md_5.bungee.api.ChatColor; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin;
7,225
package net.egis.ethicalvoting; @Getter public final class EthicalVoting extends JavaPlugin { @Getter private static EthicalVoting self; private StorageInterface storage; private ProfileManager profiles; private PlayerConnectionListener connectionListener; private VotifierVoteListener voteListener; private FireworkDamageListener fireworkDamageListener; private VotePartyHandler votePartyHandler; private VoteRewardHandler voteRewardHandler; @Override public void onEnable() { self = this; new InventoryAPI(this).init(); saveDefaultConfig(); pickStorageType(); loadPluginData(); loadFeatures(); registerEventListeners(); registerCommands(); registerIntegrations(); getLogger().info("Storage Type: " + storage.getAdapterType()); checkUpdates(); getLogger().info("EthicalVoting has been successfully enabled."); } @Override public void onDisable() { profiles.shutdown(); voteRewardHandler.getVoteQueue().shutdown(); getLogger().info("EthicalVoting has been successfully disabled."); } public void registerIntegrations() { if (getServer().getPluginManager().getPlugin("PlaceholderAPI") != null) { new EthicalPAPI().register(); getLogger().info("PlaceholderAPI integration has been successfully enabled."); } else { getLogger().warning("PlaceholderAPI integration has failed to load."); } } /* Defines which database type will be used to store user data. Current options: - MySQL - YAML (Bukkit internal) */ public void pickStorageType() { String storageInterface = getConfig().getString("database.type"); if (storageInterface == null) { getLogger().severe("Storage Interface is null. Report this to plugin developer."); getServer().shutdown(); return; } if (storageInterface.equalsIgnoreCase("mysql")) {
package net.egis.ethicalvoting; @Getter public final class EthicalVoting extends JavaPlugin { @Getter private static EthicalVoting self; private StorageInterface storage; private ProfileManager profiles; private PlayerConnectionListener connectionListener; private VotifierVoteListener voteListener; private FireworkDamageListener fireworkDamageListener; private VotePartyHandler votePartyHandler; private VoteRewardHandler voteRewardHandler; @Override public void onEnable() { self = this; new InventoryAPI(this).init(); saveDefaultConfig(); pickStorageType(); loadPluginData(); loadFeatures(); registerEventListeners(); registerCommands(); registerIntegrations(); getLogger().info("Storage Type: " + storage.getAdapterType()); checkUpdates(); getLogger().info("EthicalVoting has been successfully enabled."); } @Override public void onDisable() { profiles.shutdown(); voteRewardHandler.getVoteQueue().shutdown(); getLogger().info("EthicalVoting has been successfully disabled."); } public void registerIntegrations() { if (getServer().getPluginManager().getPlugin("PlaceholderAPI") != null) { new EthicalPAPI().register(); getLogger().info("PlaceholderAPI integration has been successfully enabled."); } else { getLogger().warning("PlaceholderAPI integration has failed to load."); } } /* Defines which database type will be used to store user data. Current options: - MySQL - YAML (Bukkit internal) */ public void pickStorageType() { String storageInterface = getConfig().getString("database.type"); if (storageInterface == null) { getLogger().severe("Storage Interface is null. Report this to plugin developer."); getServer().shutdown(); return; } if (storageInterface.equalsIgnoreCase("mysql")) {
storage = new MySQLInterface();
4
2023-12-15 16:48:38+00:00
12k
Blawuken/MicroG-Extended
play-services-core/src/main/java/org/microg/gms/auth/login/LoginActivity.java
[ { "identifier": "AuthConstants", "path": "play-services-basement/src/main/java/org/microg/gms/auth/AuthConstants.java", "snippet": "public class AuthConstants {\n public static final String DEFAULT_ACCOUNT = \"<<default account>>\";\n public static final String SCOPE_GET_ACCOUNT_ID = \"^^_account_...
import android.accounts.Account; import android.accounts.AccountManager; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.util.Base64; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.webkit.CookieManager; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.RelativeLayout; import android.widget.TextView; import androidx.annotation.StringRes; import androidx.preference.PreferenceManager; import androidx.webkit.WebViewClientCompat; import com.google.android.gms.R; import org.json.JSONArray; import org.microg.gms.auth.AuthConstants; import org.microg.gms.auth.AuthManager; import org.microg.gms.auth.AuthRequest; import org.microg.gms.auth.AuthResponse; import org.microg.gms.checkin.CheckinManager; import org.microg.gms.checkin.LastCheckinInfo; import org.microg.gms.common.HttpFormClient; import org.microg.gms.common.Utils; import org.microg.gms.people.PeopleManager; import org.microg.gms.profile.Build; import org.microg.gms.profile.ProfileManager; import java.io.IOException; import java.security.MessageDigest; import java.util.Locale; import static android.accounts.AccountManager.PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE; import static android.accounts.AccountManager.VISIBILITY_USER_MANAGED_VISIBLE; import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION_CODES.GINGERBREAD_MR1; import static android.os.Build.VERSION_CODES.HONEYCOMB; import static android.os.Build.VERSION_CODES.LOLLIPOP; import static android.telephony.TelephonyManager.SIM_STATE_UNKNOWN; import static android.view.KeyEvent.KEYCODE_BACK; import static android.view.View.INVISIBLE; import static android.view.View.VISIBLE; import static android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT; import static org.microg.gms.auth.AuthPrefs.isAuthVisible; import static org.microg.gms.checkin.CheckinPreferences.isSpoofingEnabled; import static org.microg.gms.checkin.CheckinPreferences.setSpoofingEnabled; import static org.microg.gms.common.Constants.GMS_PACKAGE_NAME; import static org.microg.gms.common.Constants.GMS_VERSION_CODE; import static org.microg.gms.common.Constants.GOOGLE_GMS_PACKAGE_NAME;
10,212
/* * Copyright (C) 2013-2017 microG Project Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.microg.gms.auth.login; public class LoginActivity extends AssistantActivity { public static final String TMPL_NEW_ACCOUNT = "new_account"; public static final String EXTRA_TMPL = "tmpl"; public static final String EXTRA_EMAIL = "email"; public static final String EXTRA_TOKEN = "masterToken"; public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; private static final String TAG = "GmsAuthLoginBrowser"; private static final String EMBEDDED_SETUP_URL = "https://accounts.google.com/EmbeddedSetup"; private static final String PROGRAMMATIC_AUTH_URL = "https://accounts.google.com/o/oauth2/programmatic_auth"; private static final String GOOGLE_SUITE_URL = "https://accounts.google.com/signin/continue"; private static final String MAGIC_USER_AGENT = " MinuteMaid"; private static final String COOKIE_OAUTH_TOKEN = "oauth_token"; private WebView webView; private String accountType; private AccountManager accountManager; private InputMethodManager inputMethodManager; private ViewGroup authContent; private int state = 0; @SuppressLint("AddJavascriptInterface") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
/* * Copyright (C) 2013-2017 microG Project Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.microg.gms.auth.login; public class LoginActivity extends AssistantActivity { public static final String TMPL_NEW_ACCOUNT = "new_account"; public static final String EXTRA_TMPL = "tmpl"; public static final String EXTRA_EMAIL = "email"; public static final String EXTRA_TOKEN = "masterToken"; public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; private static final String TAG = "GmsAuthLoginBrowser"; private static final String EMBEDDED_SETUP_URL = "https://accounts.google.com/EmbeddedSetup"; private static final String PROGRAMMATIC_AUTH_URL = "https://accounts.google.com/o/oauth2/programmatic_auth"; private static final String GOOGLE_SUITE_URL = "https://accounts.google.com/signin/continue"; private static final String MAGIC_USER_AGENT = " MinuteMaid"; private static final String COOKIE_OAUTH_TOKEN = "oauth_token"; private WebView webView; private String accountType; private AccountManager accountManager; private InputMethodManager inputMethodManager; private ViewGroup authContent; private int state = 0; @SuppressLint("AddJavascriptInterface") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
accountType = AuthConstants.DEFAULT_ACCOUNT_TYPE;
0
2023-12-17 16:14:53+00:00
12k
Yolka5/FTC-Imu3
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/opmode/threeConeTry.java
[ { "identifier": "SampleMecanumDrive", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/SampleMecanumDrive.java", "snippet": "@Config\npublic class SampleMecanumDrive extends MecanumDrive {\n public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(2, 0, 0);\n publi...
import com.acmerobotics.dashboard.config.Config; import com.acmerobotics.roadrunner.geometry.Pose2d; import com.acmerobotics.roadrunner.geometry.Vector2d; import com.acmerobotics.roadrunner.trajectory.Trajectory; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.ColorSensor; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorEx; import com.qualcomm.robotcore.hardware.DistanceSensor; import com.qualcomm.robotcore.hardware.OpticalDistanceSensor; import org.firstinspires.ftc.robotcore.external.navigation.DistanceUnit; import org.firstinspires.ftc.teamcode.drive.SampleMecanumDrive; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequence; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceBuilder; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.hardware.Servo; import com.qualcomm.robotcore.hardware.TouchSensor; import org.firstinspires.ftc.robotcore.external.hardware.camera.WebcamName; import org.openftc.apriltag.AprilTagDetection; import org.openftc.easyopencv.OpenCvCamera; import org.openftc.easyopencv.OpenCvCameraFactory; import org.openftc.easyopencv.OpenCvCameraRotation; import org.openftc.easyopencv.OpenCvInternalCamera; import java.util.ArrayList;
10,096
package org.firstinspires.ftc.teamcode.drive.opmode; @Config @Autonomous(group = "drive") public class threeConeTry extends LinearOpMode { public static double SPEED = 0.15; boolean Starting = false; int ConusIndex = 0; double value; public static double FirstDistance = 45.5; OpenCvCamera camera; AprilTagDetectionPipeline aprilTagDetectionPipeline; static final double FEET_PER_METER = 3.28084; // Lens intrinsics // UNITS ARE PIXELS // NOTE: this calibration is for the C920 webcam at 800x448. // You will need to do your own calibration for other configurations! double fx = 578.272; double fy = 578.272; double cx = 402.145; double cy = 221.506; private Servo Armservo; private Servo AngleServo; private Servo Claw; private Servo orangeCone; private Servo ConeLocker; private DcMotor elevator; private DcMotor slider; private TouchSensor magnetic1; private TouchSensor magnetic2; private boolean toggle; private boolean result; // UNITS ARE METERS double tagsize = 0.166; // Tag ID 1,2,3 from the 36h11 family /*EDIT IF NEEDED!!!*/ int LEFT = 1; int MIDDLE = 2; int RIGHT = 3; boolean Parking = false; int wantedId; AprilTagDetection tagOfInterest = null; @Override public void runOpMode() throws InterruptedException { int cameraMonitorViewId = hardwareMap.appContext.getResources().getIdentifier("cameraMonitorViewId", "id", hardwareMap.appContext.getPackageName()); camera = OpenCvCameraFactory.getInstance().createWebcam(hardwareMap.get(WebcamName.class, "Webcam 1"), cameraMonitorViewId); aprilTagDetectionPipeline = new AprilTagDetectionPipeline(tagsize, fx, fy, cx, cy); camera.setPipeline(aprilTagDetectionPipeline); Armservo = hardwareMap.get(Servo.class, "arm"); AngleServo = hardwareMap.get(Servo.class, "arm angle"); Claw = hardwareMap.get(Servo.class, "clips"); orangeCone = hardwareMap.get(Servo.class, "orangeCone"); ConeLocker = hardwareMap.get(Servo.class, "coneLocker"); elevator = hardwareMap.dcMotor.get("elevator"); elevator.setTargetPosition(0); elevator.setMode(DcMotor.RunMode.RUN_TO_POSITION); elevator.setMode(DcMotor.RunMode.RUN_USING_ENCODER); elevator.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); slider = hardwareMap.dcMotor.get("leftEncoder"); double armservoTarget = 0.5; double Angle = 0.4; double ClawPos = 0.65; camera.openCameraDeviceAsync(new OpenCvCamera.AsyncCameraOpenListener() { @Override public void onOpened() { camera.startStreaming(800,448, OpenCvCameraRotation.UPRIGHT); } @Override public void onError(int errorCode) { } }); telemetry.setMsTransmissionInterval(50); /* * The INIT-loop: * This REPLACES waitForStart! */ while (!isStarted() && !isStopRequested()) { ArrayList<AprilTagDetection> currentDetections = aprilTagDetectionPipeline.getLatestDetections(); if(currentDetections.size() != 0) { boolean tagFound = false; for(AprilTagDetection tag : currentDetections) { if(tag.id == LEFT || tag.id == MIDDLE || tag.id == RIGHT) { tagOfInterest = tag; tagFound = true; break; } } if(tagFound) { telemetry.addLine("Tag of interest is in sight!\n\nLocation data:"); tagToTelemetry(tagOfInterest); wantedId = tagOfInterest.id; } else { telemetry.addLine("Don't see tag of interest :("); if(tagOfInterest == null) { telemetry.addLine("(The tag has never been seen)"); } else { telemetry.addLine("\nBut we HAVE seen the tag before; last seen at:"); tagToTelemetry(tagOfInterest); } } } else { telemetry.addLine("Don't see tag of interest :("); if(tagOfInterest == null) { telemetry.addLine("(The tag has never been seen)"); } else { telemetry.addLine("\nBut we HAVE seen the tag before; last seen at:"); tagToTelemetry(tagOfInterest); } } telemetry.update(); sleep(20); }
package org.firstinspires.ftc.teamcode.drive.opmode; @Config @Autonomous(group = "drive") public class threeConeTry extends LinearOpMode { public static double SPEED = 0.15; boolean Starting = false; int ConusIndex = 0; double value; public static double FirstDistance = 45.5; OpenCvCamera camera; AprilTagDetectionPipeline aprilTagDetectionPipeline; static final double FEET_PER_METER = 3.28084; // Lens intrinsics // UNITS ARE PIXELS // NOTE: this calibration is for the C920 webcam at 800x448. // You will need to do your own calibration for other configurations! double fx = 578.272; double fy = 578.272; double cx = 402.145; double cy = 221.506; private Servo Armservo; private Servo AngleServo; private Servo Claw; private Servo orangeCone; private Servo ConeLocker; private DcMotor elevator; private DcMotor slider; private TouchSensor magnetic1; private TouchSensor magnetic2; private boolean toggle; private boolean result; // UNITS ARE METERS double tagsize = 0.166; // Tag ID 1,2,3 from the 36h11 family /*EDIT IF NEEDED!!!*/ int LEFT = 1; int MIDDLE = 2; int RIGHT = 3; boolean Parking = false; int wantedId; AprilTagDetection tagOfInterest = null; @Override public void runOpMode() throws InterruptedException { int cameraMonitorViewId = hardwareMap.appContext.getResources().getIdentifier("cameraMonitorViewId", "id", hardwareMap.appContext.getPackageName()); camera = OpenCvCameraFactory.getInstance().createWebcam(hardwareMap.get(WebcamName.class, "Webcam 1"), cameraMonitorViewId); aprilTagDetectionPipeline = new AprilTagDetectionPipeline(tagsize, fx, fy, cx, cy); camera.setPipeline(aprilTagDetectionPipeline); Armservo = hardwareMap.get(Servo.class, "arm"); AngleServo = hardwareMap.get(Servo.class, "arm angle"); Claw = hardwareMap.get(Servo.class, "clips"); orangeCone = hardwareMap.get(Servo.class, "orangeCone"); ConeLocker = hardwareMap.get(Servo.class, "coneLocker"); elevator = hardwareMap.dcMotor.get("elevator"); elevator.setTargetPosition(0); elevator.setMode(DcMotor.RunMode.RUN_TO_POSITION); elevator.setMode(DcMotor.RunMode.RUN_USING_ENCODER); elevator.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); slider = hardwareMap.dcMotor.get("leftEncoder"); double armservoTarget = 0.5; double Angle = 0.4; double ClawPos = 0.65; camera.openCameraDeviceAsync(new OpenCvCamera.AsyncCameraOpenListener() { @Override public void onOpened() { camera.startStreaming(800,448, OpenCvCameraRotation.UPRIGHT); } @Override public void onError(int errorCode) { } }); telemetry.setMsTransmissionInterval(50); /* * The INIT-loop: * This REPLACES waitForStart! */ while (!isStarted() && !isStopRequested()) { ArrayList<AprilTagDetection> currentDetections = aprilTagDetectionPipeline.getLatestDetections(); if(currentDetections.size() != 0) { boolean tagFound = false; for(AprilTagDetection tag : currentDetections) { if(tag.id == LEFT || tag.id == MIDDLE || tag.id == RIGHT) { tagOfInterest = tag; tagFound = true; break; } } if(tagFound) { telemetry.addLine("Tag of interest is in sight!\n\nLocation data:"); tagToTelemetry(tagOfInterest); wantedId = tagOfInterest.id; } else { telemetry.addLine("Don't see tag of interest :("); if(tagOfInterest == null) { telemetry.addLine("(The tag has never been seen)"); } else { telemetry.addLine("\nBut we HAVE seen the tag before; last seen at:"); tagToTelemetry(tagOfInterest); } } } else { telemetry.addLine("Don't see tag of interest :("); if(tagOfInterest == null) { telemetry.addLine("(The tag has never been seen)"); } else { telemetry.addLine("\nBut we HAVE seen the tag before; last seen at:"); tagToTelemetry(tagOfInterest); } } telemetry.update(); sleep(20); }
SampleMecanumDrive drive = new SampleMecanumDrive(hardwareMap);
0
2023-12-15 16:57:19+00:00
12k
PeytonPlayz595/0.30-WebGL-Server
src/com/mojang/minecraft/server/MinecraftServer.java
[ { "identifier": "LevelIO", "path": "src/com/mojang/minecraft/level/LevelIO.java", "snippet": "public final class LevelIO {\r\n\r\n private MinecraftServer server;\r\n\r\n\r\n public LevelIO(MinecraftServer var1) {\r\n this.server = var1;\r\n }\r\n\r\n public final Level load(InputStream var...
import com.mojang.minecraft.level.LevelIO; import com.mojang.minecraft.level.generator.LevelGenerator; import com.mojang.minecraft.net.PacketType; import com.mojang.net.BindTo; import com.mojang.net.NetworkHandler; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.net.URLEncoder; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Random; import java.util.logging.ConsoleHandler; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger;
9,756
package com.mojang.minecraft.server; public class MinecraftServer implements Runnable { static Logger logger = Logger.getLogger("MinecraftServer"); static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); private BindTo bindTo; private Map m = new HashMap(); private List n = new ArrayList(); private List o = new ArrayList(); private Properties properties = new Properties(); public com.mojang.minecraft.level.Level mainLevel; public String serverName; public String MOTD; public boolean adminSlot; private NetworkManager[] networkManager; public PlayerManager playerManager1 = new PlayerManager("Admins", new File("admins.txt")); public PlayerManager playerManager2 = new PlayerManager("Banned", new File("banned.txt")); private PlayerManager playerManager3 = new PlayerManager("Banned (IP)", new File("banned-ip.txt")); public PlayerManager playerManager4 = new PlayerManager("Players", new File("players.txt")); private List v = new ArrayList(); private String salt = "" + (new Random()).nextLong(); private String x = ""; private boolean growTrees; public MinecraftServer() { this.growTrees = false; try { this.properties.load(new FileReader("server.properties")); } catch (Exception var4) { logger.warning("Failed to load server.properties!"); } try { this.serverName = this.properties.getProperty("server-name", "Minecraft Server"); this.MOTD = this.properties.getProperty("motd", "Welcome to my Minecraft Server!"); this.growTrees = Boolean.parseBoolean(this.properties.getProperty("grow-trees", "false")); this.adminSlot = Boolean.parseBoolean(this.properties.getProperty("admin-slot", "false")); this.properties.setProperty("server-name", this.serverName); this.properties.setProperty("motd", this.MOTD); this.properties.setProperty("max-connections", "3"); this.properties.setProperty("grow-trees", "" + this.growTrees); this.properties.setProperty("admin-slot", "" + this.adminSlot); } catch (Exception var3) { var3.printStackTrace(); logger.warning("server.properties is broken! Delete it or fix it!"); System.exit(0); } try { this.properties.store(new FileWriter("server.properties"), "Minecraft server properties"); } catch (Exception var2) { logger.warning("Failed to save server.properties!"); } this.networkManager = new NetworkManager[32]; this.bindTo = new BindTo(this); (new ConsoleInput(this)).start(); } public final void a(NetworkHandler var1) { NetworkManager var2; if((var2 = (NetworkManager)this.m.get(var1)) != null) { this.playerManager4.removePlayer(var2.playerName); logger.info(var2 + " disconnected"); this.m.remove(var2.networkHandler); this.n.remove(var2); if(var2.playerID >= 0) { this.networkManager[var2.playerID] = null; }
package com.mojang.minecraft.server; public class MinecraftServer implements Runnable { static Logger logger = Logger.getLogger("MinecraftServer"); static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); private BindTo bindTo; private Map m = new HashMap(); private List n = new ArrayList(); private List o = new ArrayList(); private Properties properties = new Properties(); public com.mojang.minecraft.level.Level mainLevel; public String serverName; public String MOTD; public boolean adminSlot; private NetworkManager[] networkManager; public PlayerManager playerManager1 = new PlayerManager("Admins", new File("admins.txt")); public PlayerManager playerManager2 = new PlayerManager("Banned", new File("banned.txt")); private PlayerManager playerManager3 = new PlayerManager("Banned (IP)", new File("banned-ip.txt")); public PlayerManager playerManager4 = new PlayerManager("Players", new File("players.txt")); private List v = new ArrayList(); private String salt = "" + (new Random()).nextLong(); private String x = ""; private boolean growTrees; public MinecraftServer() { this.growTrees = false; try { this.properties.load(new FileReader("server.properties")); } catch (Exception var4) { logger.warning("Failed to load server.properties!"); } try { this.serverName = this.properties.getProperty("server-name", "Minecraft Server"); this.MOTD = this.properties.getProperty("motd", "Welcome to my Minecraft Server!"); this.growTrees = Boolean.parseBoolean(this.properties.getProperty("grow-trees", "false")); this.adminSlot = Boolean.parseBoolean(this.properties.getProperty("admin-slot", "false")); this.properties.setProperty("server-name", this.serverName); this.properties.setProperty("motd", this.MOTD); this.properties.setProperty("max-connections", "3"); this.properties.setProperty("grow-trees", "" + this.growTrees); this.properties.setProperty("admin-slot", "" + this.adminSlot); } catch (Exception var3) { var3.printStackTrace(); logger.warning("server.properties is broken! Delete it or fix it!"); System.exit(0); } try { this.properties.store(new FileWriter("server.properties"), "Minecraft server properties"); } catch (Exception var2) { logger.warning("Failed to save server.properties!"); } this.networkManager = new NetworkManager[32]; this.bindTo = new BindTo(this); (new ConsoleInput(this)).start(); } public final void a(NetworkHandler var1) { NetworkManager var2; if((var2 = (NetworkManager)this.m.get(var1)) != null) { this.playerManager4.removePlayer(var2.playerName); logger.info(var2 + " disconnected"); this.m.remove(var2.networkHandler); this.n.remove(var2); if(var2.playerID >= 0) { this.networkManager[var2.playerID] = null; }
this.a(PacketType.DESPAWN_PLAYER, new Object[]{Integer.valueOf(var2.playerID)});
2
2023-12-18 15:38:59+00:00
12k
Frig00/Progetto-Ing-Software
src/main/java/it/unipv/po/aioobe/trenissimo/view/ViaggioPreferitoControl.java
[ { "identifier": "Utils", "path": "src/main/java/it/unipv/po/aioobe/trenissimo/model/Utils.java", "snippet": "public class Utils {\n\n /**\n * Metodo che converte una stringa contente un tempo, in secondi.\n *\n * @param time in formato \"ore:minuti:secondi\"\n * @return Integer, i sec...
import it.unipv.po.aioobe.trenissimo.model.Utils; import it.unipv.po.aioobe.trenissimo.model.persistence.entity.ViaggiPreferitiEntity; import it.unipv.po.aioobe.trenissimo.model.persistence.service.CachedStopsService; import it.unipv.po.aioobe.trenissimo.model.user.Account; import it.unipv.po.aioobe.trenissimo.model.viaggio.ricerca.Ricerca; import javafx.concurrent.Task; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.VBox; import org.jetbrains.annotations.Nullable; import org.kordamp.ikonli.javafx.FontIcon; import java.io.IOException; import java.time.LocalDateTime;
8,700
package it.unipv.po.aioobe.trenissimo.view; /** * Main class che gestisce il render del file viaggioPreferitoControl.fxml * è anche il controller di se stesso * * @author ArrayIndexOutOfBoundsException * @see VBox * @see it.unipv.po.aioobe.trenissimo.view.accountSettingsView */ public class ViaggioPreferitoControl extends VBox { public static Boolean fromViaggioControl = false; @FXML private Label lblOrario; @FXML private Label lblPartenza; @FXML private Label lblArrivo; @FXML private Label lblCambi; @FXML private Label lblAdulti; @FXML private Label lblRagazzi; @FXML private Label lblBambini; @FXML private Label lblAnimali; @FXML private Button btnAcquista; @FXML private VBox boxChanges; @FXML private VBox boxChangesContainer; @FXML private FontIcon icoChanges; @FXML private Button btnDeletePreferito; @FXML private Label lblDeleteOK; private ViaggiPreferitiEntity viaggio; /** * Costruttore per la visualizzazione di viaggioPreferitoControl.fxml */ public ViaggioPreferitoControl() { FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("accountSettingsView/viaggioPreferitoControl.fxml")); fxmlLoader.setRoot(this); fxmlLoader.setController(this); try { fxmlLoader.load(); } catch (IOException e) { e.printStackTrace(); } } /** * Costruttore per la visualizzazione di viaggioControl.fxml * * @param viaggiPreferiti ViaggiPreferitiEntity da cui estrarre informazioni */ public ViaggioPreferitoControl(ViaggiPreferitiEntity viaggiPreferiti) { this(); setViaggio(viaggiPreferiti); } /** * Ritorna un ViaggioPreferito * * @return viaggio preferito */ public ViaggiPreferitiEntity getViaggio() { return viaggio; } /** * Raccoglie i dati di uno ViaggioPreferitoEntity * * @param viaggioPreferito */ public void setViaggio(ViaggiPreferitiEntity viaggioPreferito) { this.viaggio = viaggioPreferito; lblOrario.textProperty().setValue(viaggio.getOra().toString()); lblPartenza.textProperty().setValue(viaggio.getStazionePartenza()); lblArrivo.textProperty().setValue(viaggio.getStazioneArrivo()); lblCambi.textProperty().setValue(viaggio.getnCambi() + " cambi"); lblAdulti.textProperty().setValue(viaggio.getnAdulti().toString()); lblRagazzi.textProperty().setValue(viaggio.getnRagazzi().toString()); lblBambini.textProperty().setValue(viaggio.getnBambini().toString()); lblAnimali.textProperty().setValue(viaggio.getnAnimali().toString()); } /** * Permette di eseguire una ricerca che porterà direttamente all'acquisto del biglietto * * @see CachedStopsService * @see Ricerca * @see AcquistoView * @see it.unipv.po.aioobe.trenissimo.model.persistence.entity.StopsEntity * @see it.unipv.po.aioobe.trenissimo.model.viaggio.Viaggio */ @FXML protected void onAcquista() {
package it.unipv.po.aioobe.trenissimo.view; /** * Main class che gestisce il render del file viaggioPreferitoControl.fxml * è anche il controller di se stesso * * @author ArrayIndexOutOfBoundsException * @see VBox * @see it.unipv.po.aioobe.trenissimo.view.accountSettingsView */ public class ViaggioPreferitoControl extends VBox { public static Boolean fromViaggioControl = false; @FXML private Label lblOrario; @FXML private Label lblPartenza; @FXML private Label lblArrivo; @FXML private Label lblCambi; @FXML private Label lblAdulti; @FXML private Label lblRagazzi; @FXML private Label lblBambini; @FXML private Label lblAnimali; @FXML private Button btnAcquista; @FXML private VBox boxChanges; @FXML private VBox boxChangesContainer; @FXML private FontIcon icoChanges; @FXML private Button btnDeletePreferito; @FXML private Label lblDeleteOK; private ViaggiPreferitiEntity viaggio; /** * Costruttore per la visualizzazione di viaggioPreferitoControl.fxml */ public ViaggioPreferitoControl() { FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("accountSettingsView/viaggioPreferitoControl.fxml")); fxmlLoader.setRoot(this); fxmlLoader.setController(this); try { fxmlLoader.load(); } catch (IOException e) { e.printStackTrace(); } } /** * Costruttore per la visualizzazione di viaggioControl.fxml * * @param viaggiPreferiti ViaggiPreferitiEntity da cui estrarre informazioni */ public ViaggioPreferitoControl(ViaggiPreferitiEntity viaggiPreferiti) { this(); setViaggio(viaggiPreferiti); } /** * Ritorna un ViaggioPreferito * * @return viaggio preferito */ public ViaggiPreferitiEntity getViaggio() { return viaggio; } /** * Raccoglie i dati di uno ViaggioPreferitoEntity * * @param viaggioPreferito */ public void setViaggio(ViaggiPreferitiEntity viaggioPreferito) { this.viaggio = viaggioPreferito; lblOrario.textProperty().setValue(viaggio.getOra().toString()); lblPartenza.textProperty().setValue(viaggio.getStazionePartenza()); lblArrivo.textProperty().setValue(viaggio.getStazioneArrivo()); lblCambi.textProperty().setValue(viaggio.getnCambi() + " cambi"); lblAdulti.textProperty().setValue(viaggio.getnAdulti().toString()); lblRagazzi.textProperty().setValue(viaggio.getnRagazzi().toString()); lblBambini.textProperty().setValue(viaggio.getnBambini().toString()); lblAnimali.textProperty().setValue(viaggio.getnAnimali().toString()); } /** * Permette di eseguire una ricerca che porterà direttamente all'acquisto del biglietto * * @see CachedStopsService * @see Ricerca * @see AcquistoView * @see it.unipv.po.aioobe.trenissimo.model.persistence.entity.StopsEntity * @see it.unipv.po.aioobe.trenissimo.model.viaggio.Viaggio */ @FXML protected void onAcquista() {
var lista = CachedStopsService.getInstance().findAll();
2
2023-12-21 10:41:11+00:00
12k
chulakasam/layered
src/main/java/com/example/layeredarchitecture/controller/PlaceOrderFormController.java
[ { "identifier": "BOFactory", "path": "src/main/java/com/example/layeredarchitecture/bo/BOFactory.java", "snippet": "public class BOFactory {\n private static BOFactory boFactory;\n private BOFactory(){\n\n }\n public static BOFactory getBOFactory(){\n return (boFactory==null) ? boFact...
import com.example.layeredarchitecture.bo.BOFactory; import com.example.layeredarchitecture.bo.PlaceOrderBO; import com.example.layeredarchitecture.bo.PlaceOrderBOImpl; import com.example.layeredarchitecture.dao.custom.CustomerDAO; import com.example.layeredarchitecture.dao.custom.Impl.CustomerDAOImpl; import com.example.layeredarchitecture.dao.custom.Impl.ItemDAO; import com.example.layeredarchitecture.dao.custom.Impl.OrderDAO; import com.example.layeredarchitecture.dao.custom.Impl.OrderDetailDAOImpl; import com.example.layeredarchitecture.dao.custom.ItemDao; import com.example.layeredarchitecture.dao.custom.OrderDao; import com.example.layeredarchitecture.dao.custom.OrderDetailDAO; import com.example.layeredarchitecture.db.DBConnection; import com.example.layeredarchitecture.model.CustomerDTO; import com.example.layeredarchitecture.model.ItemDTO; import com.example.layeredarchitecture.model.OrderDetailDTO; import com.example.layeredarchitecture.view.tdm.OrderDetailTM; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXComboBox; import javafx.application.Platform; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import java.io.IOException; import java.math.BigDecimal; import java.net.URL; import java.sql.*; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors;
7,877
package com.example.layeredarchitecture.controller; public class PlaceOrderFormController { public AnchorPane root; public JFXButton btnPlaceOrder; public TextField txtCustomerName; public TextField txtDescription; public TextField txtQtyOnHand; public JFXButton btnSave; public TableView<OrderDetailTM> tblOrderDetails; public TextField txtUnitPrice; public JFXComboBox<String> cmbCustomerId; public JFXComboBox<String> cmbItemCode; public TextField txtQty; public Label lblId; public Label lblDate; public Label lblTotal; private String orderId; PlaceOrderBO placeOrderBO = (PlaceOrderBO) BOFactory.getBOFactory().getBOFactory(BOFactory.BOTypes.PLACE_ORDER); public void initialize() throws SQLException, ClassNotFoundException { tblOrderDetails.getColumns().get(0).setCellValueFactory(new PropertyValueFactory<>("code")); tblOrderDetails.getColumns().get(1).setCellValueFactory(new PropertyValueFactory<>("description")); tblOrderDetails.getColumns().get(2).setCellValueFactory(new PropertyValueFactory<>("qty")); tblOrderDetails.getColumns().get(3).setCellValueFactory(new PropertyValueFactory<>("unitPrice")); tblOrderDetails.getColumns().get(4).setCellValueFactory(new PropertyValueFactory<>("total")); TableColumn<OrderDetailTM, Button> lastCol = (TableColumn<OrderDetailTM, Button>) tblOrderDetails.getColumns().get(5); lastCol.setCellValueFactory(param -> { Button btnDelete = new Button("Delete"); btnDelete.setOnAction(event -> { tblOrderDetails.getItems().remove(param.getValue()); tblOrderDetails.getSelectionModel().clearSelection(); calculateTotal(); enableOrDisablePlaceOrderButton(); }); return new ReadOnlyObjectWrapper<>(btnDelete); }); orderId = generateNewOrderId(); lblId.setText("Order ID: " + orderId); lblDate.setText(LocalDate.now().toString()); btnPlaceOrder.setDisable(true); txtCustomerName.setFocusTraversable(false); txtCustomerName.setEditable(false); txtDescription.setFocusTraversable(false); txtDescription.setEditable(false); txtUnitPrice.setFocusTraversable(false); txtUnitPrice.setEditable(false); txtQtyOnHand.setFocusTraversable(false); txtQtyOnHand.setEditable(false); txtQty.setOnAction(event -> btnSave.fire()); txtQty.setEditable(false); btnSave.setDisable(true); cmbCustomerId.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { enableOrDisablePlaceOrderButton(); if (newValue != null) { try { /*Search Customer*/ Connection connection = DBConnection.getDbConnection().getConnection(); try { //CustomerDAOImpl customerDAO = new CustomerDAOImpl(); if (!placeOrderBO.existCustomer(newValue + "")) { // "There is no such customer associated with the id " + id new Alert(Alert.AlertType.ERROR, "There is no such customer associated with the id " + newValue + "").show(); } PreparedStatement pstm = connection.prepareStatement("SELECT * FROM Customer WHERE id=?"); pstm.setString(1, newValue + ""); ResultSet rst = pstm.executeQuery(); rst.next(); CustomerDTO customerDTO = new CustomerDTO(newValue + "", rst.getString("name"), rst.getString("address")); txtCustomerName.setText(customerDTO.getName()); } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to find the customer " + newValue + "" + e).show(); } } catch (SQLException throwables) { throwables.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtCustomerName.clear(); } }); cmbItemCode.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newItemCode) -> { txtQty.setEditable(newItemCode != null); btnSave.setDisable(newItemCode == null); if (newItemCode != null) { /*Find Item*/ try { //ItemDAO itemDAO = new ItemDAO(); if (!placeOrderBO.existItem(newItemCode + "")) { // throw new NotFoundException("There is no such item associated with the id " + code); } Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("SELECT * FROM Item WHERE code=?"); pstm.setString(1, newItemCode + ""); ResultSet rst = pstm.executeQuery(); rst.next();
package com.example.layeredarchitecture.controller; public class PlaceOrderFormController { public AnchorPane root; public JFXButton btnPlaceOrder; public TextField txtCustomerName; public TextField txtDescription; public TextField txtQtyOnHand; public JFXButton btnSave; public TableView<OrderDetailTM> tblOrderDetails; public TextField txtUnitPrice; public JFXComboBox<String> cmbCustomerId; public JFXComboBox<String> cmbItemCode; public TextField txtQty; public Label lblId; public Label lblDate; public Label lblTotal; private String orderId; PlaceOrderBO placeOrderBO = (PlaceOrderBO) BOFactory.getBOFactory().getBOFactory(BOFactory.BOTypes.PLACE_ORDER); public void initialize() throws SQLException, ClassNotFoundException { tblOrderDetails.getColumns().get(0).setCellValueFactory(new PropertyValueFactory<>("code")); tblOrderDetails.getColumns().get(1).setCellValueFactory(new PropertyValueFactory<>("description")); tblOrderDetails.getColumns().get(2).setCellValueFactory(new PropertyValueFactory<>("qty")); tblOrderDetails.getColumns().get(3).setCellValueFactory(new PropertyValueFactory<>("unitPrice")); tblOrderDetails.getColumns().get(4).setCellValueFactory(new PropertyValueFactory<>("total")); TableColumn<OrderDetailTM, Button> lastCol = (TableColumn<OrderDetailTM, Button>) tblOrderDetails.getColumns().get(5); lastCol.setCellValueFactory(param -> { Button btnDelete = new Button("Delete"); btnDelete.setOnAction(event -> { tblOrderDetails.getItems().remove(param.getValue()); tblOrderDetails.getSelectionModel().clearSelection(); calculateTotal(); enableOrDisablePlaceOrderButton(); }); return new ReadOnlyObjectWrapper<>(btnDelete); }); orderId = generateNewOrderId(); lblId.setText("Order ID: " + orderId); lblDate.setText(LocalDate.now().toString()); btnPlaceOrder.setDisable(true); txtCustomerName.setFocusTraversable(false); txtCustomerName.setEditable(false); txtDescription.setFocusTraversable(false); txtDescription.setEditable(false); txtUnitPrice.setFocusTraversable(false); txtUnitPrice.setEditable(false); txtQtyOnHand.setFocusTraversable(false); txtQtyOnHand.setEditable(false); txtQty.setOnAction(event -> btnSave.fire()); txtQty.setEditable(false); btnSave.setDisable(true); cmbCustomerId.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { enableOrDisablePlaceOrderButton(); if (newValue != null) { try { /*Search Customer*/ Connection connection = DBConnection.getDbConnection().getConnection(); try { //CustomerDAOImpl customerDAO = new CustomerDAOImpl(); if (!placeOrderBO.existCustomer(newValue + "")) { // "There is no such customer associated with the id " + id new Alert(Alert.AlertType.ERROR, "There is no such customer associated with the id " + newValue + "").show(); } PreparedStatement pstm = connection.prepareStatement("SELECT * FROM Customer WHERE id=?"); pstm.setString(1, newValue + ""); ResultSet rst = pstm.executeQuery(); rst.next(); CustomerDTO customerDTO = new CustomerDTO(newValue + "", rst.getString("name"), rst.getString("address")); txtCustomerName.setText(customerDTO.getName()); } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to find the customer " + newValue + "" + e).show(); } } catch (SQLException throwables) { throwables.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtCustomerName.clear(); } }); cmbItemCode.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newItemCode) -> { txtQty.setEditable(newItemCode != null); btnSave.setDisable(newItemCode == null); if (newItemCode != null) { /*Find Item*/ try { //ItemDAO itemDAO = new ItemDAO(); if (!placeOrderBO.existItem(newItemCode + "")) { // throw new NotFoundException("There is no such item associated with the id " + code); } Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("SELECT * FROM Item WHERE code=?"); pstm.setString(1, newItemCode + ""); ResultSet rst = pstm.executeQuery(); rst.next();
ItemDTO item = new ItemDTO(newItemCode + "", rst.getString("description"), rst.getBigDecimal("unitPrice"), rst.getInt("qtyOnHand"));
13
2023-12-15 04:45:10+00:00
12k
pan2013e/ppt4j
misc/src/main/java/ppt4j/Demo.java
[ { "identifier": "PatchAnalyzer", "path": "framework/src/main/java/ppt4j/analysis/patch/PatchAnalyzer.java", "snippet": "@Log4j\npublic class PatchAnalyzer {\n\n @Property(\"ppt4j.analysis.patch.presence_threshold\")\n private static double PATCH_PRESENCE_THRESHOLD;\n\n @Property(\"ppt4j.feature...
import ppt4j.analysis.patch.PatchAnalyzer; import ppt4j.database.Vulnerability; import ppt4j.database.VulnerabilityInfo; import ppt4j.factory.DatabaseFactory; import ppt4j.factory.ExtractorFactory; import ppt4j.util.PropertyUtils; import ppt4j.util.ResourceUtils; import ppt4j.util.VMUtils; import com.sun.tools.attach.VirtualMachine; import java.io.IOException;
10,110
package ppt4j; // Command line example (invoke in the project root folder) // java -Djdk.attach.allowAttachSelf=true --add-opens java.base/java.lang=ALL-UNNAMED \ // --add-opens java.base/java.lang.reflect=ALL-UNNAMED \ // -cp misc/target/classes:framework/target/classes:lib/*:${HOME}/database/IntelliJ_IDEA/IU-213.7172.25/lib.jar \ // ppt4j.Demo // p.s. In some shells, e.g. zsh, you may need to escape the asterisk // In this prototype version, this class should be placed under `ppt4j` package, // otherwise the aspectjweaver agent will not work as expected, and some properties // will not be automatically loaded. /** * This class is a demo of how to use the patch * presence test framework in real cases * DEMO ONLY, NOT COMPILABLE */ @SuppressWarnings("unused") public class Demo { static { String prop = System.getProperty("jdk.attach.allowAttachSelf", "false"); if (!prop.equals("true")) { System.err.println("Error: set -Djdk.attach.allowAttachSelf=true when starting the VM"); System.exit(1); } try { VirtualMachine vm = VirtualMachine.attach("" + ProcessHandle.current().pid()); vm.loadAgent("lib/aspectjweaver-1.9.19.jar"); vm.detach(); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); System.exit(1); } PropertyUtils.load(ResourceUtils.readProperties()); PropertyUtils.init(); } public static void main(String[] args) throws IOException { String home = System.getProperty("user.home"); // 1. Provide the directory of the project (pre-patch and post-patch versions) // Specify the string to something like "...src/main/java", so that // the framework can find the source code of the project String PREPATCH_DIR = home + "/database/prepatch/8/src/main/java"; String POSTPATCH_DIR = home + "/database/postpatch/8/src/main/java"; // 2. Provide the top level directory of the compiled classes // e.g., the classfile of aaa.bbb.XXX is in `CLASSPATH/aaa/bbb/XXX.class`, // so you should provide the path to `CLASSPATH` // or you can provide the path to a .jar file String CLASSPATH = home + "/database/IntelliJ_IDEA/IU-213.7172.25/lib.jar"; // 3. Provide paths to third-party source code (optional) // For vulnerabilities in the dataset, this step is not required String[] THIRD_PARTY = new String[]{"<path to third-party dependencies>"}; // Note 1: You should manually set the classpath when invoking JVM using "-cp", // otherwise the framework will not be able to load classes when analyzing. // Note 2: PPT4J loads the bytecode to be analyzed, so be careful if you // want to test its own 3rd-party dependencies (e.g., asm). It should be fine // if you pass in a directory of classfiles, e.g., target/classes. But if you pass // in a jar file, please place your jar file before `lib/*` in the classpath, // so that the VM loads your jar file first. However, as the loaded dependency // changes, the framework may not work as expected. VMUtils.checkVMClassPathPresent(CLASSPATH); // 3. Create an ExtractorFactory instance with previous resources // The factory instance will be responsible for feature extractions // and feature matching
package ppt4j; // Command line example (invoke in the project root folder) // java -Djdk.attach.allowAttachSelf=true --add-opens java.base/java.lang=ALL-UNNAMED \ // --add-opens java.base/java.lang.reflect=ALL-UNNAMED \ // -cp misc/target/classes:framework/target/classes:lib/*:${HOME}/database/IntelliJ_IDEA/IU-213.7172.25/lib.jar \ // ppt4j.Demo // p.s. In some shells, e.g. zsh, you may need to escape the asterisk // In this prototype version, this class should be placed under `ppt4j` package, // otherwise the aspectjweaver agent will not work as expected, and some properties // will not be automatically loaded. /** * This class is a demo of how to use the patch * presence test framework in real cases * DEMO ONLY, NOT COMPILABLE */ @SuppressWarnings("unused") public class Demo { static { String prop = System.getProperty("jdk.attach.allowAttachSelf", "false"); if (!prop.equals("true")) { System.err.println("Error: set -Djdk.attach.allowAttachSelf=true when starting the VM"); System.exit(1); } try { VirtualMachine vm = VirtualMachine.attach("" + ProcessHandle.current().pid()); vm.loadAgent("lib/aspectjweaver-1.9.19.jar"); vm.detach(); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); System.exit(1); } PropertyUtils.load(ResourceUtils.readProperties()); PropertyUtils.init(); } public static void main(String[] args) throws IOException { String home = System.getProperty("user.home"); // 1. Provide the directory of the project (pre-patch and post-patch versions) // Specify the string to something like "...src/main/java", so that // the framework can find the source code of the project String PREPATCH_DIR = home + "/database/prepatch/8/src/main/java"; String POSTPATCH_DIR = home + "/database/postpatch/8/src/main/java"; // 2. Provide the top level directory of the compiled classes // e.g., the classfile of aaa.bbb.XXX is in `CLASSPATH/aaa/bbb/XXX.class`, // so you should provide the path to `CLASSPATH` // or you can provide the path to a .jar file String CLASSPATH = home + "/database/IntelliJ_IDEA/IU-213.7172.25/lib.jar"; // 3. Provide paths to third-party source code (optional) // For vulnerabilities in the dataset, this step is not required String[] THIRD_PARTY = new String[]{"<path to third-party dependencies>"}; // Note 1: You should manually set the classpath when invoking JVM using "-cp", // otherwise the framework will not be able to load classes when analyzing. // Note 2: PPT4J loads the bytecode to be analyzed, so be careful if you // want to test its own 3rd-party dependencies (e.g., asm). It should be fine // if you pass in a directory of classfiles, e.g., target/classes. But if you pass // in a jar file, please place your jar file before `lib/*` in the classpath, // so that the VM loads your jar file first. However, as the loaded dependency // changes, the framework may not work as expected. VMUtils.checkVMClassPathPresent(CLASSPATH); // 3. Create an ExtractorFactory instance with previous resources // The factory instance will be responsible for feature extractions // and feature matching
ExtractorFactory factory = ExtractorFactory.get(
4
2023-12-14 15:33:50+00:00
12k
f1den/MrCrayfishGunMod
src/main/java/com/mrcrayfish/guns/common/ProjectileManager.java
[ { "identifier": "ProjectileEntity", "path": "src/main/java/com/mrcrayfish/guns/entity/ProjectileEntity.java", "snippet": "public class ProjectileEntity extends Entity implements IEntityAdditionalSpawnData\n{\n private static final Predicate<Entity> PROJECTILE_TARGETS = input -> input != null && input...
import com.mrcrayfish.guns.entity.ProjectileEntity; import com.mrcrayfish.guns.init.ModEntities; import com.mrcrayfish.guns.interfaces.IProjectileFactory; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import net.minecraftforge.registries.ForgeRegistries; import java.util.HashMap; import java.util.Map;
8,575
package com.mrcrayfish.guns.common; /** * A class to manage custom projectile factories * * Author: MrCrayfish */ public class ProjectileManager { private static ProjectileManager instance = null; public static ProjectileManager getInstance() { if(instance == null) { instance = new ProjectileManager(); } return instance; }
package com.mrcrayfish.guns.common; /** * A class to manage custom projectile factories * * Author: MrCrayfish */ public class ProjectileManager { private static ProjectileManager instance = null; public static ProjectileManager getInstance() { if(instance == null) { instance = new ProjectileManager(); } return instance; }
private final IProjectileFactory DEFAULT_FACTORY = (worldIn, entity, weapon, item, modifiedGun) -> new ProjectileEntity(ModEntities.PROJECTILE.get(), worldIn, entity, weapon, item, modifiedGun);
0
2023-12-18 15:04:35+00:00
12k
Team319/SwerveTemplate_with_AK
src/main/java/frc/robot/RobotContainer.java
[ { "identifier": "DriveCommands", "path": "src/main/java/frc/robot/commands/DriveCommands.java", "snippet": "public class DriveCommands {\n private static final double DEADBAND = 0.2;\n private static final double JOYSTICK_GOVERNOR = 0.3; // this value must not exceed 1.0\n private static final double...
import com.pathplanner.lib.auto.AutoBuilder; import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.wpilibj.GenericHID; import edu.wpi.first.wpilibj.XboxController; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.Commands; import edu.wpi.first.wpilibj2.command.button.CommandXboxController; import frc.robot.commands.DriveCommands; import frc.robot.commands.FeedForwardCharacterization; import frc.robot.subsystems.drive.Drive; import frc.robot.subsystems.drive.GyroIO; import frc.robot.subsystems.drive.GyroIOPigeon2; import frc.robot.subsystems.drive.ModuleIO; import frc.robot.subsystems.drive.ModuleIOSim; import frc.robot.subsystems.drive.ModuleIOTalonFX; import org.littletonrobotics.junction.networktables.LoggedDashboardChooser;
7,482
// Copyright 2021-2023 FRC 6328 // http://github.com/Mechanical-Advantage // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // version 3 as published by the Free Software Foundation or // available in the root directory of this project. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. package frc.robot; /** * This class is where the bulk of the robot should be declared. Since Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including * subsystems, commands, and button mappings) should be declared here. */ public class RobotContainer { // Subsystems private final Drive drive; // private final Flywheel flywheel; // Controller private final CommandXboxController controller = new CommandXboxController(0); // Dashboard inputs private final LoggedDashboardChooser<Command> autoChooser; // private final LoggedDashboardNumber flywheelSpeedInput = // new LoggedDashboardNumber("Flywheel Speed", 1500.0); /** The container for the robot. Contains subsystems, OI devices, and commands. */ public RobotContainer() { switch (Constants.currentMode) { case REAL: // Real robot, instantiate hardware IO implementations // drive = // new Drive( // new GyroIOPigeon2(), // new ModuleIOSparkMax(0), // new ModuleIOSparkMax(1), // new ModuleIOSparkMax(2), // new ModuleIOSparkMax(3)); // flywheel = new Flywheel(new FlywheelIOSparkMax()); drive = new Drive( new GyroIOPigeon2(), new ModuleIOTalonFX(0), new ModuleIOTalonFX(1), new ModuleIOTalonFX(2), new ModuleIOTalonFX(3)); // flywheel = new Flywheel(new FlywheelIOTalonFX()); break; case SIM: // Sim robot, instantiate physics sim IO implementations drive = new Drive( new GyroIO() {}, new ModuleIOSim(), new ModuleIOSim(), new ModuleIOSim(), new ModuleIOSim()); // flywheel = new Flywheel(new FlywheelIOSim()); break; default: // Replayed robot, disable IO implementations drive = new Drive( new GyroIO() {}, new ModuleIO() {}, new ModuleIO() {}, new ModuleIO() {}, new ModuleIO() {}); // flywheel = new Flywheel(new FlywheelIO() {}); break; } // Set up named commands for PathPlanner // NamedCommands.registerCommand( // "Run Flywheel", // Commands.startEnd( // () -> flywheel.runVelocity(flywheelSpeedInput.get()), flywheel::stop, flywheel)); // Set up auto routines autoChooser = new LoggedDashboardChooser<>("Auto Choices", AutoBuilder.buildAutoChooser()); // Set up FF characterization routines autoChooser.addOption( "Drive FF Characterization", new FeedForwardCharacterization( drive, drive::runCharacterizationVolts, drive::getCharacterizationVelocity)); // autoChooser.addOption( // "Flywheel FF Characterization", // new FeedForwardCharacterization( // flywheel, flywheel::runCharacterizationVolts, flywheel::getCharacterizationVelocity)); // Configure the button bindings configureButtonBindings(); } /** * Use this method to define your button->command mappings. Buttons can be created by * instantiating a {@link GenericHID} or one of its subclasses ({@link * edu.wpi.first.wpilibj.Joystick} or {@link XboxController}), and then passing it to a {@link * edu.wpi.first.wpilibj2.command.button.JoystickButton}. */ private void configureButtonBindings() { drive.setDefaultCommand(
// Copyright 2021-2023 FRC 6328 // http://github.com/Mechanical-Advantage // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // version 3 as published by the Free Software Foundation or // available in the root directory of this project. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. package frc.robot; /** * This class is where the bulk of the robot should be declared. Since Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including * subsystems, commands, and button mappings) should be declared here. */ public class RobotContainer { // Subsystems private final Drive drive; // private final Flywheel flywheel; // Controller private final CommandXboxController controller = new CommandXboxController(0); // Dashboard inputs private final LoggedDashboardChooser<Command> autoChooser; // private final LoggedDashboardNumber flywheelSpeedInput = // new LoggedDashboardNumber("Flywheel Speed", 1500.0); /** The container for the robot. Contains subsystems, OI devices, and commands. */ public RobotContainer() { switch (Constants.currentMode) { case REAL: // Real robot, instantiate hardware IO implementations // drive = // new Drive( // new GyroIOPigeon2(), // new ModuleIOSparkMax(0), // new ModuleIOSparkMax(1), // new ModuleIOSparkMax(2), // new ModuleIOSparkMax(3)); // flywheel = new Flywheel(new FlywheelIOSparkMax()); drive = new Drive( new GyroIOPigeon2(), new ModuleIOTalonFX(0), new ModuleIOTalonFX(1), new ModuleIOTalonFX(2), new ModuleIOTalonFX(3)); // flywheel = new Flywheel(new FlywheelIOTalonFX()); break; case SIM: // Sim robot, instantiate physics sim IO implementations drive = new Drive( new GyroIO() {}, new ModuleIOSim(), new ModuleIOSim(), new ModuleIOSim(), new ModuleIOSim()); // flywheel = new Flywheel(new FlywheelIOSim()); break; default: // Replayed robot, disable IO implementations drive = new Drive( new GyroIO() {}, new ModuleIO() {}, new ModuleIO() {}, new ModuleIO() {}, new ModuleIO() {}); // flywheel = new Flywheel(new FlywheelIO() {}); break; } // Set up named commands for PathPlanner // NamedCommands.registerCommand( // "Run Flywheel", // Commands.startEnd( // () -> flywheel.runVelocity(flywheelSpeedInput.get()), flywheel::stop, flywheel)); // Set up auto routines autoChooser = new LoggedDashboardChooser<>("Auto Choices", AutoBuilder.buildAutoChooser()); // Set up FF characterization routines autoChooser.addOption( "Drive FF Characterization", new FeedForwardCharacterization( drive, drive::runCharacterizationVolts, drive::getCharacterizationVelocity)); // autoChooser.addOption( // "Flywheel FF Characterization", // new FeedForwardCharacterization( // flywheel, flywheel::runCharacterizationVolts, flywheel::getCharacterizationVelocity)); // Configure the button bindings configureButtonBindings(); } /** * Use this method to define your button->command mappings. Buttons can be created by * instantiating a {@link GenericHID} or one of its subclasses ({@link * edu.wpi.first.wpilibj.Joystick} or {@link XboxController}), and then passing it to a {@link * edu.wpi.first.wpilibj2.command.button.JoystickButton}. */ private void configureButtonBindings() { drive.setDefaultCommand(
DriveCommands.joystickDrive(
0
2023-12-16 14:59:04+00:00
12k
ReChronoRain/HyperCeiler
app/src/main/java/com/sevtinge/hyperceiler/module/app/SystemSettings.java
[ { "identifier": "BaseModule", "path": "app/src/main/java/com/sevtinge/hyperceiler/module/base/BaseModule.java", "snippet": "public abstract class BaseModule implements IXposedHook {\n\n public LoadPackageParam mLoadPackageParam = null;\n public final PrefsMap<String, Object> mPrefsMap = XposedInit...
import static com.sevtinge.hyperceiler.utils.devicesdk.SystemSDKKt.isAndroidVersion; import static com.sevtinge.hyperceiler.utils.devicesdk.SystemSDKKt.isMoreHyperOSVersion; import com.sevtinge.hyperceiler.module.base.BaseModule; import com.sevtinge.hyperceiler.module.hook.systemsettings.AddGoogleListHeader; import com.sevtinge.hyperceiler.module.hook.systemsettings.AddMiuiPlusEntry; import com.sevtinge.hyperceiler.module.hook.systemsettings.AllowManageAllNotifications; import com.sevtinge.hyperceiler.module.hook.systemsettings.AppsFreezerEnable; import com.sevtinge.hyperceiler.module.hook.systemsettings.EnableFoldArea; import com.sevtinge.hyperceiler.module.hook.systemsettings.EnablePadArea; import com.sevtinge.hyperceiler.module.hook.systemsettings.EnableSpeedMode; import com.sevtinge.hyperceiler.module.hook.systemsettings.HyperCeilerSettings; import com.sevtinge.hyperceiler.module.hook.systemsettings.InternationalBuild; import com.sevtinge.hyperceiler.module.hook.systemsettings.LinkTurbo; import com.sevtinge.hyperceiler.module.hook.systemsettings.ModifySystemVersion; import com.sevtinge.hyperceiler.module.hook.systemsettings.MoreNotificationSettings; import com.sevtinge.hyperceiler.module.hook.systemsettings.NewNFCPage; import com.sevtinge.hyperceiler.module.hook.systemsettings.NoveltyHaptic; import com.sevtinge.hyperceiler.module.hook.systemsettings.QuickManageOverlayPermission; import com.sevtinge.hyperceiler.module.hook.systemsettings.QuickManageUnknownAppSources; import com.sevtinge.hyperceiler.module.hook.systemsettings.UnLockAreaScreenshot; import com.sevtinge.hyperceiler.module.hook.systemsettings.UnlockNeverSleepScreen; import com.sevtinge.hyperceiler.module.hook.systemsettings.UnlockTaplusForSettings; import com.sevtinge.hyperceiler.module.hook.systemsettings.UsbModeChoose; import com.sevtinge.hyperceiler.module.hook.systemsettings.ViewWifiPasswordHook; import com.sevtinge.hyperceiler.module.hook.systemsettings.VoipAssistantController; import com.sevtinge.hyperceiler.module.hook.systemsettings.VolumeSeparateControlForSettings; import com.sevtinge.hyperceiler.module.hook.systemsettings.aiimage.UnlockAi; import com.sevtinge.hyperceiler.module.hook.systemsettings.aiimage.UnlockMemc; import com.sevtinge.hyperceiler.module.hook.systemsettings.aiimage.UnlockSuperResolution;
9,515
package com.sevtinge.hyperceiler.module.app; public class SystemSettings extends BaseModule { @Override public void handleLoadPackage() { initHook(new HyperCeilerSettings(), mPrefsMap.getStringAsInt("settings_icon", 0) != 0);
package com.sevtinge.hyperceiler.module.app; public class SystemSettings extends BaseModule { @Override public void handleLoadPackage() { initHook(new HyperCeilerSettings(), mPrefsMap.getStringAsInt("settings_icon", 0) != 0);
initHook(new LinkTurbo(), mPrefsMap.getBoolean("system_settings_linkturbo"));
8
2023-10-27 17:17:42+00:00
12k
thebatmanfuture/fofa_search
src/main/java/org/fofaviewer/controls/MyTableView.java
[ { "identifier": "TableBean", "path": "src/main/java/org/fofaviewer/bean/TableBean.java", "snippet": "public class TableBean extends BaseBean{\n public SimpleIntegerProperty num = new SimpleIntegerProperty();\n public SimpleStringProperty host = new SimpleStringProperty();\n public SimpleStringP...
import javafx.beans.binding.Bindings; import javafx.collections.ObservableList; import javafx.scene.control.*; import javafx.scene.control.MenuItem; import javafx.scene.input.Clipboard; import javafx.scene.input.ClipboardContent; import org.fofaviewer.bean.TableBean; import org.fofaviewer.callback.MainControllerCallback; import org.fofaviewer.utils.DataUtil; import org.fofaviewer.utils.RequestUtil; import org.fofaviewer.utils.ResourceBundleUtil; import org.tinylog.Logger; import java.awt.*; import java.io.IOException; import java.net.URI; import java.util.*;
8,146
package org.fofaviewer.controls; /** * TableView装饰类 */ public class MyTableView { private final ResourceBundle resourceBundle = ResourceBundleUtil.getResource(); private final RequestUtil helper = RequestUtil.getInstance();
package org.fofaviewer.controls; /** * TableView装饰类 */ public class MyTableView { private final ResourceBundle resourceBundle = ResourceBundleUtil.getResource(); private final RequestUtil helper = RequestUtil.getInstance();
public MyTableView(TableView<TableBean> view, MainControllerCallback mainControllerCallback) {
1
2023-10-25 11:13:47+00:00
12k
amithkoujalgi/ollama4j
src/test/java/io/github/amithkoujalgi/ollama4j/integrationtests/TestRealAPIs.java
[ { "identifier": "OllamaAPI", "path": "src/main/java/io/github/amithkoujalgi/ollama4j/core/OllamaAPI.java", "snippet": "@SuppressWarnings(\"DuplicatedCode\")\npublic class OllamaAPI {\n\n private static final Logger logger = LoggerFactory.getLogger(OllamaAPI.class);\n private final String host;\n priv...
import static org.junit.jupiter.api.Assertions.*; import io.github.amithkoujalgi.ollama4j.core.OllamaAPI; import io.github.amithkoujalgi.ollama4j.core.exceptions.OllamaBaseException; import io.github.amithkoujalgi.ollama4j.core.models.OllamaResult; import io.github.amithkoujalgi.ollama4j.core.types.OllamaModelType; import io.github.amithkoujalgi.ollama4j.core.utils.OptionsBuilder; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.ConnectException; import java.net.URISyntaxException; import java.net.http.HttpConnectTimeoutException; import java.util.List; import java.util.Objects; import java.util.Properties; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test;
8,723
package io.github.amithkoujalgi.ollama4j.integrationtests; class TestRealAPIs { OllamaAPI ollamaAPI; private Properties loadProperties() { Properties properties = new Properties(); try (InputStream input = getClass().getClassLoader().getResourceAsStream("test-config.properties")) { if (input == null) { throw new RuntimeException("Sorry, unable to find test-config.properties"); } properties.load(input); return properties; } catch (IOException e) { throw new RuntimeException("Error loading properties", e); } } private File getImageFileFromClasspath(String fileName) { ClassLoader classLoader = getClass().getClassLoader(); return new File(Objects.requireNonNull(classLoader.getResource(fileName)).getFile()); } @BeforeEach void setUp() { Properties properties = loadProperties(); ollamaAPI = new OllamaAPI(properties.getProperty("ollama.api.url")); ollamaAPI.setRequestTimeoutSeconds(20); } @Test @Order(1) void testWrongEndpoint() { OllamaAPI ollamaAPI = new OllamaAPI("http://wrong-host:11434"); assertThrows(ConnectException.class, ollamaAPI::listModels); } @Test @Order(1) void testEndpointReachability() { try { assertNotNull(ollamaAPI.listModels()); } catch (HttpConnectTimeoutException e) { fail(e.getMessage()); } catch (Exception e) { throw new RuntimeException(e); } } @Test @Order(2) void testListModels() { testEndpointReachability(); try { assertNotNull(ollamaAPI.listModels()); ollamaAPI.listModels().forEach(System.out::println);
package io.github.amithkoujalgi.ollama4j.integrationtests; class TestRealAPIs { OllamaAPI ollamaAPI; private Properties loadProperties() { Properties properties = new Properties(); try (InputStream input = getClass().getClassLoader().getResourceAsStream("test-config.properties")) { if (input == null) { throw new RuntimeException("Sorry, unable to find test-config.properties"); } properties.load(input); return properties; } catch (IOException e) { throw new RuntimeException("Error loading properties", e); } } private File getImageFileFromClasspath(String fileName) { ClassLoader classLoader = getClass().getClassLoader(); return new File(Objects.requireNonNull(classLoader.getResource(fileName)).getFile()); } @BeforeEach void setUp() { Properties properties = loadProperties(); ollamaAPI = new OllamaAPI(properties.getProperty("ollama.api.url")); ollamaAPI.setRequestTimeoutSeconds(20); } @Test @Order(1) void testWrongEndpoint() { OllamaAPI ollamaAPI = new OllamaAPI("http://wrong-host:11434"); assertThrows(ConnectException.class, ollamaAPI::listModels); } @Test @Order(1) void testEndpointReachability() { try { assertNotNull(ollamaAPI.listModels()); } catch (HttpConnectTimeoutException e) { fail(e.getMessage()); } catch (Exception e) { throw new RuntimeException(e); } } @Test @Order(2) void testListModels() { testEndpointReachability(); try { assertNotNull(ollamaAPI.listModels()); ollamaAPI.listModels().forEach(System.out::println);
} catch (IOException | OllamaBaseException | InterruptedException | URISyntaxException e) {
1
2023-10-26 19:12:14+00:00
12k
Changbaiqi/yatori
yatori-console/src/main/java/com/cbq/yatori/console/run/Launch.java
[ { "identifier": "LoginResponseRequest", "path": "yatori-core/src/main/java/com/cbq/yatori/core/action/canghui/entity/loginresponse/LoginResponseRequest.java", "snippet": "@lombok.Data\npublic class LoginResponseRequest {\n @JsonProperty(\"code\")\n private long code;\n @JsonProperty(\"data\")\n...
import com.cbq.yatori.core.action.canghui.entity.loginresponse.LoginResponseRequest; import com.cbq.yatori.core.action.canghui.entity.mycourselistresponse.MyCourse; import com.cbq.yatori.core.action.canghui.entity.mycourselistresponse.MyCourseData; import com.cbq.yatori.core.action.enaea.entity.LoginAblesky; import com.cbq.yatori.core.action.enaea.entity.underwayproject.ResultList; import com.cbq.yatori.core.action.enaea.entity.underwayproject.UnderwayProjectRquest; import com.cbq.yatori.core.action.yinghua.CourseAction; import com.cbq.yatori.core.action.yinghua.CourseStudyAction; import com.cbq.yatori.core.action.yinghua.LoginAction; import com.cbq.yatori.core.action.yinghua.entity.allcourse.CourseInform; import com.cbq.yatori.core.action.yinghua.entity.allcourse.CourseRequest; import com.cbq.yatori.core.entity.*; import com.cbq.yatori.core.utils.ConfigUtils; import com.cbq.yatori.core.utils.FileUtils; import com.cbq.yatori.core.utils.VerificationCodeUtil; import lombok.extern.slf4j.Slf4j; import java.io.File; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask;
9,374
package com.cbq.yatori.console.run; /** * @author 长白崎 * @version 1.0 * @description: 加载启动程序 * @date 2023/10/31 8:45 */ @Slf4j public class Launch { private Config config; static { System.out.println(""" ___ \s ,---, ,--.'|_ ,--, \s /_ ./| | | :,' ,---. __ ,-.,--.'| \s ,---, | ' : : : ' : ' ,'\\ ,' ,'/ /|| |, \s /___/ \\. : | ,--.--. .;__,' / / / |' | |' |`--'_ \s . \\ \\ ,' ' / \\ | | | . ; ,. :| | ,',' ,'| \s \\ ; ` ,' .--. .-. |:__,'| : ' | |: :' : / ' | | \s \\ \\ ' \\__\\/: . . ' : |__' | .; :| | ' | | : \s ' \\ | ," .--.; | | | '.'| : |; : | ' : |__ \s \\ ; ; / / ,. | ; : ;\\ \\ / | , ; | | '.'|\s : \\ \\; : .' \\ | , / `----' ---' ; : ;\s \\ ' ;| , .-./ ---`-' | , / \s `--` `--`---' ---`-' \s Yatori v2.0.0-Beta.2 仅用于学习交流,请勿用于违法和商业用途!!! GitHub开源地址:https://github.com/Changbaiqi/brushlessons """); } /** * 初始化数据 */ public void init() { //加载配置文件 config = ConfigUtils.loadingConfig(); } public void toRun() { //获取账号列表----------------------------- List<User> users = config.getUsers(); //先进行登录---------------------------------------------- for (User user : users) { switch (user.getAccountType()) { //英华,创能 case YINGHUA -> { AccountCacheYingHua accountCacheYingHua = new AccountCacheYingHua(); user.setCache(accountCacheYingHua); //refresh_code:1代表密码错误, Map<String, Object> result = null; do { //获取SESSION String session = null; while ((session = LoginAction.getSESSION(user)) == null) ; accountCacheYingHua.setSession(session); //获取验证码 File code = null; while ((code = LoginAction.getCode(user)) == null) ;
package com.cbq.yatori.console.run; /** * @author 长白崎 * @version 1.0 * @description: 加载启动程序 * @date 2023/10/31 8:45 */ @Slf4j public class Launch { private Config config; static { System.out.println(""" ___ \s ,---, ,--.'|_ ,--, \s /_ ./| | | :,' ,---. __ ,-.,--.'| \s ,---, | ' : : : ' : ' ,'\\ ,' ,'/ /|| |, \s /___/ \\. : | ,--.--. .;__,' / / / |' | |' |`--'_ \s . \\ \\ ,' ' / \\ | | | . ; ,. :| | ,',' ,'| \s \\ ; ` ,' .--. .-. |:__,'| : ' | |: :' : / ' | | \s \\ \\ ' \\__\\/: . . ' : |__' | .; :| | ' | | : \s ' \\ | ," .--.; | | | '.'| : |; : | ' : |__ \s \\ ; ; / / ,. | ; : ;\\ \\ / | , ; | | '.'|\s : \\ \\; : .' \\ | , / `----' ---' ; : ;\s \\ ' ;| , .-./ ---`-' | , / \s `--` `--`---' ---`-' \s Yatori v2.0.0-Beta.2 仅用于学习交流,请勿用于违法和商业用途!!! GitHub开源地址:https://github.com/Changbaiqi/brushlessons """); } /** * 初始化数据 */ public void init() { //加载配置文件 config = ConfigUtils.loadingConfig(); } public void toRun() { //获取账号列表----------------------------- List<User> users = config.getUsers(); //先进行登录---------------------------------------------- for (User user : users) { switch (user.getAccountType()) { //英华,创能 case YINGHUA -> { AccountCacheYingHua accountCacheYingHua = new AccountCacheYingHua(); user.setCache(accountCacheYingHua); //refresh_code:1代表密码错误, Map<String, Object> result = null; do { //获取SESSION String session = null; while ((session = LoginAction.getSESSION(user)) == null) ; accountCacheYingHua.setSession(session); //获取验证码 File code = null; while ((code = LoginAction.getCode(user)) == null) ;
accountCacheYingHua.setCode(VerificationCodeUtil.aiDiscern(code));
13
2023-10-30 04:15:41+00:00
12k
sgware/sabre
src/edu/uky/cs/nil/sabre/Problem.java
[ { "identifier": "Expression", "path": "src/edu/uky/cs/nil/sabre/logic/Expression.java", "snippet": "public interface Expression extends Typed, Simplifiable {\n\t\n\t@Override\n\tpublic Expression apply(Function<Object, Object> function);\n\t\n\t@Override\n\tpublic default Expression simplify() {\n\t\tre...
import java.io.Serializable; import java.util.LinkedHashSet; import edu.uky.cs.nil.sabre.logic.Expression; import edu.uky.cs.nil.sabre.logic.HashSubstitution; import edu.uky.cs.nil.sabre.logic.Unknown; import edu.uky.cs.nil.sabre.logic.Value; import edu.uky.cs.nil.sabre.util.ImmutableSet;
7,233
package edu.uky.cs.nil.sabre; /** * Represents all the definitions needed to define a full planning task. * A problem defines: * <ul> * <li>a {@link #name name}</li> * <li>a list of {@link Type types} and {@link Entity entities} defined in a * {@link Universe universe}</li> * <li>a list of {@link Fluent fluents}</li> * <li>a list of {@link Event events}, as well as smaller lists of {@link * Action actions} and {@link Trigger triggers}</li> * <li>a {@link Expression logical expression} defining the initial state</li> * <li>an {@link #utility author utility}</li> * <li>a {@link #utilities character utility} for each character</li> * </ul> * Problem objects usually should not be constructed directly. They should be * defined using a {@link ProblemBuilder} to ensure correct formatting. * <p> * The fluents and events defined in a problem can be templates, meaning their * signatures contain {@link edu.uky.cs.nil.sabre.logic.Variable variables}. A * fluent or event template implicitly defines all possible {@link * Expression#isGround() ground} versions of that template. Every ground fluent * or event must have a unique {@link Signature signature}; A * {@link ProblemBuilder problem builder} enforces this by preventing two * templates from ambiguously defining two ground objects that would be * different but have the same signature. * * @author Stephen G. Ware */ public class Problem implements Serializable { /** Serial version ID */ private static final long serialVersionUID = Settings.VERSION_UID; /** The name of the problem */ public final String name; /** * The universe defining the problem's {@link Type types} and {@link Entity * entities} */ public final Universe universe; /** The {@link Fluent fluents} tracked in every state of the problem */ public final ImmutableSet<Fluent> fluents; /** A set of all {@link Event events} that can occur */ public final ImmutableSet<Event> events; /** * All the {@link Action actions} defined in this problem (a subset of * {@link #events events}) */ public final ImmutableSet<Action> actions; /** * All the {@link Trigger triggers} defined in this problem (a subset of * {@link #events events}) */ public final ImmutableSet<Trigger> triggers; /** * A {@link Expression logical expression} representing the initial state */ public final Expression initial; /** The author's utility {@link Expression expression} */ public final Expression utility; /** * A {@link Mapping mapping} which returns a utility {@link Expression * expression} for each {@link Character character} */ public final Mapping<Expression> utilities; /** The comment associated with this problem in its definition */ public final String comment; /** * Constructs a new problem. * * @param name the problem's name * @param universe the universe of types and entities used in this problem * @param fluents all fluents defined in this problem * @param actions all actions defined in this problem * @param triggers all triggers defined in this problem * @param initial an expression describing the initial state, which sets * values of all fluents * @param utility an expression that can be evaluated to determine how * satisfied the author is with a given state * @param utilities a mapping of expressions that can be evaluated to * determine how satisfied some character is with a given state * @param comment a text comment associated with the problem */ protected Problem( String name, Universe universe, ImmutableSet<Fluent> fluents, ImmutableSet<Action> actions, ImmutableSet<Trigger> triggers, Expression initial, Expression utility, Mapping<Expression> utilities, String comment ) { this.name = name; this.universe = universe; this.fluents = fluents; LinkedHashSet<Event> events = new LinkedHashSet<>(); for(Action action : actions) events.add(action); for(Trigger axiom : triggers) events.add(axiom); this.events = new ImmutableSet<>(events); this.actions = actions; this.triggers = triggers; this.initial = initial; this.utility = utility; this.utilities = utilities; this.comment = comment; } /** * Constructs a new problem using the definitions specified in a {@link * ProblemBuilder}. * * @param builder the problem builder */ public Problem(ProblemBuilder builder) { this( builder.getName(), builder.getUniverse(), builder.getFluents(), builder.getActions(), builder.getTriggers(), builder.getInitialState(), builder.getUtility(), builder.getUtilities(), builder.getComment() ); } @Override public String toString() { return "[Problem \"" + name + "\": " + fluents.size() + " fluents; " + actions.size() + " actions; " + triggers.size() + " triggers; " + (1 + universe.characters.size()) + " utilities]"; } /** * Returns a fluent defined in this problem based on the given signature. * The signature does not need to match a fluent explicitly defined in this * problem; it can match a fluent implicitly defined by a template. * Any types and entities in the signature will be replaced with types and * entities of the same name in this problem's universe, if they exist. * * @param signature the signature of the fluent to find * @return the defined fluent * @throws FormatException if no fluent matching this signature is defined */ public Fluent getFluent(Signature signature) { return find("Fluent", signature, fluents); } /** * Returns an event defined in this problem based on the given signature. * The signature does not need to match an event explicitly defined in this * problem; it can match an event implicitly defined by a template. * Any types and entities in the signature will be replaced with types and * entities of the same name in this problem's universe, if they exist. * * @param signature the signature of the event to find * @return the defined event * @throws FormatException if no event matching this signature is defined */ public Event getEvent(Signature signature) { return find("Event", signature, events); } /** * Returns an action defined in this problem based on the given signature. * The signature does not need to match an action explicitly defined in this * problem; it can match an action implicitly defined by a template. * Any types and entities in the signature will be replaced with types and * entities of the same name in this problem's universe, if they exist. * * @param signature the signature of the action to find * @return the defined action * @throws FormatException if no action matching this signature is defined */ public Action getAction(Signature signature) { return find("Action", signature, actions); } /** * Returns a trigger defined in this problem based on the given signature. * The signature does not need to match a trigger explicitly defined in * this problem; it can match an action implicitly defined by a template. * Any types and entities in the signature will be replaced with types and * entities of the same name in this problem's universe, if they exist. * * @param signature the signature of the trigger to find * @return the defined trigger * @throws FormatException if no trigger matching this signature is defined */ public Trigger getTrigger(Signature signature) { return find("Trigger", signature, triggers); } @SuppressWarnings("unchecked") private final <S extends Signed> S find(String type, Signature signature, ImmutableSet<S> defined) { signature = (Signature) signature.substitute(universe); for(S existing : defined) { if(existing.getSignature().covers(signature)) { existing = (S) existing.distinguish(signature); return (S) existing.substitute(new HashSubstitution(existing.getSignature().arguments, signature.arguments)); } } throw Exceptions.notDefined(type, signature.toString()); } /** * Returns the value of the {@link #utility author utility expression} in a * given state. * * @param state the state in which to evaluate the author's utility * @return the author's utility in that state */ public Value getUtility(State state) { return getUtility(utility, state); } /** * Returns the value of a {@link Character character's} {@link #utilities * utility expression} in a given state. * * @param character the character whose utility is desired * @param state the state in which to evaluate the character's utility * @return the character's utility in that state */ public Value getUtility(Character character, State state) { if(character == null) return getUtility(state); else return getUtility(utilities.get(character), state); } private static final Number getUtility(Expression expression, State state) { Value value = expression.evaluate(state);
package edu.uky.cs.nil.sabre; /** * Represents all the definitions needed to define a full planning task. * A problem defines: * <ul> * <li>a {@link #name name}</li> * <li>a list of {@link Type types} and {@link Entity entities} defined in a * {@link Universe universe}</li> * <li>a list of {@link Fluent fluents}</li> * <li>a list of {@link Event events}, as well as smaller lists of {@link * Action actions} and {@link Trigger triggers}</li> * <li>a {@link Expression logical expression} defining the initial state</li> * <li>an {@link #utility author utility}</li> * <li>a {@link #utilities character utility} for each character</li> * </ul> * Problem objects usually should not be constructed directly. They should be * defined using a {@link ProblemBuilder} to ensure correct formatting. * <p> * The fluents and events defined in a problem can be templates, meaning their * signatures contain {@link edu.uky.cs.nil.sabre.logic.Variable variables}. A * fluent or event template implicitly defines all possible {@link * Expression#isGround() ground} versions of that template. Every ground fluent * or event must have a unique {@link Signature signature}; A * {@link ProblemBuilder problem builder} enforces this by preventing two * templates from ambiguously defining two ground objects that would be * different but have the same signature. * * @author Stephen G. Ware */ public class Problem implements Serializable { /** Serial version ID */ private static final long serialVersionUID = Settings.VERSION_UID; /** The name of the problem */ public final String name; /** * The universe defining the problem's {@link Type types} and {@link Entity * entities} */ public final Universe universe; /** The {@link Fluent fluents} tracked in every state of the problem */ public final ImmutableSet<Fluent> fluents; /** A set of all {@link Event events} that can occur */ public final ImmutableSet<Event> events; /** * All the {@link Action actions} defined in this problem (a subset of * {@link #events events}) */ public final ImmutableSet<Action> actions; /** * All the {@link Trigger triggers} defined in this problem (a subset of * {@link #events events}) */ public final ImmutableSet<Trigger> triggers; /** * A {@link Expression logical expression} representing the initial state */ public final Expression initial; /** The author's utility {@link Expression expression} */ public final Expression utility; /** * A {@link Mapping mapping} which returns a utility {@link Expression * expression} for each {@link Character character} */ public final Mapping<Expression> utilities; /** The comment associated with this problem in its definition */ public final String comment; /** * Constructs a new problem. * * @param name the problem's name * @param universe the universe of types and entities used in this problem * @param fluents all fluents defined in this problem * @param actions all actions defined in this problem * @param triggers all triggers defined in this problem * @param initial an expression describing the initial state, which sets * values of all fluents * @param utility an expression that can be evaluated to determine how * satisfied the author is with a given state * @param utilities a mapping of expressions that can be evaluated to * determine how satisfied some character is with a given state * @param comment a text comment associated with the problem */ protected Problem( String name, Universe universe, ImmutableSet<Fluent> fluents, ImmutableSet<Action> actions, ImmutableSet<Trigger> triggers, Expression initial, Expression utility, Mapping<Expression> utilities, String comment ) { this.name = name; this.universe = universe; this.fluents = fluents; LinkedHashSet<Event> events = new LinkedHashSet<>(); for(Action action : actions) events.add(action); for(Trigger axiom : triggers) events.add(axiom); this.events = new ImmutableSet<>(events); this.actions = actions; this.triggers = triggers; this.initial = initial; this.utility = utility; this.utilities = utilities; this.comment = comment; } /** * Constructs a new problem using the definitions specified in a {@link * ProblemBuilder}. * * @param builder the problem builder */ public Problem(ProblemBuilder builder) { this( builder.getName(), builder.getUniverse(), builder.getFluents(), builder.getActions(), builder.getTriggers(), builder.getInitialState(), builder.getUtility(), builder.getUtilities(), builder.getComment() ); } @Override public String toString() { return "[Problem \"" + name + "\": " + fluents.size() + " fluents; " + actions.size() + " actions; " + triggers.size() + " triggers; " + (1 + universe.characters.size()) + " utilities]"; } /** * Returns a fluent defined in this problem based on the given signature. * The signature does not need to match a fluent explicitly defined in this * problem; it can match a fluent implicitly defined by a template. * Any types and entities in the signature will be replaced with types and * entities of the same name in this problem's universe, if they exist. * * @param signature the signature of the fluent to find * @return the defined fluent * @throws FormatException if no fluent matching this signature is defined */ public Fluent getFluent(Signature signature) { return find("Fluent", signature, fluents); } /** * Returns an event defined in this problem based on the given signature. * The signature does not need to match an event explicitly defined in this * problem; it can match an event implicitly defined by a template. * Any types and entities in the signature will be replaced with types and * entities of the same name in this problem's universe, if they exist. * * @param signature the signature of the event to find * @return the defined event * @throws FormatException if no event matching this signature is defined */ public Event getEvent(Signature signature) { return find("Event", signature, events); } /** * Returns an action defined in this problem based on the given signature. * The signature does not need to match an action explicitly defined in this * problem; it can match an action implicitly defined by a template. * Any types and entities in the signature will be replaced with types and * entities of the same name in this problem's universe, if they exist. * * @param signature the signature of the action to find * @return the defined action * @throws FormatException if no action matching this signature is defined */ public Action getAction(Signature signature) { return find("Action", signature, actions); } /** * Returns a trigger defined in this problem based on the given signature. * The signature does not need to match a trigger explicitly defined in * this problem; it can match an action implicitly defined by a template. * Any types and entities in the signature will be replaced with types and * entities of the same name in this problem's universe, if they exist. * * @param signature the signature of the trigger to find * @return the defined trigger * @throws FormatException if no trigger matching this signature is defined */ public Trigger getTrigger(Signature signature) { return find("Trigger", signature, triggers); } @SuppressWarnings("unchecked") private final <S extends Signed> S find(String type, Signature signature, ImmutableSet<S> defined) { signature = (Signature) signature.substitute(universe); for(S existing : defined) { if(existing.getSignature().covers(signature)) { existing = (S) existing.distinguish(signature); return (S) existing.substitute(new HashSubstitution(existing.getSignature().arguments, signature.arguments)); } } throw Exceptions.notDefined(type, signature.toString()); } /** * Returns the value of the {@link #utility author utility expression} in a * given state. * * @param state the state in which to evaluate the author's utility * @return the author's utility in that state */ public Value getUtility(State state) { return getUtility(utility, state); } /** * Returns the value of a {@link Character character's} {@link #utilities * utility expression} in a given state. * * @param character the character whose utility is desired * @param state the state in which to evaluate the character's utility * @return the character's utility in that state */ public Value getUtility(Character character, State state) { if(character == null) return getUtility(state); else return getUtility(utilities.get(character), state); } private static final Number getUtility(Expression expression, State state) { Value value = expression.evaluate(state);
if(value.equals(Unknown.UNKNOWN))
2
2023-10-26 18:14:19+00:00
12k
sngular/pact-annotation-processor
src/main/java/com/sngular/annotation/processor/PactDslProcessor.java
[ { "identifier": "PactProcessorException", "path": "src/main/java/com/sngular/annotation/processor/exception/PactProcessorException.java", "snippet": "public class PactProcessorException extends RuntimeException {\n\n private static final String ERROR_MESSAGE = \"Error processing element %s\";\n\n publ...
import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Random; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.SourceVersion; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Name; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import com.google.auto.service.AutoService; import com.google.common.collect.ImmutableMap; import com.sngular.annotation.pact.DslExclude; import com.sngular.annotation.pact.Example; import com.sngular.annotation.pact.PactDslBodyBuilder; import com.sngular.annotation.processor.exception.PactProcessorException; import com.sngular.annotation.processor.exception.TemplateFactoryException; import com.sngular.annotation.processor.exception.TemplateGenerationException; import com.sngular.annotation.processor.mapping.BigDecimalMapping; import com.sngular.annotation.processor.mapping.BigIntegerMapping; import com.sngular.annotation.processor.mapping.BooleanMapping; import com.sngular.annotation.processor.mapping.ByteMapping; import com.sngular.annotation.processor.mapping.CharMapping; import com.sngular.annotation.processor.mapping.DateMapping; import com.sngular.annotation.processor.mapping.DoubleMapping; import com.sngular.annotation.processor.mapping.FloatMapping; import com.sngular.annotation.processor.mapping.IntegerMapping; import com.sngular.annotation.processor.mapping.LongMapping; import com.sngular.annotation.processor.mapping.ShortMapping; import com.sngular.annotation.processor.mapping.StringMapping; import com.sngular.annotation.processor.mapping.TypeMapping; import com.sngular.annotation.processor.mapping.ZonedDateTimeMapping; import com.sngular.annotation.processor.model.ClassBuilderTemplate; import com.sngular.annotation.processor.model.DslComplexField; import com.sngular.annotation.processor.model.DslComplexTypeEnum; import com.sngular.annotation.processor.model.DslField; import com.sngular.annotation.processor.model.DslSimpleField; import com.sngular.annotation.processor.model.FieldValidations; import com.sngular.annotation.processor.template.ClasspathTemplateLoader; import com.sngular.annotation.processor.template.TemplateFactory; import freemarker.template.TemplateException; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.IterableUtils; import org.apache.commons.collections4.IteratorUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.apache.commons.rng.RestorableUniformRandomProvider; import org.apache.commons.rng.simple.RandomSource; import org.jetbrains.annotations.NotNull;
7,416
IteratorUtils .transformedIterator(elementsAnnotatedWith.iterator(), this::composeBuilderTemplate).forEachRemaining(builderTemplate -> { try { final var builderFile = processingEnv.getFiler().createSourceFile(builderTemplate.completePath()); templateFactory.writeTemplateToFile(ClasspathTemplateLoader.TEMPLATE_DSL_BUILDER, builderTemplate, builderFile.openWriter()); } catch (IOException | TemplateException e) { throw new TemplateGenerationException("PactDslBodyBuilder", e); } }); return true; } private ClassBuilderTemplate composeBuilderTemplate(final Element element) { final List<? extends Element> fieldElements = getFieldElements(element); final var qualifiedName = ((TypeElement) element).getQualifiedName().toString(); String packageName = null; final int lastDot = qualifiedName.lastIndexOf('.'); if (lastDot > 0) { packageName = qualifiedName.substring(0, lastDot); } final var builderSimpleClassName = qualifiedName.substring(lastDot + 1); final var builderClassName = builderSimpleClassName + "Builder"; return ClassBuilderTemplate.builder() .fileName(builderClassName) .className(builderSimpleClassName) .modelPackage(packageName) .fieldList(getFields(fieldElements)) .customModifiers(extractCustomModifiers(element)) .build(); } @NotNull private List<DslField> getFields(final List<? extends Element> fieldElements) { return IterableUtils.toList(IterableUtils.transformedIterable(fieldElements, fieldElement -> composeDslField(fieldElement, false))); } private List<String> getAnnotationValueAsType(final AnnotationMirror annotationMirror, final String key) { final var valueAsTypeList = new ArrayList<String>(); final var annotationValue = getAnnotationValue(annotationMirror, key); if (annotationValue != null) { valueAsTypeList.addAll(List.of(annotationValue.toString() .replace(" ", "").replace("{", "") .replace("}", "").replace("\"", "") .split(","))); } return valueAsTypeList; } private AnnotationValue getAnnotationValue(final AnnotationMirror annotationMirror, final String key) { AnnotationValue annotationValue = null; for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotationMirror.getElementValues().entrySet()) { if (entry.getKey().getSimpleName().toString().equals(key)) { annotationValue = entry.getValue(); } } return annotationValue; } private DslField composeDslField(final Element fieldElement, final boolean insideCollection) { final DslField result; final Optional<TypeMapping<?>> mappingOp = extractMappingByType(fieldElement); if (mappingOp.isEmpty()) { if (checkIfOwn(fieldElement)) { result = composeDslComplexField(fieldElement); } else { final String type = extractType(fieldElement); if (type.endsWith("List") || type.endsWith("Map") || type.endsWith("Set") || type.endsWith("Collection")) { result = composeCollection(fieldElement); } else { result = composeDslComplexField(fieldElement); } } } else { result = composeDslSimpleField(fieldElement, mappingOp.get(), insideCollection); } return result; } private DslComplexField composeDslComplexField(final Element element) { return DslComplexField.builder() .name(element.getSimpleName().toString()) .fieldType(element.asType().toString()) .needBuilder(checkIfOwn(element)) .complexType(DslComplexTypeEnum.OBJECT) .fieldValidations(extractValidations(element)) .empty(Objects.nonNull(element.getAnnotation(DslExclude.class))) .build(); } private DslComplexField composeCollection(final Element element) { final var typeStr = cleanType(element); return DslComplexField.builder() .name(element.getSimpleName().toString()) .fieldType(typeStr) .fields(extractTypes(element)) .fieldValidations(extractValidations(element)) .complexType(DslComplexTypeEnum.COLLECTION) .empty(Objects.nonNull(element.getAnnotation(DslExclude.class))) .build(); } private boolean checkIfOwn(final Element element) { final var typePackage = elementUtils.getPackageOf(typeUtils.asElement(element.asType())).toString(); final var parentType = elementUtils.getPackageOf(typeUtils.asElement(element.getEnclosingElement().asType())).toString(); return parentType.equalsIgnoreCase(typePackage); } private String extractType(final Element element) { return ((TypeElement) typeUtils.asElement(element.asType())).getQualifiedName().toString(); } private String cleanType(final Element element) { var finalType = element.asType().toString(); for (var annotation : element.asType().getAnnotationMirrors()) { finalType = finalType.replace(annotation.toString(), ""); } return finalType.replace(", ", ""); }
/* * 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 com.sngular.annotation.processor; @Slf4j @AutoService(Processor.class) @SupportedAnnotationTypes("com.sngular.annotation.pact.PactDslBodyBuilder") public class PactDslProcessor extends AbstractProcessor { static final Map<String, TypeMapping<?>> TYPE_MAPPING = ImmutableMap.<String, TypeMapping<?>>builder() .put("int", new IntegerMapping()) .put("Integer", new IntegerMapping()) .put("BigInteger", new BigIntegerMapping()) .put("short", new ShortMapping()) .put("Short", new ShortMapping()) .put("byte", new ByteMapping()) .put("Byte", new ByteMapping()) .put("long", new LongMapping()) .put("Long", new LongMapping()) .put("char", new CharMapping()) .put("Character", new CharMapping()) .put("String", new StringMapping()) .put("float", new FloatMapping()) .put("Float", new FloatMapping()) .put("double", new DoubleMapping()) .put("Double", new DoubleMapping()) .put("BigDecimal", new BigDecimalMapping()) .put("boolean", new BooleanMapping()) .put("Boolean", new BooleanMapping()) .put("date", new DateMapping()) .put("java.time.ZonedDateTime", new ZonedDateTimeMapping()) .put("ZonedDateTime", new ZonedDateTimeMapping()) .put("java.util.Date", new DateMapping()) .put("Date", new DateMapping()) .build(); private static final String CUSTOM_MODIFIERS = "customModifiers"; private Elements elementUtils; private Types typeUtils; private RestorableUniformRandomProvider randomSource = RandomSource.XO_RO_SHI_RO_128_PP.create(); public PactDslProcessor() { } public PactDslProcessor(final RestorableUniformRandomProvider randomSource) { this.randomSource = randomSource; } @NotNull private static List<? extends Element> getFieldElements(final Element element) { return IterableUtils.toList(IterableUtils.filteredIterable(element.getEnclosedElements(), elt -> elt.getKind().isField())); } private static String getFormat(final Element fieldElement, final String defaultFormat) { final String value = fieldElement.getAnnotation(Example.class).format(); return StringUtils.defaultIfEmpty(value, defaultFormat); } @Override public final SourceVersion getSupportedSourceVersion() { return SourceVersion.latestSupported(); } @Override public final boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) { final TemplateFactory templateFactory; try { templateFactory = new TemplateFactory(); } catch (final TemplateException e) { throw new TemplateFactoryException(e); } elementUtils = processingEnv.getElementUtils(); typeUtils = processingEnv.getTypeUtils(); final Set<? extends Element> elementsAnnotatedWith = roundEnv.getElementsAnnotatedWith(PactDslBodyBuilder.class); IteratorUtils .transformedIterator(elementsAnnotatedWith.iterator(), this::composeBuilderTemplate).forEachRemaining(builderTemplate -> { try { final var builderFile = processingEnv.getFiler().createSourceFile(builderTemplate.completePath()); templateFactory.writeTemplateToFile(ClasspathTemplateLoader.TEMPLATE_DSL_BUILDER, builderTemplate, builderFile.openWriter()); } catch (IOException | TemplateException e) { throw new TemplateGenerationException("PactDslBodyBuilder", e); } }); return true; } private ClassBuilderTemplate composeBuilderTemplate(final Element element) { final List<? extends Element> fieldElements = getFieldElements(element); final var qualifiedName = ((TypeElement) element).getQualifiedName().toString(); String packageName = null; final int lastDot = qualifiedName.lastIndexOf('.'); if (lastDot > 0) { packageName = qualifiedName.substring(0, lastDot); } final var builderSimpleClassName = qualifiedName.substring(lastDot + 1); final var builderClassName = builderSimpleClassName + "Builder"; return ClassBuilderTemplate.builder() .fileName(builderClassName) .className(builderSimpleClassName) .modelPackage(packageName) .fieldList(getFields(fieldElements)) .customModifiers(extractCustomModifiers(element)) .build(); } @NotNull private List<DslField> getFields(final List<? extends Element> fieldElements) { return IterableUtils.toList(IterableUtils.transformedIterable(fieldElements, fieldElement -> composeDslField(fieldElement, false))); } private List<String> getAnnotationValueAsType(final AnnotationMirror annotationMirror, final String key) { final var valueAsTypeList = new ArrayList<String>(); final var annotationValue = getAnnotationValue(annotationMirror, key); if (annotationValue != null) { valueAsTypeList.addAll(List.of(annotationValue.toString() .replace(" ", "").replace("{", "") .replace("}", "").replace("\"", "") .split(","))); } return valueAsTypeList; } private AnnotationValue getAnnotationValue(final AnnotationMirror annotationMirror, final String key) { AnnotationValue annotationValue = null; for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotationMirror.getElementValues().entrySet()) { if (entry.getKey().getSimpleName().toString().equals(key)) { annotationValue = entry.getValue(); } } return annotationValue; } private DslField composeDslField(final Element fieldElement, final boolean insideCollection) { final DslField result; final Optional<TypeMapping<?>> mappingOp = extractMappingByType(fieldElement); if (mappingOp.isEmpty()) { if (checkIfOwn(fieldElement)) { result = composeDslComplexField(fieldElement); } else { final String type = extractType(fieldElement); if (type.endsWith("List") || type.endsWith("Map") || type.endsWith("Set") || type.endsWith("Collection")) { result = composeCollection(fieldElement); } else { result = composeDslComplexField(fieldElement); } } } else { result = composeDslSimpleField(fieldElement, mappingOp.get(), insideCollection); } return result; } private DslComplexField composeDslComplexField(final Element element) { return DslComplexField.builder() .name(element.getSimpleName().toString()) .fieldType(element.asType().toString()) .needBuilder(checkIfOwn(element)) .complexType(DslComplexTypeEnum.OBJECT) .fieldValidations(extractValidations(element)) .empty(Objects.nonNull(element.getAnnotation(DslExclude.class))) .build(); } private DslComplexField composeCollection(final Element element) { final var typeStr = cleanType(element); return DslComplexField.builder() .name(element.getSimpleName().toString()) .fieldType(typeStr) .fields(extractTypes(element)) .fieldValidations(extractValidations(element)) .complexType(DslComplexTypeEnum.COLLECTION) .empty(Objects.nonNull(element.getAnnotation(DslExclude.class))) .build(); } private boolean checkIfOwn(final Element element) { final var typePackage = elementUtils.getPackageOf(typeUtils.asElement(element.asType())).toString(); final var parentType = elementUtils.getPackageOf(typeUtils.asElement(element.getEnclosingElement().asType())).toString(); return parentType.equalsIgnoreCase(typePackage); } private String extractType(final Element element) { return ((TypeElement) typeUtils.asElement(element.asType())).getQualifiedName().toString(); } private String cleanType(final Element element) { var finalType = element.asType().toString(); for (var annotation : element.asType().getAnnotationMirrors()) { finalType = finalType.replace(annotation.toString(), ""); } return finalType.replace(", ", ""); }
private FieldValidations extractValidations(final Element element) {
22
2023-10-25 14:36:38+00:00
12k
granny/Pl3xMap
core/src/main/java/net/pl3x/map/core/registry/RendererRegistry.java
[ { "identifier": "BasicRenderer", "path": "core/src/main/java/net/pl3x/map/core/renderer/BasicRenderer.java", "snippet": "public final class BasicRenderer extends Renderer {\n public BasicRenderer(@NotNull RegionScanTask task, @NotNull Builder builder) {\n super(task, builder);\n }\n\n @O...
import net.pl3x.map.core.renderer.Renderer; import net.pl3x.map.core.renderer.VanillaRenderer; import net.pl3x.map.core.renderer.VintageStoryRenderer; import net.pl3x.map.core.renderer.task.RegionScanTask; import org.jetbrains.annotations.NotNull; import java.lang.reflect.InvocationTargetException; import net.pl3x.map.core.renderer.BasicRenderer; import net.pl3x.map.core.renderer.BiomeRenderer; import net.pl3x.map.core.renderer.BlockInfoRenderer; import net.pl3x.map.core.renderer.FlowerMapRenderer; import net.pl3x.map.core.renderer.InhabitedRenderer; import net.pl3x.map.core.renderer.NightRenderer;
9,274
/* * MIT License * * Copyright (c) 2020-2023 William Blake Galbreath * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.pl3x.map.core.registry; public class RendererRegistry extends Registry<Renderer.@NotNull Builder> { public static final String BASIC = "basic"; public static final String BIOMES = "biomes"; public static final String BLOCKINFO = "blockinfo"; public static final String FLOWERMAP = "flowermap"; public static final String INHABITED = "inhabited"; public static final String NIGHT = "night"; public static final String VANILLA = "vanilla"; public static final String VINTAGE_STORY = "vintage_story"; public void register() { register(BASIC, new Renderer.Builder(BASIC, "Basic", BasicRenderer.class)); register(BIOMES, new Renderer.Builder(BIOMES, "Biomes", BiomeRenderer.class)); register(BLOCKINFO, new Renderer.Builder(BLOCKINFO, "BlockInfo", BlockInfoRenderer.class)); register(FLOWERMAP, new Renderer.Builder(FLOWERMAP, "FlowerMap", FlowerMapRenderer.class)); register(INHABITED, new Renderer.Builder(INHABITED, "Inhabited", InhabitedRenderer.class)); register(NIGHT, new Renderer.Builder(NIGHT, "Night", NightRenderer.class)); register(VANILLA, new Renderer.Builder(VANILLA, "Vanilla", VanillaRenderer.class));
/* * MIT License * * Copyright (c) 2020-2023 William Blake Galbreath * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.pl3x.map.core.registry; public class RendererRegistry extends Registry<Renderer.@NotNull Builder> { public static final String BASIC = "basic"; public static final String BIOMES = "biomes"; public static final String BLOCKINFO = "blockinfo"; public static final String FLOWERMAP = "flowermap"; public static final String INHABITED = "inhabited"; public static final String NIGHT = "night"; public static final String VANILLA = "vanilla"; public static final String VINTAGE_STORY = "vintage_story"; public void register() { register(BASIC, new Renderer.Builder(BASIC, "Basic", BasicRenderer.class)); register(BIOMES, new Renderer.Builder(BIOMES, "Biomes", BiomeRenderer.class)); register(BLOCKINFO, new Renderer.Builder(BLOCKINFO, "BlockInfo", BlockInfoRenderer.class)); register(FLOWERMAP, new Renderer.Builder(FLOWERMAP, "FlowerMap", FlowerMapRenderer.class)); register(INHABITED, new Renderer.Builder(INHABITED, "Inhabited", InhabitedRenderer.class)); register(NIGHT, new Renderer.Builder(NIGHT, "Night", NightRenderer.class)); register(VANILLA, new Renderer.Builder(VANILLA, "Vanilla", VanillaRenderer.class));
register(VINTAGE_STORY, new Renderer.Builder(VINTAGE_STORY, "VintageStory", VintageStoryRenderer.class));
8
2023-10-26 01:14:31+00:00
12k
jd-opensource/sql-analysis
sql-analysis/src/main/java/com/jd/sql/analysis/core/SqlAnalysisAspect.java
[ { "identifier": "SqlAnalysis", "path": "sql-analysis/src/main/java/com/jd/sql/analysis/analysis/SqlAnalysis.java", "snippet": "public class SqlAnalysis {\n\n private static Logger logger = LoggerFactory.getLogger(SqlAnalysis.class);\n\n /**\n * mysql 版本标识\n */\n private static String my...
import com.jd.sql.analysis.analysis.SqlAnalysis; import com.jd.sql.analysis.analysis.SqlAnalysisResultList; import com.jd.sql.analysis.config.JmqConfig; import com.jd.sql.analysis.config.SqlAnalysisConfig; import com.jd.sql.analysis.extract.SqlExtract; import com.jd.sql.analysis.extract.SqlExtractResult; import com.jd.sql.analysis.out.OutModelEnum; import com.jd.sql.analysis.out.SqlScoreResultOutMq; import com.jd.sql.analysis.out.SqlScoreResultOutService; import com.jd.sql.analysis.out.SqlScoreResultOutServiceDefault; import com.jd.sql.analysis.replace.SqlReplace; import com.jd.sql.analysis.replace.SqlReplaceConfig; import com.jd.sql.analysis.rule.SqlScoreRuleLoader; import com.jd.sql.analysis.rule.SqlScoreRuleLoaderRulesEngine; import com.jd.sql.analysis.score.SqlScoreResult; import com.jd.sql.analysis.score.SqlScoreService; import com.jd.sql.analysis.score.SqlScoreServiceRulesEngine; import com.jd.sql.analysis.util.GsonUtil; import org.apache.commons.lang3.StringUtils; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.executor.statement.StatementHandler; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.plugin.*; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.Connection; import java.util.Properties;
9,708
package com.jd.sql.analysis.core; /** * @Author huhaitao21 * @Description sql分析切面类 * @Date 22:47 2022/10/25 **/ @Intercepts({@Signature( type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class} ), @Signature( type = Executor.class, method = "update", args = {MappedStatement.class, Object.class} ),@Signature( type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class} )}) public class SqlAnalysisAspect implements Interceptor { Logger logger = LoggerFactory.getLogger(SqlAnalysisAspect.class); /** * 评分规则服务 */ private static SqlScoreService sqlScoreService = new SqlScoreServiceRulesEngine(); /** * 评分结果输出服务 */ private static SqlScoreResultOutService sqlScoreResultOut = new SqlScoreResultOutServiceDefault(); @Override public Object intercept(Invocation invocation) throws Throwable { try { Object firstArg = invocation.getArgs()[0]; if(SqlAnalysisConfig.getSqlReplaceModelSwitch()!=null && SqlAnalysisConfig.getSqlReplaceModelSwitch() && firstArg instanceof MappedStatement){ //sql替换模块 MappedStatement mappedStatement = (MappedStatement)firstArg; String replaceSql = SqlReplaceConfig.getReplaceSqlBySqlId(mappedStatement.getId()); if(StringUtils.isNotBlank(replaceSql)){ SqlReplace.replace(invocation,replaceSql); } }else if(SqlAnalysisConfig.getAnalysisSwitch() && firstArg instanceof Connection){ //sql 分析模块 //获取入参statement StatementHandler statementHandler = (StatementHandler)invocation.getTarget(); //提取待执行的完整sql语句 SqlExtractResult sqlExtractResult = SqlExtract.extract(statementHandler); if(sqlExtractResult!=null){ //对sql进行分析 Connection connection = (Connection)invocation.getArgs()[0]; SqlAnalysisResultList resultList = SqlAnalysis.analysis(sqlExtractResult,connection); //对分析结果进行评估 SqlScoreResult sqlScoreResult = sqlScoreService.score(resultList); if(sqlScoreResult!=null){ sqlScoreResult.setSqlId(sqlExtractResult.getSqlId()); sqlScoreResult.setSourceSql(sqlExtractResult.getSourceSql()); //输出评分结果 sqlScoreResultOut.outResult(sqlScoreResult); }else{
package com.jd.sql.analysis.core; /** * @Author huhaitao21 * @Description sql分析切面类 * @Date 22:47 2022/10/25 **/ @Intercepts({@Signature( type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class} ), @Signature( type = Executor.class, method = "update", args = {MappedStatement.class, Object.class} ),@Signature( type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class} )}) public class SqlAnalysisAspect implements Interceptor { Logger logger = LoggerFactory.getLogger(SqlAnalysisAspect.class); /** * 评分规则服务 */ private static SqlScoreService sqlScoreService = new SqlScoreServiceRulesEngine(); /** * 评分结果输出服务 */ private static SqlScoreResultOutService sqlScoreResultOut = new SqlScoreResultOutServiceDefault(); @Override public Object intercept(Invocation invocation) throws Throwable { try { Object firstArg = invocation.getArgs()[0]; if(SqlAnalysisConfig.getSqlReplaceModelSwitch()!=null && SqlAnalysisConfig.getSqlReplaceModelSwitch() && firstArg instanceof MappedStatement){ //sql替换模块 MappedStatement mappedStatement = (MappedStatement)firstArg; String replaceSql = SqlReplaceConfig.getReplaceSqlBySqlId(mappedStatement.getId()); if(StringUtils.isNotBlank(replaceSql)){ SqlReplace.replace(invocation,replaceSql); } }else if(SqlAnalysisConfig.getAnalysisSwitch() && firstArg instanceof Connection){ //sql 分析模块 //获取入参statement StatementHandler statementHandler = (StatementHandler)invocation.getTarget(); //提取待执行的完整sql语句 SqlExtractResult sqlExtractResult = SqlExtract.extract(statementHandler); if(sqlExtractResult!=null){ //对sql进行分析 Connection connection = (Connection)invocation.getArgs()[0]; SqlAnalysisResultList resultList = SqlAnalysis.analysis(sqlExtractResult,connection); //对分析结果进行评估 SqlScoreResult sqlScoreResult = sqlScoreService.score(resultList); if(sqlScoreResult!=null){ sqlScoreResult.setSqlId(sqlExtractResult.getSqlId()); sqlScoreResult.setSourceSql(sqlExtractResult.getSourceSql()); //输出评分结果 sqlScoreResultOut.outResult(sqlScoreResult); }else{
logger.error("sql analysis score error {},{}", GsonUtil.bean2Json(resultList),GsonUtil.bean2Json(sqlExtractResult));
17
2023-10-25 08:59:26+00:00
12k
d0ge/sessionless
src/test/java/SignUnsignTest.java
[ { "identifier": "DangerousTokenSigner", "path": "src/main/java/one/d4d/sessionless/itsdangerous/crypto/DangerousTokenSigner.java", "snippet": "public class DangerousTokenSigner extends TokenSigner {\n\n public DangerousTokenSigner(SecretKey key) {\n super(key);\n }\n\n public DangerousTo...
import one.d4d.sessionless.itsdangerous.*; import one.d4d.sessionless.itsdangerous.crypto.DangerousTokenSigner; import one.d4d.sessionless.itsdangerous.model.DangerousSignedToken; import one.d4d.sessionless.itsdangerous.model.SignedToken; import one.d4d.sessionless.itsdangerous.model.SignedTokenObjectFinder; import one.d4d.sessionless.keys.SecretKey; import one.d4d.sessionless.utils.Utils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import java.util.Optional;
9,990
public class SignUnsignTest { @Test void KeyDerivationTest() { Assertions.assertDoesNotThrow(() -> { for(Algorithms a: Algorithms.values()){ for(Derivation d: Derivation.values()){ byte[] secret = "secret".getBytes(); byte[] salt = "cookie-session".getBytes(); String ts = new String(Utils.timestampInFuture()); DangerousSignedToken newToken = new DangerousSignedToken((byte)'.',"{}",ts,""); DangerousTokenSigner s = new DangerousTokenSigner(a,d,secret,salt,(byte)'.'); newToken.setSigner(s); String signedToken = newToken.dumps();
public class SignUnsignTest { @Test void KeyDerivationTest() { Assertions.assertDoesNotThrow(() -> { for(Algorithms a: Algorithms.values()){ for(Derivation d: Derivation.values()){ byte[] secret = "secret".getBytes(); byte[] salt = "cookie-session".getBytes(); String ts = new String(Utils.timestampInFuture()); DangerousSignedToken newToken = new DangerousSignedToken((byte)'.',"{}",ts,""); DangerousTokenSigner s = new DangerousTokenSigner(a,d,secret,salt,(byte)'.'); newToken.setSigner(s); String signedToken = newToken.dumps();
Optional<SignedToken> optionalToken = SignedTokenObjectFinder.parseToken(signedToken);
3
2023-10-30 09:12:06+00:00
12k
LEAWIND/Third-Person
common/src/main/java/net/leawind/mc/thirdperson/core/CameraAgent.java
[ { "identifier": "ThirdPerson", "path": "common/src/main/java/net/leawind/mc/thirdperson/ThirdPerson.java", "snippet": "public class ThirdPerson {\n\tpublic static final Logger LOGGER = LoggerFactory.getLogger(ModConstants.MOD_ID);\n\tprivate static final ConfigManager CONFIG_MA...
import net.leawind.mc.thirdperson.ThirdPerson; import net.leawind.mc.thirdperson.api.ModConstants; import net.leawind.mc.thirdperson.api.cameraoffset.CameraOffsetMode; import net.leawind.mc.thirdperson.impl.config.Config; import net.leawind.mc.thirdperson.mixin.CameraInvoker; import net.leawind.mc.thirdperson.mixin.LocalPlayerInvoker; import net.leawind.mc.util.api.math.vector.Vector2d; import net.leawind.mc.util.api.math.vector.Vector3d; import net.leawind.mc.util.math.LMath; import net.leawind.mc.util.math.smoothvalue.ExpSmoothDouble; import net.leawind.mc.util.math.smoothvalue.ExpSmoothVector2d; import net.leawind.mc.util.math.smoothvalue.ExpSmoothVector3d; import net.minecraft.client.Camera; import net.minecraft.client.Minecraft; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.projectile.ProjectileUtil; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.ClipContext; import net.minecraft.world.phys.*; import org.apache.logging.log4j.util.PerformanceSensitive; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable;
8,151
package net.leawind.mc.thirdperson.core; public final class CameraAgent { public static final @NotNull Camera fakeCamera = new Camera(); public static final @NotNull Vector2d relativeRotation = Vector2d.of(0); /** * 相机偏移量 */
package net.leawind.mc.thirdperson.core; public final class CameraAgent { public static final @NotNull Camera fakeCamera = new Camera(); public static final @NotNull Vector2d relativeRotation = Vector2d.of(0); /** * 相机偏移量 */
public static final @NotNull ExpSmoothVector2d smoothOffsetRatio;
10
2023-10-31 05:52:36+00:00
12k
kandybaby/S3mediaArchival
backend/src/main/java/com/example/mediaarchival/consumers/DownloadConsumer.java
[ { "identifier": "MediaController", "path": "backend/src/main/java/com/example/mediaarchival/controllers/MediaController.java", "snippet": "@RestController\n@RequestMapping(\"/api/media-objects\")\npublic class MediaController {\n private final MediaRepository mediaRepository;\n\n private final JmsTemp...
import com.example.mediaarchival.controllers.MediaController; import com.example.mediaarchival.models.LibraryModel; import com.example.mediaarchival.models.MediaModel; import com.example.mediaarchival.repositories.MediaRepository; import com.example.mediaarchival.utils.DirectoryUtils; import com.example.mediaarchival.utils.EnvUtils; import java.io.IOException; import java.nio.file.Paths; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.annotation.JmsListener; import org.springframework.stereotype.Component; import software.amazon.awssdk.transfer.s3.S3TransferManager; import software.amazon.awssdk.transfer.s3.model.CompletedFileDownload; import software.amazon.awssdk.transfer.s3.model.DownloadFileRequest; import software.amazon.awssdk.transfer.s3.model.FileDownload;
8,774
package com.example.mediaarchival.consumers; /** * Consumer class that handles the downloading of media objects from an S3 bucket. * This class listens to a JMS queue for download requests and processes them accordingly. */ @Component public class DownloadConsumer { private final S3TransferManager transferManager; private final MediaRepository mediaRepository; private final MediaController mediaController; private static final Logger errorLogger = LoggerFactory.getLogger("ERROR_LOGGER"); @Autowired public DownloadConsumer( MediaRepository mediaRepository, S3TransferManager transferManager, MediaController mediaController) { this.transferManager = transferManager; this.mediaRepository = mediaRepository; this.mediaController = mediaController; } /** * Downloads a media object from an S3 bucket based on a path received from the download queue. * This method listens to a JMS queue and triggers when a download request is received. * * @param path The path of the media object in the S3 bucket. * @throws IOException If an I/O error occurs during the download process. */ @JmsListener( destination = "downloadQueue", containerFactory = "containerFactory", concurrency = "5") public void downloadObject(String path) throws IOException {
package com.example.mediaarchival.consumers; /** * Consumer class that handles the downloading of media objects from an S3 bucket. * This class listens to a JMS queue for download requests and processes them accordingly. */ @Component public class DownloadConsumer { private final S3TransferManager transferManager; private final MediaRepository mediaRepository; private final MediaController mediaController; private static final Logger errorLogger = LoggerFactory.getLogger("ERROR_LOGGER"); @Autowired public DownloadConsumer( MediaRepository mediaRepository, S3TransferManager transferManager, MediaController mediaController) { this.transferManager = transferManager; this.mediaRepository = mediaRepository; this.mediaController = mediaController; } /** * Downloads a media object from an S3 bucket based on a path received from the download queue. * This method listens to a JMS queue and triggers when a download request is received. * * @param path The path of the media object in the S3 bucket. * @throws IOException If an I/O error occurs during the download process. */ @JmsListener( destination = "downloadQueue", containerFactory = "containerFactory", concurrency = "5") public void downloadObject(String path) throws IOException {
MediaModel media = mediaRepository.findByPath(path);
2
2023-10-27 01:54:57+00:00
12k
siam1026/siam-cloud
siam-goods/goods-provider/src/main/java/com/siam/package_goods/controller/member/ShoppingCartController.java
[ { "identifier": "BasicData", "path": "siam-common/src/main/java/com/siam/package_common/entity/BasicData.java", "snippet": "public class BasicData extends BasicResult{\n private Object data;\n\n public Object getData() {\n return data;\n }\n\n public void setData(Object data) {\n ...
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.siam.package_common.entity.BasicData; import com.siam.package_common.entity.BasicResult; import com.siam.package_common.constant.BasicResultCode; import com.siam.package_common.constant.Quantity; import com.siam.package_common.exception.StoneCustomerException; import com.siam.package_common.util.GsonUtils; import com.siam.package_user.auth.cache.MemberSessionManager; import com.siam.package_user.entity.Member; import com.siam.package_goods.entity.ShoppingCart; import com.siam.package_goods.model.example.ShoppingCartExample; import com.siam.package_goods.service.ShoppingCartService; import com.siam.package_goods.service.GoodsSpecificationOptionService; import com.siam.package_user.util.TokenUtil; import io.swagger.annotations.Api; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; 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.RestController; import javax.servlet.http.HttpServletRequest; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.Map;
10,486
package com.siam.package_goods.controller.member; @Slf4j @RestController @RequestMapping(value = "/rest/member/shoppingCart") @Transactional(rollbackFor = Exception.class) @Api(tags = "购物车模块相关接口", description = "ShoppingCartController") public class ShoppingCartController { @Autowired private ShoppingCartService shoppingCartService; @Autowired private GoodsSpecificationOptionService goodsSpecificationOptionService; @Autowired private MemberSessionManager memberSessionManager; /** * 购物车列表 * * @return * @author 暹罗 */ @PostMapping(value = "/list") public BasicResult list(@RequestBody @Validated(value = {}) ShoppingCart shoppingCart, HttpServletRequest request){ BasicData basicResult = new BasicData(); Member loginMember = memberSessionManager.getSession(TokenUtil.getToken()); if(shoppingCart.getShopId() == null){
package com.siam.package_goods.controller.member; @Slf4j @RestController @RequestMapping(value = "/rest/member/shoppingCart") @Transactional(rollbackFor = Exception.class) @Api(tags = "购物车模块相关接口", description = "ShoppingCartController") public class ShoppingCartController { @Autowired private ShoppingCartService shoppingCartService; @Autowired private GoodsSpecificationOptionService goodsSpecificationOptionService; @Autowired private MemberSessionManager memberSessionManager; /** * 购物车列表 * * @return * @author 暹罗 */ @PostMapping(value = "/list") public BasicResult list(@RequestBody @Validated(value = {}) ShoppingCart shoppingCart, HttpServletRequest request){ BasicData basicResult = new BasicData(); Member loginMember = memberSessionManager.getSession(TokenUtil.getToken()); if(shoppingCart.getShopId() == null){
throw new StoneCustomerException("店铺id不能为空");
4
2023-10-26 10:45:10+00:00
12k
elizagamedev/android-libre-japanese-input
app/src/main/java/sh/eliza/japaneseinput/KeyEventButtonTouchListener.java
[ { "identifier": "DrawableType", "path": "app/src/main/java/sh/eliza/japaneseinput/keyboard/BackgroundDrawableFactory.java", "snippet": "public enum DrawableType {\n // Key background for twelvekeys layout.\n TWELVEKEYS_REGULAR_KEY_BACKGROUND,\n TWELVEKEYS_FUNCTION_KEY_BACKGROUND,\n TWELVEKEYS_FUNCTI...
import android.view.View; import android.view.View.OnTouchListener; import com.google.common.base.Optional; import java.util.Collections; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCommands.Input.TouchAction; import sh.eliza.japaneseinput.keyboard.BackgroundDrawableFactory.DrawableType; import sh.eliza.japaneseinput.keyboard.Flick; import sh.eliza.japaneseinput.keyboard.Flick.Direction; import sh.eliza.japaneseinput.keyboard.Key; import sh.eliza.japaneseinput.keyboard.Key.Stick; import sh.eliza.japaneseinput.keyboard.KeyEntity; import sh.eliza.japaneseinput.keyboard.KeyEventContext; import sh.eliza.japaneseinput.keyboard.KeyEventHandler; import sh.eliza.japaneseinput.keyboard.KeyState; import android.view.MotionEvent;
9,557
// Copyright 2010-2018, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package sh.eliza.japaneseinput; /** * This class is an event listener for a view which sends a key to MozcServer. * * <p>Note that currently, we assume all key are repeatable based on our requirements. We can easily * support non repeatable key if necessary. */ public class KeyEventButtonTouchListener implements OnTouchListener { private final int sourceId; private final int keyCode; private KeyEventHandler keyEventHandler = null; private KeyEventContext keyEventContext = null; /** This is exported as protected for testing. */ protected KeyEventButtonTouchListener(int sourceId, int keyCode) { this.sourceId = sourceId; this.keyCode = keyCode; } /** Resets the internal state of this listener. This is exported as protected for testing. */ protected void reset() { KeyEventHandler keyEventHandler = this.keyEventHandler; KeyEventContext keyEventContext = this.keyEventContext; if (keyEventHandler != null && keyEventContext != null) { keyEventHandler.cancelDelayedKeyEvent(keyEventContext); } this.keyEventContext = null; } /** Sets a new event handler to this instance. This is exported as protected for testing. */ protected void setKeyEventHandler(KeyEventHandler keyEventHandler) { // We'll detach the current event context from the old key event handler. reset(); this.keyEventHandler = keyEventHandler; } /** * Creates a (pseudo) {@link Key} instance based on the given {@code button} and its {@code * keyCode}. This is exported as package private for testing. */ private static Key createKey(View button, int sourceId, int keyCode) { KeyEntity keyEntity = new KeyEntity( sourceId, keyCode, KeyEntity.INVALID_KEY_CODE, true, 0, Optional.absent(), false, Optional.absent(), 0, 0, 0, 0); Flick flick = new Flick(Direction.CENTER, keyEntity); KeyState keyState = new KeyState( "", Collections.emptySet(), Collections.emptySet(), Collections.emptySet(), Collections.singletonList(flick)); // Now, we support repeatable keys only. return new Key( 0, 0, button.getWidth(), button.getHeight(), 0, 0, true, false,
// Copyright 2010-2018, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package sh.eliza.japaneseinput; /** * This class is an event listener for a view which sends a key to MozcServer. * * <p>Note that currently, we assume all key are repeatable based on our requirements. We can easily * support non repeatable key if necessary. */ public class KeyEventButtonTouchListener implements OnTouchListener { private final int sourceId; private final int keyCode; private KeyEventHandler keyEventHandler = null; private KeyEventContext keyEventContext = null; /** This is exported as protected for testing. */ protected KeyEventButtonTouchListener(int sourceId, int keyCode) { this.sourceId = sourceId; this.keyCode = keyCode; } /** Resets the internal state of this listener. This is exported as protected for testing. */ protected void reset() { KeyEventHandler keyEventHandler = this.keyEventHandler; KeyEventContext keyEventContext = this.keyEventContext; if (keyEventHandler != null && keyEventContext != null) { keyEventHandler.cancelDelayedKeyEvent(keyEventContext); } this.keyEventContext = null; } /** Sets a new event handler to this instance. This is exported as protected for testing. */ protected void setKeyEventHandler(KeyEventHandler keyEventHandler) { // We'll detach the current event context from the old key event handler. reset(); this.keyEventHandler = keyEventHandler; } /** * Creates a (pseudo) {@link Key} instance based on the given {@code button} and its {@code * keyCode}. This is exported as package private for testing. */ private static Key createKey(View button, int sourceId, int keyCode) { KeyEntity keyEntity = new KeyEntity( sourceId, keyCode, KeyEntity.INVALID_KEY_CODE, true, 0, Optional.absent(), false, Optional.absent(), 0, 0, 0, 0); Flick flick = new Flick(Direction.CENTER, keyEntity); KeyState keyState = new KeyState( "", Collections.emptySet(), Collections.emptySet(), Collections.emptySet(), Collections.singletonList(flick)); // Now, we support repeatable keys only. return new Key( 0, 0, button.getWidth(), button.getHeight(), 0, 0, true, false,
Stick.EVEN,
4
2023-10-25 07:33:25+00:00
12k
PhilipPanda/Temple-Client
src/main/java/xyz/templecheats/templeclient/impl/gui/ui/watermark.java
[ { "identifier": "ModuleManager", "path": "src/main/java/xyz/templecheats/templeclient/ModuleManager.java", "snippet": "public class ModuleManager {\n\n public static ArrayList<Module> modules = new ArrayList<>();\n\n public static void addMod(Module mod) {\n modules.add(mod);\n }\n\n ...
import xyz.templecheats.templeclient.ModuleManager; import xyz.templecheats.templeclient.impl.modules.client.ClickGUI; import xyz.templecheats.templeclient.impl.modules.client.Panic; import xyz.templecheats.templeclient.impl.modules.Module; import xyz.templecheats.templeclient.impl.gui.font.FontUtils; import xyz.templecheats.templeclient.impl.gui.font.MinecraftFontRenderer; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.renderer.GlStateManager; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import java.util.ArrayList; import java.util.Comparator;
10,198
package xyz.templecheats.templeclient.impl.gui.ui; public class watermark { private static Comparator<Module> MODULE_COMPARATOR = new Comparator<Module>() { @Override public int compare(Module a, Module b) { return Integer.compare(Minecraft.getMinecraft().fontRenderer.getStringWidth(b.getName()), Minecraft.getMinecraft().fontRenderer.getStringWidth(a.getName())); } }; @SubscribeEvent public void onRender(RenderGameOverlayEvent.Post e) { switch (e.getType()) { case TEXT: if (!Panic.isPanic) { int y = 10; final int[] counter = {1}; Minecraft mc = Minecraft.getMinecraft();
package xyz.templecheats.templeclient.impl.gui.ui; public class watermark { private static Comparator<Module> MODULE_COMPARATOR = new Comparator<Module>() { @Override public int compare(Module a, Module b) { return Integer.compare(Minecraft.getMinecraft().fontRenderer.getStringWidth(b.getName()), Minecraft.getMinecraft().fontRenderer.getStringWidth(a.getName())); } }; @SubscribeEvent public void onRender(RenderGameOverlayEvent.Post e) { switch (e.getType()) { case TEXT: if (!Panic.isPanic) { int y = 10; final int[] counter = {1}; Minecraft mc = Minecraft.getMinecraft();
MinecraftFontRenderer fr = FontUtils.normal;
5
2023-10-28 12:03:50+00:00
12k
PlayReissLP/Continuity
src/main/java/me/pepperbell/continuity/client/properties/BaseCTMProperties.java
[ { "identifier": "CTMProperties", "path": "src/main/java/me/pepperbell/continuity/api/client/CTMProperties.java", "snippet": "public interface CTMProperties extends Comparable<CTMProperties> {\n\tboolean affectsTextures();\n\n\tboolean affectsTexture(Identifier id);\n\n\tboolean affectsBlockStates();\n\n...
import java.nio.charset.StandardCharsets; import java.util.EnumSet; import java.util.List; import java.util.Locale; import java.util.Properties; import java.util.Set; import java.util.function.IntPredicate; import java.util.function.Predicate; import java.util.regex.Pattern; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringEscapeUtils; import org.jetbrains.annotations.NotNull; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterators; import com.google.common.hash.Hashing; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import me.pepperbell.continuity.api.client.CTMProperties; import me.pepperbell.continuity.api.client.CTMPropertiesFactory; import me.pepperbell.continuity.client.ContinuityClient; import me.pepperbell.continuity.client.util.InvalidIdentifierHandler; import me.pepperbell.continuity.client.util.MathUtil; import me.pepperbell.continuity.client.util.PropertiesParsingHelper; import me.pepperbell.continuity.client.util.ResourceRedirectHelper; import me.pepperbell.continuity.client.util.TextureUtil; import me.pepperbell.continuity.client.util.biome.BiomeHolder; import me.pepperbell.continuity.client.util.biome.BiomeHolderManager; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.client.MinecraftClient; import net.minecraft.client.util.SpriteIdentifier; import net.minecraft.resource.DefaultResourcePack; import net.minecraft.resource.ResourceManager; import net.minecraft.resource.ResourcePack; import net.minecraft.resource.ResourceType; import net.minecraft.util.Identifier; import net.minecraft.util.InvalidIdentifierException; import net.minecraft.util.math.Direction; import net.minecraft.util.registry.Registry; import net.minecraft.world.biome.Biome;
8,408
} } else if (hasMinHeight) { heightPredicate = y -> y >= finalMin; } else if (hasMaxHeight) { heightPredicate = y -> y <= finalMax; } } } } protected void parseName() { String nameStr = properties.getProperty("name"); if (nameStr != null) { nameStr = nameStr.trim(); nameStr = StringEscapeUtils.escapeJava(nameStr); boolean isPattern = false; boolean caseInsensitive = false; if (nameStr.startsWith("regex:")) { nameStr = nameStr.substring(6); } else if (nameStr.startsWith("iregex:")) { nameStr = nameStr.substring(7); caseInsensitive = true; } else if (nameStr.startsWith("pattern:")) { nameStr = nameStr.substring(8); isPattern = true; } else if (nameStr.startsWith("ipattern:")) { nameStr = nameStr.substring(9); isPattern = true; caseInsensitive = true; } else { blockEntityNamePredicate = nameStr::equals; return; } String patternStr = nameStr; if (isPattern) { patternStr = Pattern.quote(patternStr); patternStr = patternStr.replace("?", "\\E.\\Q"); patternStr = patternStr.replace("*", "\\E.*\\Q"); } Pattern pattern = Pattern.compile(patternStr, caseInsensitive ? Pattern.CASE_INSENSITIVE : 0); blockEntityNamePredicate = blockEntityName -> pattern.matcher(blockEntityName).matches(); } } protected void parseResourceCondition() { String conditionsStr = properties.getProperty("resourceCondition"); if (conditionsStr != null) { conditionsStr = conditionsStr.trim(); String[] conditionStrs = conditionsStr.split("\\|"); if (conditionStrs.length != 0) { ResourcePack[] packs = MinecraftClient.getInstance().getResourceManager().streamResourcePacks().toArray(ResourcePack[]::new); ArrayUtils.reverse(packs); DefaultResourcePack defaultPack = MinecraftClient.getInstance().getResourcePackProvider().getPack(); InvalidIdentifierHandler.enableInvalidPaths(); Outer: for (int i = 0; i < conditionStrs.length; i++) { String conditionStr = conditionStrs[i]; if (!conditionStr.isEmpty()) { String[] parts = conditionStr.split("@", 2); if (parts.length != 0) { Identifier resourceId = new Identifier(parts[0]); String packStr; if (parts.length > 1) { packStr = parts[1]; } else { packStr = null; } Predicate<ResourcePack> predicate; if (packStr == null || packStr.equals("default")) { predicate = pack -> pack == defaultPack; } else if (packStr.equals("programmer_art")) { predicate = pack -> pack.getName().equals("Programmer Art"); } else { ContinuityClient.LOGGER.warn("Invalid pack '" + packStr + "' in 'resourceCondition' element '" + conditionStr + "' at index " + i + " in file '" + id + "' in pack '" + packName + "'"); continue; } for (ResourcePack pack : packs) { if (pack.contains(ResourceType.CLIENT_RESOURCES, resourceId)) { if (!predicate.test(pack)) { valid = false; break Outer; } break; } } } } } InvalidIdentifierHandler.disableInvalidPaths(); } } } protected boolean isValid() { return valid; } protected void resolveTiles() { textureDependencies = new ObjectOpenHashSet<>(); spriteIds = new ObjectArrayList<>(); ResourceManager resourceManager = MinecraftClient.getInstance().getResourceManager(); for (Identifier tile : tiles) { SpriteIdentifier spriteId; if (tile.equals(SPECIAL_SKIP_ID)) { spriteId = SPECIAL_SKIP_SPRITE_ID; } else if (tile.equals(SPECIAL_DEFAULT_ID)) { spriteId = SPECIAL_DEFAULT_SPRITE_ID; } else { String namespace = tile.getNamespace(); String path = tile.getPath(); if (path.startsWith("textures/")) { path = path.substring(9); if (path.endsWith(".png")) { path = path.substring(0, path.length() - 4); } } else { path = getRedirectPath(path); Identifier redirectId = new Identifier(namespace, "textures/" + path + ".png");
package me.pepperbell.continuity.client.properties; public class BaseCTMProperties implements CTMProperties { public static final Identifier SPECIAL_SKIP_ID = ContinuityClient.asId("special/skip"); public static final Identifier SPECIAL_DEFAULT_ID = ContinuityClient.asId("special/default"); public static final SpriteIdentifier SPECIAL_SKIP_SPRITE_ID = TextureUtil.toSpriteId(SPECIAL_SKIP_ID); public static final SpriteIdentifier SPECIAL_DEFAULT_SPRITE_ID = TextureUtil.toSpriteId(SPECIAL_DEFAULT_ID); protected Properties properties; protected Identifier id; protected String packName; protected int packPriority; protected String method; protected Set<Identifier> matchTilesSet; protected Predicate<BlockState> matchBlocksPredicate; protected int weight = 0; protected List<Identifier> tiles; protected EnumSet<Direction> faces; protected Predicate<Biome> biomePredicate; protected IntPredicate heightPredicate; protected Predicate<String> blockEntityNamePredicate; protected boolean valid = true; protected Set<SpriteIdentifier> textureDependencies; protected List<SpriteIdentifier> spriteIds; public BaseCTMProperties(Properties properties, Identifier id, String packName, int packPriority, String method) { this.properties = properties; this.id = id; this.packName = packName; this.packPriority = packPriority; this.method = method; } @Override public boolean affectsTextures() { return matchTilesSet != null; } @Override public boolean affectsTexture(Identifier id) { if (matchTilesSet != null) { return matchTilesSet.contains(id); } return false; } @Override public boolean affectsBlockStates() { return matchBlocksPredicate != null; } @Override public boolean affectsBlockState(BlockState state) { if (matchBlocksPredicate != null) { return matchBlocksPredicate.test(state); } return false; } @Override public Set<SpriteIdentifier> getTextureDependencies() { if (textureDependencies == null) { resolveTiles(); } return textureDependencies; } /* -1 this < o 0 this == o 1 this > o */ @Override public int compareTo(@NotNull CTMProperties o) { if (o instanceof BaseCTMProperties) { int c = MathUtil.signum(weight - ((BaseCTMProperties)o).weight); if (c != 0) { return c; } } if (affectsTextures() && !o.affectsTextures()) { return 1; } if (!affectsTextures() && o.affectsTextures()) { return -1; } if (o instanceof BaseCTMProperties) { BaseCTMProperties o1 = (BaseCTMProperties)o; int c = MathUtil.signum(packPriority - o1.packPriority); if (c != 0) { return c; } return o1.getId().compareTo(getId()); } return 0; } public void init() { parseMatchTiles(); parseMatchBlocks(); detectMatches(); validateMatches(); parseWeight(); parseTiles(); validateTiles(); parseFaces(); parseBiomes(); parseHeights(); parseName(); parseResourceCondition(); } protected void parseMatchTiles() { matchTilesSet = PropertiesParsingHelper.parseMatchTiles(properties, "matchTiles", id, packName); } protected void parseMatchBlocks() { matchBlocksPredicate = PropertiesParsingHelper.parseBlockStates(properties, "matchBlocks", id, packName); } protected void detectMatches() { String baseName = FilenameUtils.getBaseName(id.getPath()); if (matchBlocksPredicate == null) { String prefix = "block_"; if (baseName.startsWith(prefix)) { try { Identifier id = new Identifier(baseName.substring(prefix.length())); Block block = Registry.BLOCK.get(id); if (block != Blocks.AIR) { matchBlocksPredicate = state -> state.getBlock() == block; } } catch (InvalidIdentifierException e) { // } } } } protected void validateMatches() { if (matchTilesSet == null && matchBlocksPredicate == null) { ContinuityClient.LOGGER.error("No tile or block matches provided in file '" + id + "' in pack '" + packName + "'"); valid = false; } } protected void parseWeight() { String weightStr = properties.getProperty("weight"); if (weightStr != null) { weightStr = weightStr.trim(); try { weight = Integer.parseInt(weightStr); } catch (NumberFormatException e) { ContinuityClient.LOGGER.warn("Invalid 'weight' value '" + weightStr + "' in file '" + id + "' in pack '" + packName + "'"); } } } protected void parseTiles() { String tilesStr = properties.getProperty("tiles"); if (tilesStr != null) { tilesStr = tilesStr.trim(); String[] tileStrs = tilesStr.split("[ ,]"); if (tileStrs.length != 0) { String basePath = FilenameUtils.getPath(id.getPath()); ImmutableList.Builder<Identifier> listBuilder = ImmutableList.builder(); InvalidIdentifierHandler.enableInvalidPaths(); for (int i = 0; i < tileStrs.length; i++) { String tileStr = tileStrs[i]; if (!tileStr.isEmpty()) { if (tileStr.endsWith("<skip>") || tileStr.endsWith("<skip>.png")) { listBuilder.add(SPECIAL_SKIP_ID); continue; } else if (tileStr.endsWith("<default>") || tileStr.endsWith("<default>.png")) { listBuilder.add(SPECIAL_DEFAULT_ID); continue; } if (tileStr.contains("-")) { String[] tileStrRange = tileStr.split("-"); if (tileStrRange.length == 2) { try { int min = Integer.parseInt(tileStrRange[0]); int max = Integer.parseInt(tileStrRange[1]); if (min <= max) { for (int t = min; t <= max; t++) { listBuilder.add(new Identifier(id.getNamespace(), basePath + t + ".png")); } continue; } } catch (NumberFormatException e) { // } ContinuityClient.LOGGER.warn("Invalid 'tiles' element '" + tileStr + "' at index " + i + " in file '" + id + "' in pack '" + packName + "'"); } } else { String[] parts = tileStr.split(":", 2); if (parts.length != 0) { String namespace; String path; if (parts.length > 1) { namespace = parts[0]; path = parts[1]; } else { namespace = id.getNamespace(); path = parts[0]; } if (!path.endsWith(".png")) { path = path + ".png"; } if (path.startsWith("./")) { path = basePath + path.substring(2); } else if (path.startsWith("~/")) { path = "optifine/" + path.substring(2); } else if (path.startsWith("/")) { path = "optifine/" + path.substring(1); } else if (!path.startsWith("textures/") && !path.startsWith("optifine/")) { path = basePath + path; } listBuilder.add(new Identifier(namespace, path)); } } } } InvalidIdentifierHandler.disableInvalidPaths(); ImmutableList<Identifier> list = listBuilder.build(); if (!list.isEmpty()) { tiles = list; } } } } protected void validateTiles() { if (tiles == null) { ContinuityClient.LOGGER.error("No tiles provided in file '" + id + "' in pack '" + packName + "'"); valid = false; } } protected void parseFaces() { String facesStr = properties.getProperty("faces"); if (facesStr != null) { facesStr = facesStr.trim(); String[] faceStrs = facesStr.split("[ ,]"); if (faceStrs.length != 0) { for (int i = 0; i < faceStrs.length; i++) { String faceStr = faceStrs[i]; if (!faceStr.isEmpty()) { faceStr = faceStr.toUpperCase(Locale.ROOT); if (faceStr.equals("BOTTOM")) { faceStr = "DOWN"; } else if (faceStr.equals("TOP")) { faceStr = "UP"; } try { Direction direction = Direction.valueOf(faceStr); if (faces == null) { faces = EnumSet.noneOf(Direction.class); } faces.add(direction); continue; } catch (IllegalArgumentException e) { // } if (faceStr.equals("SIDES")) { if (faces == null) { faces = EnumSet.noneOf(Direction.class); } Iterators.addAll(faces, Direction.Type.HORIZONTAL.iterator()); continue; } else if (faceStr.equals("ALL")) { faces = null; return; } ContinuityClient.LOGGER.warn("Unknown 'faces' element '" + faceStr + "' at index " + i + " in file '" + id + "' in pack '" + packName + "'"); } } } } } protected void parseBiomes() { String biomesStr = properties.getProperty("biomes"); if (biomesStr != null) { biomesStr = biomesStr.trim(); boolean negate = false; if (biomesStr.charAt(0) == '!') { negate = true; biomesStr = biomesStr.substring(1); } String[] biomeStrs = biomesStr.split(" "); if (biomeStrs.length != 0) { ImmutableSet.Builder<BiomeHolder> setBuilder = ImmutableSet.builder(); for (int i = 0; i < biomeStrs.length; i++) { String biomeStr = biomeStrs[i]; if (!biomeStr.isEmpty()) { try { Identifier biomeId = new Identifier(biomeStr.toLowerCase(Locale.ROOT)); setBuilder.add(BiomeHolderManager.getOrCreateHolder(biomeId)); } catch (InvalidIdentifierException e) { ContinuityClient.LOGGER.warn("Invalid 'biomes' element '" + biomeStr + "' at index " + i + " in file '" + id + "' in pack '" + packName + "'", e); } } } ImmutableSet<BiomeHolder> set = setBuilder.build(); if (!set.isEmpty()) { biomePredicate = biome -> { for (BiomeHolder holder : set) { if (holder.getBiome() == biome) { return true; } } return false; }; if (negate) { biomePredicate = biomePredicate.negate(); } } } } } protected void parseHeights() { String heightsStr = properties.getProperty("heights"); if (heightsStr != null) { heightsStr = heightsStr.trim(); String[] heightStrs = heightsStr.split("[ ,]"); if (heightStrs.length != 0) { ImmutableList.Builder<IntPredicate> predicateListBuilder = ImmutableList.builder(); for (int i = 0; i < heightStrs.length; i++) { String heightStr = heightStrs[i]; if (!heightStr.isEmpty()) { String[] parts = heightStr.split("-"); int length = parts.length; try { if (length == 2) { int min = Integer.parseInt(parts[0]); int max = Integer.parseInt(parts[1]); if (min < max) { predicateListBuilder.add(y -> y >= min && y <= max); } else if (min > max) { predicateListBuilder.add(y -> y >= max && y <= min); } else { predicateListBuilder.add(y -> y == min); } continue; } else if (length == 1) { int height = Integer.parseInt(parts[0]); predicateListBuilder.add(y -> y == height); continue; } } catch (NumberFormatException e) { // } ContinuityClient.LOGGER.warn("Invalid 'heights' element '" + heightStr + "' at index " + i + " in file '" + id + "' in pack '" + packName + "'"); } } ImmutableList<IntPredicate> predicateList = predicateListBuilder.build(); if (!predicateList.isEmpty()) { int amount = predicateList.size(); heightPredicate = y -> { for (int i = 0; i < amount; i++) { if (!predicateList.get(i).test(y)) { return false; } } return true; }; } } } if (heightPredicate == null) { String minHeightStr = properties.getProperty("minHeight"); String maxHeightStr = properties.getProperty("maxHeight"); boolean hasMinHeight = minHeightStr != null; boolean hasMaxHeight = maxHeightStr != null; if (hasMinHeight || hasMaxHeight) { int min = 0; int max = 0; if (hasMinHeight) { minHeightStr = minHeightStr.trim(); try { min = Integer.parseInt(minHeightStr); } catch (NumberFormatException e) { hasMinHeight = false; ContinuityClient.LOGGER.warn("Invalid 'minHeight' value '" + minHeightStr + "' in file '" + id + "' in pack '" + packName + "'"); } } if (hasMaxHeight) { maxHeightStr = maxHeightStr.trim(); try { max = Integer.parseInt(maxHeightStr); } catch (NumberFormatException e) { hasMaxHeight = false; ContinuityClient.LOGGER.warn("Invalid 'maxHeight' value '" + minHeightStr + "' in file '" + id + "' in pack '" + packName + "'"); } } int finalMin = min; int finalMax = max; if (hasMinHeight && hasMaxHeight) { if (finalMin < finalMax) { heightPredicate = y -> y >= finalMin && y <= finalMax; } else if (finalMin > finalMax) { heightPredicate = y -> y >= finalMax && y <= finalMin; } else { heightPredicate = y -> y == finalMin; } } else if (hasMinHeight) { heightPredicate = y -> y >= finalMin; } else if (hasMaxHeight) { heightPredicate = y -> y <= finalMax; } } } } protected void parseName() { String nameStr = properties.getProperty("name"); if (nameStr != null) { nameStr = nameStr.trim(); nameStr = StringEscapeUtils.escapeJava(nameStr); boolean isPattern = false; boolean caseInsensitive = false; if (nameStr.startsWith("regex:")) { nameStr = nameStr.substring(6); } else if (nameStr.startsWith("iregex:")) { nameStr = nameStr.substring(7); caseInsensitive = true; } else if (nameStr.startsWith("pattern:")) { nameStr = nameStr.substring(8); isPattern = true; } else if (nameStr.startsWith("ipattern:")) { nameStr = nameStr.substring(9); isPattern = true; caseInsensitive = true; } else { blockEntityNamePredicate = nameStr::equals; return; } String patternStr = nameStr; if (isPattern) { patternStr = Pattern.quote(patternStr); patternStr = patternStr.replace("?", "\\E.\\Q"); patternStr = patternStr.replace("*", "\\E.*\\Q"); } Pattern pattern = Pattern.compile(patternStr, caseInsensitive ? Pattern.CASE_INSENSITIVE : 0); blockEntityNamePredicate = blockEntityName -> pattern.matcher(blockEntityName).matches(); } } protected void parseResourceCondition() { String conditionsStr = properties.getProperty("resourceCondition"); if (conditionsStr != null) { conditionsStr = conditionsStr.trim(); String[] conditionStrs = conditionsStr.split("\\|"); if (conditionStrs.length != 0) { ResourcePack[] packs = MinecraftClient.getInstance().getResourceManager().streamResourcePacks().toArray(ResourcePack[]::new); ArrayUtils.reverse(packs); DefaultResourcePack defaultPack = MinecraftClient.getInstance().getResourcePackProvider().getPack(); InvalidIdentifierHandler.enableInvalidPaths(); Outer: for (int i = 0; i < conditionStrs.length; i++) { String conditionStr = conditionStrs[i]; if (!conditionStr.isEmpty()) { String[] parts = conditionStr.split("@", 2); if (parts.length != 0) { Identifier resourceId = new Identifier(parts[0]); String packStr; if (parts.length > 1) { packStr = parts[1]; } else { packStr = null; } Predicate<ResourcePack> predicate; if (packStr == null || packStr.equals("default")) { predicate = pack -> pack == defaultPack; } else if (packStr.equals("programmer_art")) { predicate = pack -> pack.getName().equals("Programmer Art"); } else { ContinuityClient.LOGGER.warn("Invalid pack '" + packStr + "' in 'resourceCondition' element '" + conditionStr + "' at index " + i + " in file '" + id + "' in pack '" + packName + "'"); continue; } for (ResourcePack pack : packs) { if (pack.contains(ResourceType.CLIENT_RESOURCES, resourceId)) { if (!predicate.test(pack)) { valid = false; break Outer; } break; } } } } } InvalidIdentifierHandler.disableInvalidPaths(); } } } protected boolean isValid() { return valid; } protected void resolveTiles() { textureDependencies = new ObjectOpenHashSet<>(); spriteIds = new ObjectArrayList<>(); ResourceManager resourceManager = MinecraftClient.getInstance().getResourceManager(); for (Identifier tile : tiles) { SpriteIdentifier spriteId; if (tile.equals(SPECIAL_SKIP_ID)) { spriteId = SPECIAL_SKIP_SPRITE_ID; } else if (tile.equals(SPECIAL_DEFAULT_ID)) { spriteId = SPECIAL_DEFAULT_SPRITE_ID; } else { String namespace = tile.getNamespace(); String path = tile.getPath(); if (path.startsWith("textures/")) { path = path.substring(9); if (path.endsWith(".png")) { path = path.substring(0, path.length() - 4); } } else { path = getRedirectPath(path); Identifier redirectId = new Identifier(namespace, "textures/" + path + ".png");
ResourceRedirectHelper.addRedirect(resourceManager, redirectId, tile);
6
2023-10-29 00:08:50+00:00
12k
oghenevovwerho/yaa
src/main/java/yaa/semantic/passes/fs1/F1BlockInClz.java
[ { "identifier": "Decimal", "path": "src/main/java/yaa/ast/Decimal.java", "snippet": "public class Decimal extends Stmt {\r\n public YaaToken token;\r\n\r\n public Decimal(YaaToken token) {\r\n this.token = token;\r\n }\r\n\r\n @Override\r\n public YaaInfo visit(FileState fs) {\r\n return fs.$...
import yaa.ast.Decimal; import yaa.ast.OverBlock; import yaa.parser.TokenUtils; import yaa.pojos.GlobalData; import yaa.pojos.YaaError; import yaa.pojos.YaaFun; import yaa.pojos.YaaMeta; import static yaa.pojos.GlobalData.fs1; import static yaa.pojos.GlobalData.int$name;
9,457
package yaa.semantic.passes.fs1; public class F1BlockInClz { public static void f1BlockInClz(OverBlock block) { fs1.newTable(); for (var parent$mtd$pack : block.methods.values()) { for (var method : parent$mtd$pack) { var newMethod = (YaaFun) F1NFun.f1NewFun(method); for (var metaCall : method.metaCalls) { var meta = fs1.getSymbol(metaCall.name.content); if (meta instanceof YaaMeta && meta.name.equals(GlobalData.configMetaClzName)) { for (var arg : metaCall.arguments.entrySet()) { var argument = arg.getKey(); if (argument.content.equals("privacy")) { if (arg.getValue() instanceof Decimal decimal) {
package yaa.semantic.passes.fs1; public class F1BlockInClz { public static void f1BlockInClz(OverBlock block) { fs1.newTable(); for (var parent$mtd$pack : block.methods.values()) { for (var method : parent$mtd$pack) { var newMethod = (YaaFun) F1NFun.f1NewFun(method); for (var metaCall : method.metaCalls) { var meta = fs1.getSymbol(metaCall.name.content); if (meta instanceof YaaMeta && meta.name.equals(GlobalData.configMetaClzName)) { for (var arg : metaCall.arguments.entrySet()) { var argument = arg.getKey(); if (argument.content.equals("privacy")) { if (arg.getValue() instanceof Decimal decimal) {
int value = TokenUtils.decimalValue(decimal.token);
2
2023-10-26 17:41:13+00:00
12k
echcz/web-service
src/main/jooq/cn/echcz/webservice/adapter/repository/Keys.java
[ { "identifier": "ActionLogTable", "path": "src/main/jooq/cn/echcz/webservice/adapter/repository/tables/ActionLogTable.java", "snippet": "@SuppressWarnings({ \"all\", \"unchecked\", \"rawtypes\" })\npublic class ActionLogTable extends TableImpl<ActionLogRecord> {\n\n private static final long serialVe...
import cn.echcz.webservice.adapter.repository.tables.ActionLogTable; import cn.echcz.webservice.adapter.repository.tables.DocumentTable; import cn.echcz.webservice.adapter.repository.tables.records.ActionLogRecord; import cn.echcz.webservice.adapter.repository.tables.records.DocumentRecord; import org.jooq.TableField; import org.jooq.UniqueKey; import org.jooq.impl.DSL; import org.jooq.impl.Internal;
7,410
/* * This file is generated by jOOQ. */ package cn.echcz.webservice.adapter.repository; /** * A class modelling foreign key relationships and constraints of tables in * the default schema. */ @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class Keys { // ------------------------------------------------------------------------- // UNIQUE and PRIMARY KEY definitions // ------------------------------------------------------------------------- public static final UniqueKey<ActionLogRecord> KEY_ACTION_LOG_PRIMARY = Internal.createUniqueKey(ActionLogTable.ACTION_LOG, DSL.name("KEY_action_log_PRIMARY"), new TableField[] { ActionLogTable.ACTION_LOG.ID }, true);
/* * This file is generated by jOOQ. */ package cn.echcz.webservice.adapter.repository; /** * A class modelling foreign key relationships and constraints of tables in * the default schema. */ @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class Keys { // ------------------------------------------------------------------------- // UNIQUE and PRIMARY KEY definitions // ------------------------------------------------------------------------- public static final UniqueKey<ActionLogRecord> KEY_ACTION_LOG_PRIMARY = Internal.createUniqueKey(ActionLogTable.ACTION_LOG, DSL.name("KEY_action_log_PRIMARY"), new TableField[] { ActionLogTable.ACTION_LOG.ID }, true);
public static final UniqueKey<DocumentRecord> KEY_DOCUMENT_PRIMARY = Internal.createUniqueKey(DocumentTable.DOCUMENT, DSL.name("KEY_document_PRIMARY"), new TableField[] { DocumentTable.DOCUMENT.ID }, true);
3
2023-10-30 18:55:49+00:00
12k
tom5454/Toms-Peripherals
Forge/src/platform-shared/java/com/tom/peripherals/Content.java
[ { "identifier": "GPUBlock", "path": "Forge/src/platform-shared/java/com/tom/peripherals/block/GPUBlock.java", "snippet": "public class GPUBlock extends Block implements EntityBlock {\n\n\tpublic GPUBlock() {\n\t\tsuper(Block.Properties.of().mapColor(DyeColor.WHITE).sound(SoundType.METAL).strength(5));\n...
import java.util.function.Function; import java.util.function.Supplier; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import com.tom.peripherals.block.GPUBlock; import com.tom.peripherals.block.MonitorBlock; import com.tom.peripherals.block.RedstonePortBlock; import com.tom.peripherals.block.WatchDogTimerBlock; import com.tom.peripherals.block.entity.GPUBlockEntity; import com.tom.peripherals.block.entity.MonitorBlockEntity; import com.tom.peripherals.block.entity.RedstonePortBlockEntity; import com.tom.peripherals.block.entity.WatchDogTimerBlockEntity; import com.tom.peripherals.platform.GameObject; import com.tom.peripherals.platform.GameObject.GameObjectBlockEntity; import com.tom.peripherals.platform.GameObject.GameRegistryBE.BlockEntityFactory; import com.tom.peripherals.platform.Platform;
10,779
package com.tom.peripherals; public class Content { public static final GameObject<GPUBlock> gpu = blockWithItem("gpu", GPUBlock::new); public static final GameObject<MonitorBlock> monitor = blockWithItem("monitor", MonitorBlock::new); public static final GameObject<WatchDogTimerBlock> wdt = blockWithItem("wdt", WatchDogTimerBlock::new); public static final GameObject<RedstonePortBlock> redstonePort = blockWithItem("redstone_port", RedstonePortBlock::new); public static final GameObject<Item> gpuChip = item("gpu_chip", () -> new Item(new Item.Properties())); public static final GameObject<Item> gpuChipRaw = item("gpu_chip_raw", () -> new Item(new Item.Properties())); public static final GameObjectBlockEntity<GPUBlockEntity> gpuBE = blockEntity("gpu", GPUBlockEntity::new, gpu); public static final GameObjectBlockEntity<MonitorBlockEntity> monitorBE = blockEntity("monitor", MonitorBlockEntity::new, monitor); public static final GameObjectBlockEntity<WatchDogTimerBlockEntity> wdtBE = blockEntity("wdt", WatchDogTimerBlockEntity::new, wdt);
package com.tom.peripherals; public class Content { public static final GameObject<GPUBlock> gpu = blockWithItem("gpu", GPUBlock::new); public static final GameObject<MonitorBlock> monitor = blockWithItem("monitor", MonitorBlock::new); public static final GameObject<WatchDogTimerBlock> wdt = blockWithItem("wdt", WatchDogTimerBlock::new); public static final GameObject<RedstonePortBlock> redstonePort = blockWithItem("redstone_port", RedstonePortBlock::new); public static final GameObject<Item> gpuChip = item("gpu_chip", () -> new Item(new Item.Properties())); public static final GameObject<Item> gpuChipRaw = item("gpu_chip_raw", () -> new Item(new Item.Properties())); public static final GameObjectBlockEntity<GPUBlockEntity> gpuBE = blockEntity("gpu", GPUBlockEntity::new, gpu); public static final GameObjectBlockEntity<MonitorBlockEntity> monitorBE = blockEntity("monitor", MonitorBlockEntity::new, monitor); public static final GameObjectBlockEntity<WatchDogTimerBlockEntity> wdtBE = blockEntity("wdt", WatchDogTimerBlockEntity::new, wdt);
public static final GameObjectBlockEntity<RedstonePortBlockEntity> redstonePortBE = blockEntity("redstone_port", RedstonePortBlockEntity::new, redstonePort);
6
2023-10-30 17:05:11+00:00
12k
unloggedio/intellij-java-plugin
src/main/java/com/insidious/plugin/factory/testcase/TestGenerationState.java
[ { "identifier": "ParameterNameFactory", "path": "src/main/java/com/insidious/plugin/client/ParameterNameFactory.java", "snippet": "public class ParameterNameFactory {\n\n private final Map<String, String> nameByIdMap = new HashMap<>();\n private final Map<String, Parameter> nameToParameterMap = ne...
import com.fasterxml.jackson.databind.ObjectMapper; import com.insidious.plugin.client.ParameterNameFactory; import com.insidious.plugin.factory.testcase.parameter.VariableContainer; import com.insidious.plugin.util.ClassTypeUtils; import com.insidious.plugin.pojo.Parameter; import com.insidious.plugin.util.LoggerUtil; import com.insidious.plugin.util.ObjectMapperInstance; import com.intellij.openapi.diagnostic.Logger; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import org.apache.commons.codec.digest.DigestUtils; import javax.lang.model.element.Modifier; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern;
8,347
package com.insidious.plugin.factory.testcase; /** * This container will hold the intermediate state of the script being generated, to keep track of * - created variables * - mocked calls */ public class TestGenerationState { private static final ObjectMapper objectMapper = ObjectMapperInstance.getInstance(); private static final Pattern ENDS_WITH_DIGITS = Pattern.compile("(.+)([0-9]+)$");
package com.insidious.plugin.factory.testcase; /** * This container will hold the intermediate state of the script being generated, to keep track of * - created variables * - mocked calls */ public class TestGenerationState { private static final ObjectMapper objectMapper = ObjectMapperInstance.getInstance(); private static final Pattern ENDS_WITH_DIGITS = Pattern.compile("(.+)([0-9]+)$");
private static final Logger logger = LoggerUtil.getInstance(TestGenerationState.class);
4
2023-10-31 09:07:46+00:00
12k
quentin452/DangerRPG-Continuation
src/main/java/mixac1/dangerrpg/capability/RPGEntityHelper.java
[ { "identifier": "IRPGEntity", "path": "src/main/java/mixac1/dangerrpg/api/entity/IRPGEntity.java", "snippet": "public interface IRPGEntity {\n\n EAFloat getEAMeleeDamage(EntityLivingBase entity);\n\n EAFloat getEARangeDamage(EntityLivingBase entity);\n\n void registerAttributes(Class<? extends ...
import mixac1.dangerrpg.api.entity.IRPGEntity; import mixac1.dangerrpg.api.entity.LvlEAProvider.DafailtLvlEAProvider; import mixac1.dangerrpg.api.event.RegEAEvent; import mixac1.dangerrpg.capability.data.RPGEntityRegister.RPGEntityData; import mixac1.dangerrpg.init.RPGCapability; import mixac1.dangerrpg.init.RPGConfig.EntityConfig; import mixac1.dangerrpg.util.IMultiplier; import mixac1.dangerrpg.util.IMultiplier.Multiplier; import mixac1.dangerrpg.util.IMultiplier.MultiplierAdd; import mixac1.dangerrpg.util.IMultiplier.MultiplierMul; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.monster.EntityMob; import net.minecraft.entity.player.EntityPlayer; import net.minecraftforge.common.MinecraftForge;
9,373
package mixac1.dangerrpg.capability; public abstract class RPGEntityHelper { public static final Multiplier HEALTH_MUL = new MultiplierMul(EntityConfig.d.entityLvlUpHealthMul); public static final Multiplier DAMAGE_MUL = new MultiplierMul(EntityConfig.d.entityLvlUpHealthMul); public static boolean isRPGable(EntityLivingBase entity) { return RPGCapability.rpgEntityRegistr.isActivated(entity); } public static boolean registerEntity(Class entityClass) { if (EntityLivingBase.class.isAssignableFrom(entityClass)) { if (RPGCapability.rpgEntityRegistr.containsKey(entityClass)) { return true; } IRPGEntity iRPG = EntityPlayer.class.isAssignableFrom(entityClass) ? IRPGEntity.DEFAULT_PLAYER : EntityMob.class.isAssignableFrom(entityClass) ? IRPGEntity.DEFAULT_MOB : IRPGEntity.DEFAULT_LIVING; RPGCapability.rpgEntityRegistr.put(entityClass, new RPGEntityData(iRPG, false)); return true; } return false; } public static void registerEntityDefault(Class<? extends EntityLivingBase> entityClass, RPGEntityData map) { map.registerEA(EntityAttributes.LVL, 1); MinecraftForge.EVENT_BUS.post(new RegEAEvent.DefaultEAEvent(entityClass, map)); } public static void registerEntityLiving(Class<? extends EntityLiving> entityClass, RPGEntityData map) { map.registerEA(EntityAttributes.HEALTH, 0f, HEALTH_MUL); MinecraftForge.EVENT_BUS.post(new RegEAEvent.EntytyLivingEAEvent(entityClass, map)); } public static void registerEntityMob(Class<? extends EntityMob> entityClass, RPGEntityData map) { map.registerEA(EntityAttributes.MELEE_DAMAGE, 0f, DAMAGE_MUL); MinecraftForge.EVENT_BUS.post(new RegEAEvent.EntytyMobEAEvent(entityClass, map)); } public static void registerEntityPlayer(Class<? extends EntityPlayer> entityClass, RPGEntityData map) { Multiplier ADD_1 = IMultiplier.ADD_1; Multiplier ADD_2 = new MultiplierAdd(2F); Multiplier ADD_0d001 = new MultiplierAdd(0.001F); Multiplier ADD_0d01 = new MultiplierAdd(0.01F); Multiplier ADD_0d025 = new MultiplierAdd(0.025F); Multiplier ADD_0d2 = new MultiplierAdd(0.2F); float q0 = EntityConfig.d.playerStartManaValue; float q1 = EntityConfig.d.playerStartManaRegenValue;
package mixac1.dangerrpg.capability; public abstract class RPGEntityHelper { public static final Multiplier HEALTH_MUL = new MultiplierMul(EntityConfig.d.entityLvlUpHealthMul); public static final Multiplier DAMAGE_MUL = new MultiplierMul(EntityConfig.d.entityLvlUpHealthMul); public static boolean isRPGable(EntityLivingBase entity) { return RPGCapability.rpgEntityRegistr.isActivated(entity); } public static boolean registerEntity(Class entityClass) { if (EntityLivingBase.class.isAssignableFrom(entityClass)) { if (RPGCapability.rpgEntityRegistr.containsKey(entityClass)) { return true; } IRPGEntity iRPG = EntityPlayer.class.isAssignableFrom(entityClass) ? IRPGEntity.DEFAULT_PLAYER : EntityMob.class.isAssignableFrom(entityClass) ? IRPGEntity.DEFAULT_MOB : IRPGEntity.DEFAULT_LIVING; RPGCapability.rpgEntityRegistr.put(entityClass, new RPGEntityData(iRPG, false)); return true; } return false; } public static void registerEntityDefault(Class<? extends EntityLivingBase> entityClass, RPGEntityData map) { map.registerEA(EntityAttributes.LVL, 1); MinecraftForge.EVENT_BUS.post(new RegEAEvent.DefaultEAEvent(entityClass, map)); } public static void registerEntityLiving(Class<? extends EntityLiving> entityClass, RPGEntityData map) { map.registerEA(EntityAttributes.HEALTH, 0f, HEALTH_MUL); MinecraftForge.EVENT_BUS.post(new RegEAEvent.EntytyLivingEAEvent(entityClass, map)); } public static void registerEntityMob(Class<? extends EntityMob> entityClass, RPGEntityData map) { map.registerEA(EntityAttributes.MELEE_DAMAGE, 0f, DAMAGE_MUL); MinecraftForge.EVENT_BUS.post(new RegEAEvent.EntytyMobEAEvent(entityClass, map)); } public static void registerEntityPlayer(Class<? extends EntityPlayer> entityClass, RPGEntityData map) { Multiplier ADD_1 = IMultiplier.ADD_1; Multiplier ADD_2 = new MultiplierAdd(2F); Multiplier ADD_0d001 = new MultiplierAdd(0.001F); Multiplier ADD_0d01 = new MultiplierAdd(0.01F); Multiplier ADD_0d025 = new MultiplierAdd(0.025F); Multiplier ADD_0d2 = new MultiplierAdd(0.2F); float q0 = EntityConfig.d.playerStartManaValue; float q1 = EntityConfig.d.playerStartManaRegenValue;
map.registerEALvlable(PlayerAttributes.HEALTH, 0f, new DafailtLvlEAProvider(2, 1000, ADD_2));
1
2023-10-31 21:00:14+00:00
12k
thinhunan/wonder8-promotion-rule
java/src/main/java/com/github/thinhunan/wonder8/promotion/rule/Strategy.java
[ { "identifier": "Item", "path": "java/src/main/java/com/github/thinhunan/wonder8/promotion/rule/model/Item.java", "snippet": "public class Item {\n String category;\n String SPU;\n String SKU;\n String seat;\n\n /// 单位:分 (by cent)\n int price;\n\n public Item(){}\n\n /*\n * @...
import com.github.thinhunan.wonder8.promotion.rule.model.Item; import com.github.thinhunan.wonder8.promotion.rule.model.P; import com.github.thinhunan.wonder8.promotion.rule.model.Rule; import com.github.thinhunan.wonder8.promotion.rule.model.SimplexRule; import com.github.thinhunan.wonder8.promotion.rule.model.strategy.BestMatch; import com.github.thinhunan.wonder8.promotion.rule.model.strategy.Calculator; import com.github.thinhunan.wonder8.promotion.rule.model.strategy.MatchGroup; import com.github.thinhunan.wonder8.promotion.rule.model.strategy.MatchType; import com.github.thinhunan.wonder8.promotion.rule.model.validate.RuleValidateResult; import java.util.*;
7,227
package com.github.thinhunan.wonder8.promotion.rule; public class Strategy { /** * 找出一组商品和和一堆规则的最佳组合匹配,即多个规则合作下优惠力度最大的匹配结果 * @param rules {Rule[]} * @param items {Item[]} * @param type {MatchType} * MatchType.OneTime = 匹配一次 * MatchType.OneRule = 匹配一个规则,但这个规则可以匹配多次 * MatchType.MultiRule = 可以匹配多个规则,每个规则可以匹配多次 * @param groupSetting {MatchGroup} * MatchGroup.CrossedMatch = 分组计算,不同组的优惠可叠加,所有规则放在一起求最大优惠 * MatchGroup.SequentialMatch = 分组计算,不同组的优惠可叠加,不同组的优惠按组计算后求最大叠加优惠 * @return {BestMatch} */ public static BestMatch bestChoice(List<Rule> rules, List<Item> items, MatchType type, MatchGroup groupSetting) { BestMatch bestMatch = Calculator.calculate(rules, items,type, groupSetting); bindSuggestion(bestMatch); return bestMatch; } /** * 找出一组商品和和一堆规则的最佳组合匹配,即多个规则合作下优惠力度最大的匹配结果 * @param rules {Rule[]} * @param items {Item[]} * @param type {MatchType} * MatchType.OneTime = 匹配一次 * MatchType.OneRule = 匹配一个规则,但这个规则可以匹配多次 * MatchType.MultiRule = 可以匹配多个规则,每个规则可以匹配多次 * @return {BestMatch} */ public static BestMatch bestChoice(List<Rule> rules, List<Item> items, MatchType type) { return bestChoice(rules, items,type,MatchGroup.CrossedMatch); } /** * 找出一组商品和和一堆规则的最佳匹配,但只应用一条规则 * @param {Rule[]} rules * @param {Item[]} tickets * @return {MatchResult} */ @Deprecated public static BestMatch bestMatch(List<Rule> rules, List<Item> items) { return bestChoice(rules, items,MatchType.OneRule); } /** * 找出一组商品和和一堆规则的最佳匹配,即优惠力度最大的匹配结果 * 与bestMatch()的区别在于,不管当前选的商品可以拆成匹配多少次,都只按一次匹配来算优惠 * 匹配的张数是规则的最低要求,价值取最高价格 * @param {Rule[]} rules * @param {Item[]} tickets * @return {MatchResult} */ @Deprecated public static BestMatch bestOfOnlyOnceDiscount(List<Rule> rules, List<Item> items) { return bestChoice(rules, items,MatchType.OneTime); } private static void bindSuggestion(BestMatch best) { if (best != null) {
package com.github.thinhunan.wonder8.promotion.rule; public class Strategy { /** * 找出一组商品和和一堆规则的最佳组合匹配,即多个规则合作下优惠力度最大的匹配结果 * @param rules {Rule[]} * @param items {Item[]} * @param type {MatchType} * MatchType.OneTime = 匹配一次 * MatchType.OneRule = 匹配一个规则,但这个规则可以匹配多次 * MatchType.MultiRule = 可以匹配多个规则,每个规则可以匹配多次 * @param groupSetting {MatchGroup} * MatchGroup.CrossedMatch = 分组计算,不同组的优惠可叠加,所有规则放在一起求最大优惠 * MatchGroup.SequentialMatch = 分组计算,不同组的优惠可叠加,不同组的优惠按组计算后求最大叠加优惠 * @return {BestMatch} */ public static BestMatch bestChoice(List<Rule> rules, List<Item> items, MatchType type, MatchGroup groupSetting) { BestMatch bestMatch = Calculator.calculate(rules, items,type, groupSetting); bindSuggestion(bestMatch); return bestMatch; } /** * 找出一组商品和和一堆规则的最佳组合匹配,即多个规则合作下优惠力度最大的匹配结果 * @param rules {Rule[]} * @param items {Item[]} * @param type {MatchType} * MatchType.OneTime = 匹配一次 * MatchType.OneRule = 匹配一个规则,但这个规则可以匹配多次 * MatchType.MultiRule = 可以匹配多个规则,每个规则可以匹配多次 * @return {BestMatch} */ public static BestMatch bestChoice(List<Rule> rules, List<Item> items, MatchType type) { return bestChoice(rules, items,type,MatchGroup.CrossedMatch); } /** * 找出一组商品和和一堆规则的最佳匹配,但只应用一条规则 * @param {Rule[]} rules * @param {Item[]} tickets * @return {MatchResult} */ @Deprecated public static BestMatch bestMatch(List<Rule> rules, List<Item> items) { return bestChoice(rules, items,MatchType.OneRule); } /** * 找出一组商品和和一堆规则的最佳匹配,即优惠力度最大的匹配结果 * 与bestMatch()的区别在于,不管当前选的商品可以拆成匹配多少次,都只按一次匹配来算优惠 * 匹配的张数是规则的最低要求,价值取最高价格 * @param {Rule[]} rules * @param {Item[]} tickets * @return {MatchResult} */ @Deprecated public static BestMatch bestOfOnlyOnceDiscount(List<Rule> rules, List<Item> items) { return bestChoice(rules, items,MatchType.OneTime); } private static void bindSuggestion(BestMatch best) { if (best != null) {
List<RuleValidateResult> ss = suggestions(best.getRules(), best.left());
8
2023-10-28 09:03:45+00:00
12k
llllllxy/tiny-jdbc-boot-starter
src/main/java/org/tinycloud/jdbc/sql/SqlGenerator.java
[ { "identifier": "Criteria", "path": "src/main/java/org/tinycloud/jdbc/criteria/Criteria.java", "snippet": "public class Criteria extends AbstractCriteria {\n\n public <R> Criteria lt(String field, R value) {\n String condition = \" AND \" + field + \" < \" + \"?\";\n conditions.add(cond...
import org.springframework.util.StringUtils; import org.tinycloud.jdbc.annotation.Column; import org.tinycloud.jdbc.annotation.Table; import org.tinycloud.jdbc.criteria.Criteria; import org.tinycloud.jdbc.criteria.LambdaCriteria; import org.tinycloud.jdbc.exception.JdbcException; import org.tinycloud.jdbc.annotation.IdType; import org.tinycloud.jdbc.id.IdUtils; import org.tinycloud.jdbc.util.ReflectUtils; import org.tinycloud.jdbc.util.Triple; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List;
10,267
package org.tinycloud.jdbc.sql; /** * sql生成器,通过传入的对象,将对象转为要执行的SQL,要绑定到SQL的参数 * * @author liuxingyu01 * @since 2023-07-28-16:49 **/ public class SqlGenerator { /** * 构建插入SQL * * @param object 入参 * @return 组装完毕的SqlProvider */ public static SqlProvider insertSql(Object object, boolean ignoreNulls) { Triple<Class<?>, Field[], Table> triple = ReflectUtils.validateTargetClass(object); Field[] fields = triple.getSecond(); Table tableAnnotation = triple.getThird(); StringBuilder sql = new StringBuilder(); List<Object> parameters = new ArrayList<>(); StringBuilder columns = new StringBuilder(); StringBuilder values = new StringBuilder(); for (Field field : fields) { ReflectUtils.makeAccessible(field); ReflectUtils.makeAccessible(field); Column columnAnnotation = field.getAnnotation(Column.class); if (columnAnnotation == null) { continue; } String column = columnAnnotation.value(); boolean primaryKey = columnAnnotation.primaryKey(); if (primaryKey) { IdType idType = columnAnnotation.idType(); if (idType == IdType.AUTO_INCREMENT) { // 自增主键直接跳过,无需处理 continue; } // 如果是其他主键策略,设置完主键后,塞回到实体类里,这样可以方便插入后获取主键值 if (idType == IdType.OBJECT_ID) {
package org.tinycloud.jdbc.sql; /** * sql生成器,通过传入的对象,将对象转为要执行的SQL,要绑定到SQL的参数 * * @author liuxingyu01 * @since 2023-07-28-16:49 **/ public class SqlGenerator { /** * 构建插入SQL * * @param object 入参 * @return 组装完毕的SqlProvider */ public static SqlProvider insertSql(Object object, boolean ignoreNulls) { Triple<Class<?>, Field[], Table> triple = ReflectUtils.validateTargetClass(object); Field[] fields = triple.getSecond(); Table tableAnnotation = triple.getThird(); StringBuilder sql = new StringBuilder(); List<Object> parameters = new ArrayList<>(); StringBuilder columns = new StringBuilder(); StringBuilder values = new StringBuilder(); for (Field field : fields) { ReflectUtils.makeAccessible(field); ReflectUtils.makeAccessible(field); Column columnAnnotation = field.getAnnotation(Column.class); if (columnAnnotation == null) { continue; } String column = columnAnnotation.value(); boolean primaryKey = columnAnnotation.primaryKey(); if (primaryKey) { IdType idType = columnAnnotation.idType(); if (idType == IdType.AUTO_INCREMENT) { // 自增主键直接跳过,无需处理 continue; } // 如果是其他主键策略,设置完主键后,塞回到实体类里,这样可以方便插入后获取主键值 if (idType == IdType.OBJECT_ID) {
Object fieldValue = IdUtils.objectId();
4
2023-10-25 14:44:59+00:00
12k
ansforge/SAMU-Hub-Modeles
src/test/java/com/hubsante/model/builders/CreateCaseWrapperBuilderTest.java
[ { "identifier": "EdxlHandler", "path": "src/main/java/com/hubsante/model/EdxlHandler.java", "snippet": "@Slf4j\npublic class EdxlHandler {\n\n private XmlMapper xmlMapper;\n\n private ObjectMapper jsonMapper;\n\n public EdxlHandler() {\n xmlMapper = (XmlMapper) new XmlMapper()\n ...
import static org.junit.jupiter.api.Assertions.assertThrows; import com.hubsante.model.EdxlHandler; import com.hubsante.model.cisu.CreateCase; import com.hubsante.model.cisu.CreateCaseWrapper; import com.hubsante.model.common.DistributionElement; import com.hubsante.model.common.Recipient; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.hubsante.model.utils.TestFileUtils.getMessageString; import static org.junit.jupiter.api.Assertions.assertEquals;
7,538
/** * Copyright © 2023-2024 Agence du Numerique en Sante (ANS) * * 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.hubsante.model.builders; public class CreateCaseWrapperBuilderTest { private final String MESSAGE_ID = "id-12345"; private final String SENDER_ID = "sender-x"; private final String RECIPIENT_ID = "recipient-y"; private EdxlHandler converter = new EdxlHandler(); @Test @DisplayName("should build a RC-EDA Message") public void shouldBuildRC_EDAMessage() throws IOException { Recipient recipient = new Recipient().name(RECIPIENT_ID).URI("hubex:" + RECIPIENT_ID); List<Recipient> recipientList = Stream.of(recipient).collect(Collectors.toList()); DistributionElement distributionElement = new DistributionElementBuilder(MESSAGE_ID, SENDER_ID, recipientList) .build(); CreateCaseWrapper createCaseWrapper = new CreateCaseWrapperBuilder(distributionElement, getCreateCaseMock()) .build(); assertEquals(MESSAGE_ID, createCaseWrapper.getMessageId()); assertEquals(getCreateCaseMock(), createCaseWrapper.getCreateCase()); } @Test @DisplayName("should not build a RC_EDA with invalid kind") public void shouldNotBuildRC_EDAWithInvalidKind() throws IOException { Recipient recipient = new Recipient().name(RECIPIENT_ID).URI("hubex:" + RECIPIENT_ID); List<Recipient> recipientList = Stream.of(recipient).collect(Collectors.toList()); DistributionElement distributionElement = new DistributionElementBuilder(MESSAGE_ID, SENDER_ID, recipientList) .kind(DistributionElement.KindEnum.ACK) .build(); assertThrows(IllegalArgumentException.class, () -> new CreateCaseWrapperBuilder(distributionElement, getCreateCaseMock()).build()); }
/** * Copyright © 2023-2024 Agence du Numerique en Sante (ANS) * * 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.hubsante.model.builders; public class CreateCaseWrapperBuilderTest { private final String MESSAGE_ID = "id-12345"; private final String SENDER_ID = "sender-x"; private final String RECIPIENT_ID = "recipient-y"; private EdxlHandler converter = new EdxlHandler(); @Test @DisplayName("should build a RC-EDA Message") public void shouldBuildRC_EDAMessage() throws IOException { Recipient recipient = new Recipient().name(RECIPIENT_ID).URI("hubex:" + RECIPIENT_ID); List<Recipient> recipientList = Stream.of(recipient).collect(Collectors.toList()); DistributionElement distributionElement = new DistributionElementBuilder(MESSAGE_ID, SENDER_ID, recipientList) .build(); CreateCaseWrapper createCaseWrapper = new CreateCaseWrapperBuilder(distributionElement, getCreateCaseMock()) .build(); assertEquals(MESSAGE_ID, createCaseWrapper.getMessageId()); assertEquals(getCreateCaseMock(), createCaseWrapper.getCreateCase()); } @Test @DisplayName("should not build a RC_EDA with invalid kind") public void shouldNotBuildRC_EDAWithInvalidKind() throws IOException { Recipient recipient = new Recipient().name(RECIPIENT_ID).URI("hubex:" + RECIPIENT_ID); List<Recipient> recipientList = Stream.of(recipient).collect(Collectors.toList()); DistributionElement distributionElement = new DistributionElementBuilder(MESSAGE_ID, SENDER_ID, recipientList) .kind(DistributionElement.KindEnum.ACK) .build(); assertThrows(IllegalArgumentException.class, () -> new CreateCaseWrapperBuilder(distributionElement, getCreateCaseMock()).build()); }
private CreateCase getCreateCaseMock() throws IOException {
1
2023-10-25 14:24:31+00:00
12k
yaroslav318/shop-telegram-bot
telegram-bot/src/main/java/ua/ivanzaitsev/bot/handlers/commands/CartCommandHandler.java
[ { "identifier": "CommandHandler", "path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/handlers/CommandHandler.java", "snippet": "public interface CommandHandler extends Handler {\n\n void executeCommand(AbsSender absSender, Update update, Long chatId) throws TelegramApiException;\n\n}" }, { ...
import java.util.Arrays; import java.util.List; import java.util.Set; 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.CallbackQuery; import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton; import org.telegram.telegrambots.meta.bots.AbsSender; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import ua.ivanzaitsev.bot.handlers.CommandHandler; import ua.ivanzaitsev.bot.handlers.UpdateHandler; import ua.ivanzaitsev.bot.handlers.commands.registries.CommandHandlerRegistry; import ua.ivanzaitsev.bot.models.domain.Button; import ua.ivanzaitsev.bot.models.domain.CartItem; import ua.ivanzaitsev.bot.models.domain.ClientOrder; import ua.ivanzaitsev.bot.models.domain.Command; import ua.ivanzaitsev.bot.models.domain.MessagePlaceholder; import ua.ivanzaitsev.bot.models.entities.Client; import ua.ivanzaitsev.bot.models.entities.Message; import ua.ivanzaitsev.bot.models.entities.Product; import ua.ivanzaitsev.bot.repositories.CartRepository; import ua.ivanzaitsev.bot.repositories.ClientCommandStateRepository; import ua.ivanzaitsev.bot.repositories.ClientOrderStateRepository; import ua.ivanzaitsev.bot.repositories.ClientRepository; import ua.ivanzaitsev.bot.services.MessageService;
7,315
if (currentCartPage >= cartItems.size() - 1) { currentCartPage = 0; } else { currentCartPage += 1; } cartRepository.updatePageNumberByChatId(chatId, currentCartPage); editCartMessage(absSender, chatId, messageId, cartItems, currentCartPage); } private void sendEmptyCartMessage(AbsSender absSender, Long chatId) throws TelegramApiException { SendMessage message = SendMessage.builder() .chatId(chatId) .text("Cart is empty.") .build(); absSender.execute(message); } private void editEmptyCartMessage(AbsSender absSender, Long chatId, Integer messageId) throws TelegramApiException { EditMessageText message = EditMessageText.builder() .chatId(chatId) .messageId(messageId) .text("Cart is empty.") .build(); absSender.execute(message); } private void editClearedCartMessage(AbsSender absSender, Long chatId, Integer messageId) throws TelegramApiException { EditMessageText message = EditMessageText.builder() .chatId(chatId) .messageId(messageId) .text("Cart cleared.") .build(); absSender.execute(message); } private void sendCartMessage(AbsSender absSender, Long chatId, List<CartItem> cartItems, int currentCartPage) throws TelegramApiException { SendMessage message = SendMessage.builder() .chatId(chatId) .text(createProductText(cartItems.get(currentCartPage))) .replyMarkup(createCartKeyboard(cartItems, currentCartPage)) .parseMode("HTML") .build(); absSender.execute(message); } private void editCartMessage(AbsSender absSender, Long chatId, Integer messageId, List<CartItem> cartItems, int currentCartPage) throws TelegramApiException { EditMessageText message = EditMessageText.builder() .chatId(chatId) .messageId(messageId) .text(createProductText(cartItems.get(currentCartPage))) .replyMarkup(createCartKeyboard(cartItems, currentCartPage)) .parseMode("HTML") .build(); absSender.execute(message); } private String createProductText(CartItem cartItem) { Message message = messageService.findByName("CART_MESSAGE"); if (cartItem != null) { Product product = cartItem.getProduct(); message.applyPlaceholder(MessagePlaceholder.of("%PRODUCT_NAME%", product.getName())); message.applyPlaceholder(MessagePlaceholder.of("%PRODUCT_DESCRIPTION%", product.getDescription())); message.applyPlaceholder(MessagePlaceholder.of("%PRODUCT_PRICE%", product.getPrice())); message.applyPlaceholder(MessagePlaceholder.of("%PRODUCT_QUANTITY%", cartItem.getQuantity())); message.applyPlaceholder( MessagePlaceholder.of("%PRODUCT_TOTAL_PRICE%", product.getPrice() * cartItem.getQuantity())); } return message.buildText(); } private InlineKeyboardMarkup createCartKeyboard(List<CartItem> cartItems, int currentCartPage) { ClientOrder clientOrder = new ClientOrder(); clientOrder.setCartItems(cartItems); InlineKeyboardMarkup.InlineKeyboardMarkupBuilder keyboardBuilder = InlineKeyboardMarkup.builder(); keyboardBuilder.keyboardRow(Arrays.asList( InlineKeyboardButton.builder().text("\u2716").callbackData(DELETE_PRODUCT_CALLBACK).build(), InlineKeyboardButton.builder().text("\u2796").callbackData(MINUS_PRODUCT_CALLBACK).build(), InlineKeyboardButton.builder().text(cartItems.get(currentCartPage).getQuantity() + " pcs.") .callbackData(PRODUCT_QUANTITY_CALLBACK).build(), InlineKeyboardButton.builder().text("\u2795").callbackData(PLUS_PRODUCT_CALLBACK).build() )); keyboardBuilder.keyboardRow(Arrays.asList( InlineKeyboardButton.builder().text("\u25c0").callbackData(PREVIOUS_PRODUCT_CALLBACK).build(), InlineKeyboardButton.builder().text((currentCartPage + 1) + "/" + cartItems.size()) .callbackData(CURRENT_PAGE_CALLBACK).build(), InlineKeyboardButton.builder().text("\u25b6").callbackData(NEXT_PRODUCT_CALLBACK).build() )); keyboardBuilder.keyboardRow(Arrays.asList( InlineKeyboardButton.builder() .text(String.format("\u2705 Order for %d $ Checkout?", clientOrder.calculateTotalPrice())) .callbackData(PROCESS_ORDER_CALLBACK).build() )); return keyboardBuilder.build(); } private void doProcessOrder(AbsSender absSender, Update update, Long chatId, Integer messageId) throws TelegramApiException { List<CartItem> cartItems = cartRepository.findAllCartItemsByChatId(chatId); if (cartItems.isEmpty()) { editEmptyCartMessage(absSender, chatId, messageId); return; } editProcessOrderMessage(absSender, chatId, messageId); saveClientOrderState(chatId, cartItems); executeNextCommand(absSender, update, chatId); } private void saveClientOrderState(Long chatId, List<CartItem> cartItems) {
package ua.ivanzaitsev.bot.handlers.commands; public class CartCommandHandler implements CommandHandler, UpdateHandler { private static final int MAX_QUANTITY_PER_PRODUCT = 50; private static final String PRODUCT_QUANTITY_CALLBACK = "cart=product-quantity"; private static final String CURRENT_PAGE_CALLBACK = "cart=current-page"; private static final String DELETE_PRODUCT_CALLBACK = "cart=delete-product"; private static final String MINUS_PRODUCT_CALLBACK = "cart=minus-product"; private static final String PLUS_PRODUCT_CALLBACK = "cart=plus-product"; private static final String PREVIOUS_PRODUCT_CALLBACK = "cart=previous-product"; private static final String NEXT_PRODUCT_CALLBACK = "cart=next-product"; private static final String PROCESS_ORDER_CALLBACK = "cart=process-order"; private static final Set<String> CALLBACKS = Set.of(DELETE_PRODUCT_CALLBACK, MINUS_PRODUCT_CALLBACK, PLUS_PRODUCT_CALLBACK, PREVIOUS_PRODUCT_CALLBACK, NEXT_PRODUCT_CALLBACK, PROCESS_ORDER_CALLBACK); private final CommandHandlerRegistry commandHandlerRegistry; private final ClientCommandStateRepository clientCommandStateRepository; private final ClientOrderStateRepository clientOrderStateRepository; private final CartRepository cartRepository; private final ClientRepository clientRepository; private final MessageService messageService; public CartCommandHandler( CommandHandlerRegistry commandHandlerRegistry, ClientCommandStateRepository clientCommandStateRepository, ClientOrderStateRepository clientOrderStateRepository, CartRepository cartRepository, ClientRepository clientRepository, MessageService messageService) { this.commandHandlerRegistry = commandHandlerRegistry; this.clientCommandStateRepository = clientCommandStateRepository; this.clientOrderStateRepository = clientOrderStateRepository; this.cartRepository = cartRepository; this.clientRepository = clientRepository; this.messageService = messageService; } @Override public Command getCommand() { return Command.CART; } @Override public void executeCommand(AbsSender absSender, Update update, Long chatId) throws TelegramApiException { handleCartMessageUpdate(absSender, chatId); } @Override public boolean canHandleUpdate(Update update) { return isCartMessageUpdate(update) || isCallbackQueryUpdate(update); } @Override public void handleUpdate(AbsSender absSender, Update update) throws TelegramApiException { if (isCartMessageUpdate(update)) { handleCartMessageUpdate(absSender, update.getMessage().getChatId()); } if (isCallbackQueryUpdate(update)) { handleCallbackQueryUpdate(absSender, update); } } private boolean isCartMessageUpdate(Update update) { return update.hasMessage() && update.getMessage().hasText() && update.getMessage().getText().equals(Button.CART.getAlias()); } private boolean isCallbackQueryUpdate(Update update) { return update.hasCallbackQuery() && CALLBACKS.contains(update.getCallbackQuery().getData()); } private void handleCartMessageUpdate(AbsSender absSender, Long chatId) throws TelegramApiException { List<CartItem> cartItems = cartRepository.findAllCartItemsByChatId(chatId); cartRepository.updatePageNumberByChatId(chatId, 0); if (cartItems.isEmpty()) { sendEmptyCartMessage(absSender, chatId); return; } sendCartMessage(absSender, chatId, cartItems, 0); } private void handleCallbackQueryUpdate(AbsSender absSender, Update update) throws TelegramApiException { CallbackQuery callbackQuery = update.getCallbackQuery(); Long chatId = callbackQuery.getMessage().getChatId(); Integer messageId = callbackQuery.getMessage().getMessageId(); String data = callbackQuery.getData(); if (DELETE_PRODUCT_CALLBACK.equals(data)) { doDeleteProduct(absSender, chatId, messageId); } if (MINUS_PRODUCT_CALLBACK.equals(data)) { doMinusProduct(absSender, chatId, messageId); } if (PLUS_PRODUCT_CALLBACK.equals(data)) { doPlusProduct(absSender, chatId, messageId); } if (PREVIOUS_PRODUCT_CALLBACK.equals(data)) { doPreviousProduct(absSender, chatId, messageId); } if (NEXT_PRODUCT_CALLBACK.equals(data)) { doNextProduct(absSender, chatId, messageId); } if (PROCESS_ORDER_CALLBACK.equals(data)) { doProcessOrder(absSender, update, chatId, messageId); } } private void doDeleteProduct(AbsSender absSender, Long chatId, Integer messageId) throws TelegramApiException { List<CartItem> cartItems = cartRepository.findAllCartItemsByChatId(chatId); int currentCartPage = cartRepository.findPageNumberByChatId(chatId); if (!cartItems.isEmpty()) { CartItem cartItem = cartItems.get(currentCartPage); if (cartItem != null) { cartItems.remove(cartItem); cartRepository.deleteCartItem(chatId, cartItem.getId()); } } if (cartItems.isEmpty()) { editClearedCartMessage(absSender, chatId, messageId); return; } if (cartItems.size() == currentCartPage) { currentCartPage -= 1; cartRepository.updatePageNumberByChatId(chatId, currentCartPage); } editCartMessage(absSender, chatId, messageId, cartItems, currentCartPage); } private void doMinusProduct(AbsSender absSender, Long chatId, Integer messageId) throws TelegramApiException { List<CartItem> cartItems = cartRepository.findAllCartItemsByChatId(chatId); int currentCartPage = cartRepository.findPageNumberByChatId(chatId); if (cartItems.isEmpty()) { editEmptyCartMessage(absSender, chatId, messageId); return; } CartItem cartItem = cartItems.get(currentCartPage); if (cartItem == null || cartItem.getQuantity() <= 1) { return; } cartItem.setQuantity(cartItem.getQuantity() - 1); cartRepository.updateCartItem(chatId, cartItem); editCartMessage(absSender, chatId, messageId, cartItems, currentCartPage); } private void doPlusProduct(AbsSender absSender, Long chatId, Integer messageId) throws TelegramApiException { List<CartItem> cartItems = cartRepository.findAllCartItemsByChatId(chatId); int currentCartPage = cartRepository.findPageNumberByChatId(chatId); if (cartItems.isEmpty()) { editEmptyCartMessage(absSender, chatId, messageId); return; } CartItem cartItem = cartItems.get(currentCartPage); if (cartItem == null || cartItem.getQuantity() >= MAX_QUANTITY_PER_PRODUCT) { return; } cartItem.setQuantity(cartItem.getQuantity() + 1); cartRepository.updateCartItem(chatId, cartItem); editCartMessage(absSender, chatId, messageId, cartItems, currentCartPage); } private void doPreviousProduct(AbsSender absSender, Long chatId, Integer messageId) throws TelegramApiException { List<CartItem> cartItems = cartRepository.findAllCartItemsByChatId(chatId); int currentCartPage = cartRepository.findPageNumberByChatId(chatId); if (cartItems.isEmpty()) { editEmptyCartMessage(absSender, chatId, messageId); return; } if (cartItems.size() == 1) { return; } if (currentCartPage <= 0) { currentCartPage = cartItems.size() - 1; } else { currentCartPage -= 1; } cartRepository.updatePageNumberByChatId(chatId, currentCartPage); editCartMessage(absSender, chatId, messageId, cartItems, currentCartPage); } private void doNextProduct(AbsSender absSender, Long chatId, Integer messageId) throws TelegramApiException { List<CartItem> cartItems = cartRepository.findAllCartItemsByChatId(chatId); int currentCartPage = cartRepository.findPageNumberByChatId(chatId); if (cartItems.isEmpty()) { editEmptyCartMessage(absSender, chatId, messageId); return; } if (cartItems.size() == 1) { return; } if (currentCartPage >= cartItems.size() - 1) { currentCartPage = 0; } else { currentCartPage += 1; } cartRepository.updatePageNumberByChatId(chatId, currentCartPage); editCartMessage(absSender, chatId, messageId, cartItems, currentCartPage); } private void sendEmptyCartMessage(AbsSender absSender, Long chatId) throws TelegramApiException { SendMessage message = SendMessage.builder() .chatId(chatId) .text("Cart is empty.") .build(); absSender.execute(message); } private void editEmptyCartMessage(AbsSender absSender, Long chatId, Integer messageId) throws TelegramApiException { EditMessageText message = EditMessageText.builder() .chatId(chatId) .messageId(messageId) .text("Cart is empty.") .build(); absSender.execute(message); } private void editClearedCartMessage(AbsSender absSender, Long chatId, Integer messageId) throws TelegramApiException { EditMessageText message = EditMessageText.builder() .chatId(chatId) .messageId(messageId) .text("Cart cleared.") .build(); absSender.execute(message); } private void sendCartMessage(AbsSender absSender, Long chatId, List<CartItem> cartItems, int currentCartPage) throws TelegramApiException { SendMessage message = SendMessage.builder() .chatId(chatId) .text(createProductText(cartItems.get(currentCartPage))) .replyMarkup(createCartKeyboard(cartItems, currentCartPage)) .parseMode("HTML") .build(); absSender.execute(message); } private void editCartMessage(AbsSender absSender, Long chatId, Integer messageId, List<CartItem> cartItems, int currentCartPage) throws TelegramApiException { EditMessageText message = EditMessageText.builder() .chatId(chatId) .messageId(messageId) .text(createProductText(cartItems.get(currentCartPage))) .replyMarkup(createCartKeyboard(cartItems, currentCartPage)) .parseMode("HTML") .build(); absSender.execute(message); } private String createProductText(CartItem cartItem) { Message message = messageService.findByName("CART_MESSAGE"); if (cartItem != null) { Product product = cartItem.getProduct(); message.applyPlaceholder(MessagePlaceholder.of("%PRODUCT_NAME%", product.getName())); message.applyPlaceholder(MessagePlaceholder.of("%PRODUCT_DESCRIPTION%", product.getDescription())); message.applyPlaceholder(MessagePlaceholder.of("%PRODUCT_PRICE%", product.getPrice())); message.applyPlaceholder(MessagePlaceholder.of("%PRODUCT_QUANTITY%", cartItem.getQuantity())); message.applyPlaceholder( MessagePlaceholder.of("%PRODUCT_TOTAL_PRICE%", product.getPrice() * cartItem.getQuantity())); } return message.buildText(); } private InlineKeyboardMarkup createCartKeyboard(List<CartItem> cartItems, int currentCartPage) { ClientOrder clientOrder = new ClientOrder(); clientOrder.setCartItems(cartItems); InlineKeyboardMarkup.InlineKeyboardMarkupBuilder keyboardBuilder = InlineKeyboardMarkup.builder(); keyboardBuilder.keyboardRow(Arrays.asList( InlineKeyboardButton.builder().text("\u2716").callbackData(DELETE_PRODUCT_CALLBACK).build(), InlineKeyboardButton.builder().text("\u2796").callbackData(MINUS_PRODUCT_CALLBACK).build(), InlineKeyboardButton.builder().text(cartItems.get(currentCartPage).getQuantity() + " pcs.") .callbackData(PRODUCT_QUANTITY_CALLBACK).build(), InlineKeyboardButton.builder().text("\u2795").callbackData(PLUS_PRODUCT_CALLBACK).build() )); keyboardBuilder.keyboardRow(Arrays.asList( InlineKeyboardButton.builder().text("\u25c0").callbackData(PREVIOUS_PRODUCT_CALLBACK).build(), InlineKeyboardButton.builder().text((currentCartPage + 1) + "/" + cartItems.size()) .callbackData(CURRENT_PAGE_CALLBACK).build(), InlineKeyboardButton.builder().text("\u25b6").callbackData(NEXT_PRODUCT_CALLBACK).build() )); keyboardBuilder.keyboardRow(Arrays.asList( InlineKeyboardButton.builder() .text(String.format("\u2705 Order for %d $ Checkout?", clientOrder.calculateTotalPrice())) .callbackData(PROCESS_ORDER_CALLBACK).build() )); return keyboardBuilder.build(); } private void doProcessOrder(AbsSender absSender, Update update, Long chatId, Integer messageId) throws TelegramApiException { List<CartItem> cartItems = cartRepository.findAllCartItemsByChatId(chatId); if (cartItems.isEmpty()) { editEmptyCartMessage(absSender, chatId, messageId); return; } editProcessOrderMessage(absSender, chatId, messageId); saveClientOrderState(chatId, cartItems); executeNextCommand(absSender, update, chatId); } private void saveClientOrderState(Long chatId, List<CartItem> cartItems) {
Client client = clientRepository.findByChatId(chatId);
8
2023-10-29 15:49:41+00:00
12k
MikiP98/HumilityAFM
src/main/java/io/github/mikip98/HumilityAFM.java
[ { "identifier": "ConfigJSON", "path": "src/main/java/io/github/mikip98/config/ConfigJSON.java", "snippet": "public class ConfigJSON {\n\n // Save the configuration to a JSON file in the Minecraft configuration folder\n public static void saveConfigToFile() {\n Gson gson = new GsonBuilder()....
import io.github.mikip98.config.ConfigJSON; import io.github.mikip98.config.ModConfig; import io.github.mikip98.content.blockentities.LEDBlockEntity; import io.github.mikip98.content.blockentities.cabinetBlock.IlluminatedCabinetBlockEntity; import io.github.mikip98.content.blocks.JustHorizontalFacingBlock; import io.github.mikip98.content.blocks.leds.LEDBlock; import io.github.mikip98.content.blocks.stairs.InnerStairs; import io.github.mikip98.content.blocks.stairs.OuterStairs; import io.github.mikip98.content.blocks.cabinet.CabinetBlock; import io.github.mikip98.content.blocks.cabinet.IlluminatedCabinetBlock; import io.github.mikip98.helpers.*; import net.fabricmc.api.ModInitializer; import net.fabricmc.fabric.api.item.v1.FabricItemSettings; import net.fabricmc.fabric.api.itemgroup.v1.FabricItemGroup; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.entity.FabricBlockEntityTypeBuilder; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.block.Block; import net.minecraft.block.entity.BlockEntityType; import net.minecraft.item.*; import net.minecraft.registry.Registries; import net.minecraft.registry.Registry; import net.minecraft.sound.BlockSoundGroup; import net.minecraft.text.Text; import net.minecraft.util.Identifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.github.mikip98.content.blockentities.cabinetBlock.CabinetBlockEntity; import java.io.File; import java.nio.file.Path; import static net.fabricmc.loader.api.FabricLoader.getInstance;
9,900
package io.github.mikip98; public class HumilityAFM implements ModInitializer { // This logger is used to write text to the console and the log file. // It is considered best practice to use your mod id as the logger's name. // That way, it's clear which mod wrote info, warnings, and errors. public static final String MOD_ID = "humility-afm"; public static final String MOD_NAME = "Humility AFM"; public static final String MOD_CAMEL = "HumilityAFM"; public static final Logger LOGGER = LoggerFactory.getLogger(MOD_CAMEL); //Cabinet block private static final float CabinetBlockStrength = 2.0f; private static final FabricBlockSettings CabinetBlockSettings = FabricBlockSettings.create().strength(CabinetBlockStrength).requiresTool().nonOpaque(); public static final CabinetBlock CABINET_BLOCK = new CabinetBlock(CabinetBlockSettings); public static final Item CABINET_BLOCK_ITEM = new BlockItem(CABINET_BLOCK, new FabricItemSettings()); private static final FabricBlockSettings IlluminatedCabinetBlockSettings = CabinetBlockSettings.luminance(2); public static final IlluminatedCabinetBlock ILLUMINATED_CABINET_BLOCK = new IlluminatedCabinetBlock(IlluminatedCabinetBlockSettings); //Cabinet block entity public static BlockEntityType<CabinetBlockEntity> CABINET_BLOCK_ENTITY; public static BlockEntityType<IlluminatedCabinetBlockEntity> ILLUMINATED_CABINET_BLOCK_ENTITY; // LED block entity public static BlockEntityType<LEDBlockEntity> LED_BLOCK_ENTITY; // Stairs private static final float WoodenStairsBlockStrength = 2.0f; private static final FabricBlockSettings StairsBlockSettings = FabricBlockSettings.create().strength(WoodenStairsBlockStrength).requiresTool(); public static final Block OUTER_STAIRS = new OuterStairs(StairsBlockSettings); public static final Block INNER_STAIRS = new InnerStairs(StairsBlockSettings); public static final Item OUTER_STAIRS_ITEM = new BlockItem(OUTER_STAIRS, new FabricItemSettings()); public static final Item INNER_STAIRS_ITEM = new BlockItem(INNER_STAIRS, new FabricItemSettings()); // Wooden mosaic private static final float WoodenMosaicStrength = 3.0f * 1.5f; private static final FabricBlockSettings WoodenMosaicSettings = FabricBlockSettings.create().strength(WoodenMosaicStrength).requiresTool().sounds(BlockSoundGroup.WOOD); public static final Block WOODEN_MOSAIC = new Block(WoodenMosaicSettings); public static final Item WOODEN_MOSAIC_ITEM = new BlockItem(WOODEN_MOSAIC, new FabricItemSettings()); // LED public static Block LED_BLOCK; public static Item LED_ITEM; // Candlestick // public static Block CANDLESTICK = new JustHorizontalFacingBlock(FabricBlockSettings.create().strength(0.5f).nonOpaque()); // public static Item CANDLESTICK_ITEM = new BlockItem(CANDLESTICK, new FabricItemSettings()); private Block[] getCabinetBlockVariantsToRegisterBlockEntity() { final Block[] cabinetBlockVariants = CabinetBlockHelper.cabinetBlockVariants; Block[] blocks = new Block[cabinetBlockVariants.length + 1]; blocks[0] = CABINET_BLOCK; System.arraycopy(cabinetBlockVariants, 0, blocks, 1, cabinetBlockVariants.length); return blocks; } private Block[] getIlluminatedCabinetBlockVariantsToRegisterBlockEntity() { final Block[] illuminatedCabinetBlockVariants = CabinetBlockHelper.illuminatedCabinetBlockVariants; Block[] blocks = new Block[illuminatedCabinetBlockVariants.length + 1]; blocks[0] = ILLUMINATED_CABINET_BLOCK; System.arraycopy(illuminatedCabinetBlockVariants, 0, blocks, 1, illuminatedCabinetBlockVariants.length); return blocks; } @Override public void onInitialize() { // This code runs as soon as Minecraft is in a mod-load-ready state. // However, some things (like resources) may still be uninitialized. // Proceed with mild caution. // ------------------------------------ INITIALIZATION ------------------------------------ LOGGER.info(MOD_NAME + " is initializing!");
package io.github.mikip98; public class HumilityAFM implements ModInitializer { // This logger is used to write text to the console and the log file. // It is considered best practice to use your mod id as the logger's name. // That way, it's clear which mod wrote info, warnings, and errors. public static final String MOD_ID = "humility-afm"; public static final String MOD_NAME = "Humility AFM"; public static final String MOD_CAMEL = "HumilityAFM"; public static final Logger LOGGER = LoggerFactory.getLogger(MOD_CAMEL); //Cabinet block private static final float CabinetBlockStrength = 2.0f; private static final FabricBlockSettings CabinetBlockSettings = FabricBlockSettings.create().strength(CabinetBlockStrength).requiresTool().nonOpaque(); public static final CabinetBlock CABINET_BLOCK = new CabinetBlock(CabinetBlockSettings); public static final Item CABINET_BLOCK_ITEM = new BlockItem(CABINET_BLOCK, new FabricItemSettings()); private static final FabricBlockSettings IlluminatedCabinetBlockSettings = CabinetBlockSettings.luminance(2); public static final IlluminatedCabinetBlock ILLUMINATED_CABINET_BLOCK = new IlluminatedCabinetBlock(IlluminatedCabinetBlockSettings); //Cabinet block entity public static BlockEntityType<CabinetBlockEntity> CABINET_BLOCK_ENTITY; public static BlockEntityType<IlluminatedCabinetBlockEntity> ILLUMINATED_CABINET_BLOCK_ENTITY; // LED block entity public static BlockEntityType<LEDBlockEntity> LED_BLOCK_ENTITY; // Stairs private static final float WoodenStairsBlockStrength = 2.0f; private static final FabricBlockSettings StairsBlockSettings = FabricBlockSettings.create().strength(WoodenStairsBlockStrength).requiresTool(); public static final Block OUTER_STAIRS = new OuterStairs(StairsBlockSettings); public static final Block INNER_STAIRS = new InnerStairs(StairsBlockSettings); public static final Item OUTER_STAIRS_ITEM = new BlockItem(OUTER_STAIRS, new FabricItemSettings()); public static final Item INNER_STAIRS_ITEM = new BlockItem(INNER_STAIRS, new FabricItemSettings()); // Wooden mosaic private static final float WoodenMosaicStrength = 3.0f * 1.5f; private static final FabricBlockSettings WoodenMosaicSettings = FabricBlockSettings.create().strength(WoodenMosaicStrength).requiresTool().sounds(BlockSoundGroup.WOOD); public static final Block WOODEN_MOSAIC = new Block(WoodenMosaicSettings); public static final Item WOODEN_MOSAIC_ITEM = new BlockItem(WOODEN_MOSAIC, new FabricItemSettings()); // LED public static Block LED_BLOCK; public static Item LED_ITEM; // Candlestick // public static Block CANDLESTICK = new JustHorizontalFacingBlock(FabricBlockSettings.create().strength(0.5f).nonOpaque()); // public static Item CANDLESTICK_ITEM = new BlockItem(CANDLESTICK, new FabricItemSettings()); private Block[] getCabinetBlockVariantsToRegisterBlockEntity() { final Block[] cabinetBlockVariants = CabinetBlockHelper.cabinetBlockVariants; Block[] blocks = new Block[cabinetBlockVariants.length + 1]; blocks[0] = CABINET_BLOCK; System.arraycopy(cabinetBlockVariants, 0, blocks, 1, cabinetBlockVariants.length); return blocks; } private Block[] getIlluminatedCabinetBlockVariantsToRegisterBlockEntity() { final Block[] illuminatedCabinetBlockVariants = CabinetBlockHelper.illuminatedCabinetBlockVariants; Block[] blocks = new Block[illuminatedCabinetBlockVariants.length + 1]; blocks[0] = ILLUMINATED_CABINET_BLOCK; System.arraycopy(illuminatedCabinetBlockVariants, 0, blocks, 1, illuminatedCabinetBlockVariants.length); return blocks; } @Override public void onInitialize() { // This code runs as soon as Minecraft is in a mod-load-ready state. // However, some things (like resources) may still be uninitialized. // Proceed with mild caution. // ------------------------------------ INITIALIZATION ------------------------------------ LOGGER.info(MOD_NAME + " is initializing!");
ConfigJSON.loadConfigFromFile();
0
2023-10-30 12:11:22+00:00
12k
HeitorLouzeiro/gerenciador-disciplinas-java
core/src/main/java/com/project/Menu/MenuItens/Listar.java
[ { "identifier": "AlunoDAO", "path": "core/src/main/java/com/project/Dao/AlunoDAO.java", "snippet": "public class AlunoDAO {\n \n /**\n * Conexão com o banco de dados.\n */\n private Connection connection;\n\n /**\n * Construtor da classe AlunoDAO.\n * Inicializa a conexão com...
import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.project.Dao.AlunoDAO; import com.project.Dao.CursoDAO; import com.project.Dao.DisciplinasDAO; import com.project.Dao.FrequenciaDAO; import com.project.Dao.IFPIDAO; import com.project.Dao.NotasDAO; import com.project.Dao.ProfessorDAO; import com.project.Dao.SecretarioDAO;
7,944
package com.project.Menu.MenuItens; /** * Classe responsável por fornecer métodos para listar informações do sistema. * * @Author @HeitorLouzeiro */ public class Listar { static class Space { static String space = "-----------------------------------------------------"; } /** * Lista todos os cursos disponíveis para um determinado usuário. * * @param codUsuario O código do usuário para o qual os cursos serão listados. * @throws IOException Se ocorrer um erro de I/O durante a execução. */ public void listarCursos(int codUsuario) throws IOException{ CursoDAO cursoDAO = new CursoDAO(); try { System.out.println("Listando todos os cursos..."); cursoDAO.mostrarCursos(codUsuario); System.out.println(Space.space); } catch (SQLException e) { e.printStackTrace(); } } // Listar todos os alunos public void listarAlunos() throws IOException {
package com.project.Menu.MenuItens; /** * Classe responsável por fornecer métodos para listar informações do sistema. * * @Author @HeitorLouzeiro */ public class Listar { static class Space { static String space = "-----------------------------------------------------"; } /** * Lista todos os cursos disponíveis para um determinado usuário. * * @param codUsuario O código do usuário para o qual os cursos serão listados. * @throws IOException Se ocorrer um erro de I/O durante a execução. */ public void listarCursos(int codUsuario) throws IOException{ CursoDAO cursoDAO = new CursoDAO(); try { System.out.println("Listando todos os cursos..."); cursoDAO.mostrarCursos(codUsuario); System.out.println(Space.space); } catch (SQLException e) { e.printStackTrace(); } } // Listar todos os alunos public void listarAlunos() throws IOException {
SecretarioDAO secretarioDAO = new SecretarioDAO();
7
2023-10-30 18:29:39+00:00
12k
llllllxy/tiny-security-boot-starter
src/main/java/org/tinycloud/security/AuthAutoConfiguration.java
[ { "identifier": "AuthenticeInterceptor", "path": "src/main/java/org/tinycloud/security/interceptor/AuthenticeInterceptor.java", "snippet": "public class AuthenticeInterceptor extends HandlerInterceptorAdapter {\n\n /**\n * 存储会话的接口\n */\n private AuthProvider authProvider;\n\n public Aut...
import org.tinycloud.security.interceptor.AuthenticeInterceptor; import org.tinycloud.security.interceptor.PermissionInterceptor; import org.tinycloud.security.interfaces.PermissionInfoInterface; import org.tinycloud.security.provider.AuthProvider; import org.tinycloud.security.provider.JdbcAuthProvider; import org.tinycloud.security.provider.RedisAuthProvider; import org.tinycloud.security.provider.SingleAuthProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.jdbc.core.JdbcTemplate;
8,957
package org.tinycloud.security; /** * <p> * tiny-security 自动配置类 * </p> * * @author liuxingyu01 * @since 2022-12-13 11:45 **/ @Configuration @EnableConfigurationProperties(AuthProperties.class) public class AuthAutoConfiguration { final static Logger logger = LoggerFactory.getLogger(AuthAutoConfiguration.class); @Autowired private AuthProperties authProperties; /** * 注入redisAuthProvider */ @ConditionalOnMissingBean(AuthProvider.class) @ConditionalOnProperty(name = "tiny-security.store-type", havingValue = "redis") @Bean public AuthProvider redisAuthProvider(StringRedisTemplate stringRedisTemplate) { if (stringRedisTemplate == null) { logger.error("AuthAutoConfiguration: Bean StringRedisTemplate is null!"); return null; } logger.info("RedisAuthProvider is running!"); return new RedisAuthProvider(stringRedisTemplate, authProperties); } /** * 注入jdbcAuthProvider */ @ConditionalOnMissingBean(AuthProvider.class) @ConditionalOnProperty(name = "tiny-security.store-type", havingValue = "jdbc") @Bean public AuthProvider jdbcAuthProvider(JdbcTemplate jdbcTemplate) { if (jdbcTemplate == null) { logger.error("AuthAutoConfiguration: Bean JdbcTemplate is null!"); return null; } logger.info("JdbcAuthProvider is running!");
package org.tinycloud.security; /** * <p> * tiny-security 自动配置类 * </p> * * @author liuxingyu01 * @since 2022-12-13 11:45 **/ @Configuration @EnableConfigurationProperties(AuthProperties.class) public class AuthAutoConfiguration { final static Logger logger = LoggerFactory.getLogger(AuthAutoConfiguration.class); @Autowired private AuthProperties authProperties; /** * 注入redisAuthProvider */ @ConditionalOnMissingBean(AuthProvider.class) @ConditionalOnProperty(name = "tiny-security.store-type", havingValue = "redis") @Bean public AuthProvider redisAuthProvider(StringRedisTemplate stringRedisTemplate) { if (stringRedisTemplate == null) { logger.error("AuthAutoConfiguration: Bean StringRedisTemplate is null!"); return null; } logger.info("RedisAuthProvider is running!"); return new RedisAuthProvider(stringRedisTemplate, authProperties); } /** * 注入jdbcAuthProvider */ @ConditionalOnMissingBean(AuthProvider.class) @ConditionalOnProperty(name = "tiny-security.store-type", havingValue = "jdbc") @Bean public AuthProvider jdbcAuthProvider(JdbcTemplate jdbcTemplate) { if (jdbcTemplate == null) { logger.error("AuthAutoConfiguration: Bean JdbcTemplate is null!"); return null; } logger.info("JdbcAuthProvider is running!");
return new JdbcAuthProvider(jdbcTemplate, authProperties);
4
2023-10-26 08:13:08+00:00
12k
0-Gixty-0/Grupp-11-OOPP
sailinggame/src/test/java/modeltest/modelinitialization/AICommanderTest.java
[ { "identifier": "EntityDirector", "path": "sailinggame/src/main/java/com/group11/model/builders/EntityDirector.java", "snippet": "public class EntityDirector {\n private IEntityBuilder builder;\n\n public EntityDirector(IEntityBuilder builder) {\n this.builder = builder;\n }\n\n /**\n...
import com.group11.model.builders.EntityDirector; import com.group11.model.builders.ShipBuilder; import com.group11.model.gameentites.AEntity; import com.group11.model.gameentites.CommandableEntity; import com.group11.model.gameworld.ATile; import com.group11.model.gameworld.LandTile; import com.group11.model.gameworld.SeaTile; import com.group11.model.modelinitialization.AICommander; import com.group11.model.utility.UMovement; import com.group11.model.utility.UViewTileMatrixDecoder; import com.group11.model.utility.UEntityMatrixGenerator; import org.junit.Before; import org.junit.Test; import java.awt.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static junit.framework.TestCase.assertEquals;
7,510
package modeltest.modelinitialization; public class AICommanderTest { private List<List<Integer>> grid = new ArrayList<>(); private List<List<ATile>> terrainMatrix = new ArrayList<>(); private EntityDirector director = new EntityDirector(new ShipBuilder()); private List<AEntity> entities = new ArrayList<>(); private List<List<AEntity>> entityMatrix = UEntityMatrixGenerator.createEntityMatrix(5,5, entities); private class TestAICommander extends AICommander { public TestAICommander(List<List<AEntity>> entityMatrix, List<List<ATile>> terrainMatrix) { super(entityMatrix); super.innerRadius = 1; } } @Before public void beforePreconditions() { this.grid.add(Arrays.asList(1,1,0,1,1)); this.grid.add(Arrays.asList(1,0,1,0,1)); this.grid.add(Arrays.asList(1,1,1,1,1)); this.grid.add(Arrays.asList(1,0,1,0,1)); this.grid.add(Arrays.asList(1,1,0,1,1)); ArrayList<ATile> tileRow = new ArrayList<>(); tileRow.add(new SeaTile(new Point(0,0))); tileRow.add(new SeaTile(new Point(0,1))); tileRow.add(new LandTile(new Point(0,2))); tileRow.add(new SeaTile(new Point(0,3))); tileRow.add(new SeaTile(new Point(0,4))); this.terrainMatrix.add(tileRow); tileRow = new ArrayList<>(); tileRow.add(new SeaTile(new Point(1,0))); tileRow.add(new LandTile(new Point(1,1))); tileRow.add(new SeaTile(new Point(1,2))); tileRow.add(new LandTile(new Point(1,3))); tileRow.add(new SeaTile(new Point(1,4))); this.terrainMatrix.add(tileRow); tileRow = new ArrayList<>(); tileRow.add(new SeaTile(new Point(2,0))); tileRow.add(new SeaTile(new Point(2,1))); tileRow.add(new SeaTile(new Point(2,2))); tileRow.add(new SeaTile(new Point(2,3))); tileRow.add(new SeaTile(new Point(2,4))); this.terrainMatrix.add(tileRow); tileRow = new ArrayList<>(); tileRow.add(new SeaTile(new Point(3,0))); tileRow.add(new LandTile(new Point(3,1))); tileRow.add(new SeaTile(new Point(3,2))); tileRow.add(new LandTile(new Point(3,3))); tileRow.add(new SeaTile(new Point(3,4))); this.terrainMatrix.add(tileRow); tileRow = new ArrayList<>(); tileRow.add(new SeaTile(new Point(0,0))); tileRow.add(new SeaTile(new Point(0,1))); tileRow.add(new LandTile(new Point(0,2))); tileRow.add(new SeaTile(new Point(0,3))); tileRow.add(new SeaTile(new Point(0,4))); this.terrainMatrix.add(tileRow); UMovement.setTileMatrix(this.terrainMatrix); UViewTileMatrixDecoder.setTilematrix(terrainMatrix); } @Test public void testEnemyMovesUp() {
package modeltest.modelinitialization; public class AICommanderTest { private List<List<Integer>> grid = new ArrayList<>(); private List<List<ATile>> terrainMatrix = new ArrayList<>(); private EntityDirector director = new EntityDirector(new ShipBuilder()); private List<AEntity> entities = new ArrayList<>(); private List<List<AEntity>> entityMatrix = UEntityMatrixGenerator.createEntityMatrix(5,5, entities); private class TestAICommander extends AICommander { public TestAICommander(List<List<AEntity>> entityMatrix, List<List<ATile>> terrainMatrix) { super(entityMatrix); super.innerRadius = 1; } } @Before public void beforePreconditions() { this.grid.add(Arrays.asList(1,1,0,1,1)); this.grid.add(Arrays.asList(1,0,1,0,1)); this.grid.add(Arrays.asList(1,1,1,1,1)); this.grid.add(Arrays.asList(1,0,1,0,1)); this.grid.add(Arrays.asList(1,1,0,1,1)); ArrayList<ATile> tileRow = new ArrayList<>(); tileRow.add(new SeaTile(new Point(0,0))); tileRow.add(new SeaTile(new Point(0,1))); tileRow.add(new LandTile(new Point(0,2))); tileRow.add(new SeaTile(new Point(0,3))); tileRow.add(new SeaTile(new Point(0,4))); this.terrainMatrix.add(tileRow); tileRow = new ArrayList<>(); tileRow.add(new SeaTile(new Point(1,0))); tileRow.add(new LandTile(new Point(1,1))); tileRow.add(new SeaTile(new Point(1,2))); tileRow.add(new LandTile(new Point(1,3))); tileRow.add(new SeaTile(new Point(1,4))); this.terrainMatrix.add(tileRow); tileRow = new ArrayList<>(); tileRow.add(new SeaTile(new Point(2,0))); tileRow.add(new SeaTile(new Point(2,1))); tileRow.add(new SeaTile(new Point(2,2))); tileRow.add(new SeaTile(new Point(2,3))); tileRow.add(new SeaTile(new Point(2,4))); this.terrainMatrix.add(tileRow); tileRow = new ArrayList<>(); tileRow.add(new SeaTile(new Point(3,0))); tileRow.add(new LandTile(new Point(3,1))); tileRow.add(new SeaTile(new Point(3,2))); tileRow.add(new LandTile(new Point(3,3))); tileRow.add(new SeaTile(new Point(3,4))); this.terrainMatrix.add(tileRow); tileRow = new ArrayList<>(); tileRow.add(new SeaTile(new Point(0,0))); tileRow.add(new SeaTile(new Point(0,1))); tileRow.add(new LandTile(new Point(0,2))); tileRow.add(new SeaTile(new Point(0,3))); tileRow.add(new SeaTile(new Point(0,4))); this.terrainMatrix.add(tileRow); UMovement.setTileMatrix(this.terrainMatrix); UViewTileMatrixDecoder.setTilematrix(terrainMatrix); } @Test public void testEnemyMovesUp() {
ArrayList<CommandableEntity> enemyList = new ArrayList<>();
3
2023-10-31 11:40:56+00:00
12k
nailuj1992/OracionesCatolicas
app/src/main/java/com/prayers/app/activity/rosary/RosaryCurrentMysteryActivity.java
[ { "identifier": "AbstractClosableActivity", "path": "app/src/main/java/com/prayers/app/activity/AbstractClosableActivity.java", "snippet": "public abstract class AbstractClosableActivity extends AbstractActivity {\n\n private Button btnHome;\n\n /**\n * Prepare all view fields.\n */\n p...
import android.os.Bundle; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import com.prayers.app.activity.AbstractClosableActivity; import com.prayers.app.activity.R; import com.prayers.app.constants.GeneralConstants; import com.prayers.app.constants.RedirectionConstants; import com.prayers.app.mapper.RosaryMapper; import com.prayers.app.model.rosary.Mysteries; import com.prayers.app.model.rosary.Mystery; import com.prayers.app.ui.adapter.RosaryMysteryAdapter; import com.prayers.app.utils.FieldsUtils; import com.prayers.app.utils.RedirectionUtils;
7,488
package com.prayers.app.activity.rosary; public class RosaryCurrentMysteryActivity extends AbstractClosableActivity { private Mysteries selectedMysteries; private int selectedMystery; private Mystery mystery; private TextView txtTitleCurrentMystery; private TextView txtTextCurrentMystery; private RecyclerView viewParagraphs; private ImageView imgMysteriesBackground; private Button btnPrev; private Button btnNext; @Override public int getActivity() { return R.layout.rosary_current_mystery_activity; } @Override public void prepareOthersActivity() { txtTitleCurrentMystery = (TextView) findViewById(R.id.title_rosary_current_mystery); txtTextCurrentMystery = (TextView) findViewById(R.id.txt_rosary_current_mystery);
package com.prayers.app.activity.rosary; public class RosaryCurrentMysteryActivity extends AbstractClosableActivity { private Mysteries selectedMysteries; private int selectedMystery; private Mystery mystery; private TextView txtTitleCurrentMystery; private TextView txtTextCurrentMystery; private RecyclerView viewParagraphs; private ImageView imgMysteriesBackground; private Button btnPrev; private Button btnNext; @Override public int getActivity() { return R.layout.rosary_current_mystery_activity; } @Override public void prepareOthersActivity() { txtTitleCurrentMystery = (TextView) findViewById(R.id.title_rosary_current_mystery); txtTextCurrentMystery = (TextView) findViewById(R.id.txt_rosary_current_mystery);
viewParagraphs = FieldsUtils.configureRecyclerView(this, R.id.view_paragraphs);
7
2023-10-25 17:17:47+00:00
12k
LeoK99/swtw45WS21_reupload
src/main/java/com/buschmais/frontend/views/user/UserView.java
[ { "identifier": "ImageDao", "path": "src/main/java/com/buschmais/backend/image/ImageDao.java", "snippet": "@Service\npublic class ImageDao {\n\n\tprivate final GridFsTemplate gridFsTemplate;\n\tprivate final GridFsOperations operations;\n\tprivate final ImageRepository imageRepository;\n\n\t@Autowired\n...
import com.buschmais.backend.image.ImageDao; import com.buschmais.backend.users.User; import com.buschmais.backend.users.dataAccess.UserDao; import com.buschmais.frontend.broadcasting.BroadcastListener; import com.buschmais.frontend.broadcasting.Broadcaster; import com.buschmais.frontend.components.ErrorNotification; import com.buschmais.frontend.components.SuccessNotification; import com.buschmais.frontend.vars.NumberConstantsFrontend; import com.buschmais.frontend.vars.StringConstantsFrontend; import com.vaadin.flow.component.DetachEvent; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.dependency.CssImport; import com.vaadin.flow.component.html.Image; import com.vaadin.flow.component.html.Label; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.textfield.PasswordField; import com.vaadin.flow.component.textfield.TextField; import com.vaadin.flow.component.upload.Upload; import com.vaadin.flow.component.upload.receivers.FileBuffer; import com.vaadin.flow.dom.DomEventListener; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.server.StreamResource; import lombok.NonNull; import org.springframework.beans.factory.annotation.Autowired; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Optional;
8,435
package com.buschmais.frontend.views.user; //@Route(value = StringConstantsFrontend.USER_PATH, layout = MainLayout.class) @CssImport(value = "./themes/adr-workbench/vaadin-components/buttons.css") @CssImport(value = "./themes/adr-workbench/user/user.css") @CssImport(value = "./themes/adr-workbench/vaadin-components/vaadin-text-field-styles.css", themeFor = "vaadin-text-field vaadin-password-field") @PageTitle("User") public class UserView extends VerticalLayout implements BroadcastListener { // TODO: Check about all passwords attributes (Password Hash - clear password), beautifying and error handling /* Property enum */ private enum Property { USER_NAME("Benutzername"), PASSWORD("Passwort"), PROFILE_PICTURE("Profilbild"); private final String name; private final static List<Property> changedProperties = new ArrayList<>(); private boolean hasChanged = false; private boolean isReadyToSave = false; Property(String name) { this.name = name; } public String getName() { return this.name; } public boolean hasChanged() { return this.hasChanged; } public boolean isReadyToSave() { return this.isReadyToSave; } public void setHasChanged(boolean hasChanged) { this.hasChanged = hasChanged; if (hasChanged) { changedProperties.add(this); } else { changedProperties.remove(this); } } public void setReadyToSave(boolean readyToSave) { this.isReadyToSave = readyToSave; } } // buttons private Button editButton; private Button saveButton; private Button cancelButton; // text-fields private TextField userNameTextField; private PasswordField newPasswordField; private PasswordField currentPasswortField; private Label changePasswordLabel; // layouts private VerticalLayout userNameLayout; private VerticalLayout changePasswordLayout; private VerticalLayout profilePictureLayout; private VerticalLayout buttonLayout; // confirm dialog private com.buschmais.frontend.components.ConfirmDialog cancelButtonConfirmDialog; // other class instances private final UserDao userDao; private final ImageDao imageDao; private final ImageCtx imageCtx; public UserView(@Autowired UserDao userDao, @Autowired ImageDao imageDao) { this.userDao = userDao; this.imageDao = imageDao; synchronized (this.userDao){ Optional<User> found_user = userDao.findByUserName(userDao.getCurrentUser().getUserName()); found_user.ifPresent(userDao::setCurrentUser); imageCtx = new ImageCtx(this.userDao, this.imageDao); Property.changedProperties.clear(); setupComponents(); createDefaultLayout(); // Attach listeners for broadcasting and detachment Broadcaster.registerListener(this); addDetachListener((DetachEvent e) -> Broadcaster.unregisterListener(this)); } } /** * This method creates the instances of the components and adds classnames to them. * Additionally it changes properties of a component. */ private void setupComponents() { /* Create Instances */ //labels Label userNameLabel; Label profilePictureLabel; { // username-field, password field this.userNameTextField = new TextField(); this.newPasswordField = new PasswordField("Neues Passwort"); this.currentPasswortField = new PasswordField("Aktuelles Passwort"); // all buttons this.editButton = new Button(StringConstantsFrontend.USERVIEW_BUTTON_EDIT_PROFILE); this.saveButton = new Button(StringConstantsFrontend.GENERAL_DIALOG_BUTTON_SAVE); this.cancelButton = new Button(StringConstantsFrontend.GENERAL_DIALOG_BUTTON_CANCEL); // labels userNameLabel = new Label(StringConstantsFrontend.GENERAL_USERNAME_TEXT); this.changePasswordLabel = new Label(StringConstantsFrontend.USERVIEW_CHANGE_PASSWORD); profilePictureLabel = new Label(StringConstantsFrontend.USERVIEW_PROFILE_PICTURE); // layouts this.userNameLayout = new VerticalLayout(userNameLabel, this.userNameTextField); this.changePasswordLayout = new VerticalLayout(); this.profilePictureLayout = new VerticalLayout(profilePictureLabel, imageCtx.img); this.buttonLayout = new VerticalLayout(this.editButton); } /* Set Properties for components */ { // username-field, password-field this.userNameTextField.addClassName("user-name-text-field"); this.userNameTextField.setValue(userDao.getCurrentUser().getUserName()); userNameLabel.addClassName("sub-heading"); this.changePasswordLabel.addClassName("sub-heading"); // buttons this.editButton.addClassName("confirm-button"); this.saveButton.addClassName("confirm-button"); this.cancelButton.addClassName("cancel-button"); // profile-picture, upload profilePictureLabel.addClassName("sub-heading"); } /* Add Listener */ addClickListener(); addValueChangeListener(); imageCtx.loadImage(); } /** * This method adds a ClickListener to the buttons. */ private void addClickListener() { // edit-button this.editButton.addClickListener(event -> changeToEditMode()); // cancel-button this.cancelButton.addClickListener(event -> { StringBuilder unsavedChanges = new StringBuilder(StringConstantsFrontend.USERVIEW_UNSAVED_CHANGES + " ("); for (Property property : Property.changedProperties) { unsavedChanges.append(property.getName()).append(", "); } unsavedChanges = new StringBuilder(unsavedChanges.substring(0, unsavedChanges.length() - 2)); //remove last, and space letter unsavedChanges.append("). " + StringConstantsFrontend.USERVIEW_UNSAVED_CHANGES_WILL_GET_LOST + " " + StringConstantsFrontend.USERVIEW_UNSAVED_CHANGES_REALLY_ABORT); if (!Property.changedProperties.isEmpty()) { // confirm message dialog this.cancelButtonConfirmDialog = new com.buschmais.frontend.components.ConfirmDialog( StringConstantsFrontend.USERVIEW_UNSAVED_CHANGES_REALLY_ABORT, unsavedChanges.toString(), StringConstantsFrontend.USERVIEW_CONFIRM_DIALOG_BUTTON_LABEL_DISCARD_CHANGES, confirmEvent -> {this.cancelButtonConfirmDialog.close(); changeToReadOnlyMode();}, StringConstantsFrontend.USERVIEW_CONFIRM_DIALOG_BUTTON_LABEL_CONTINUE_EDITING, cancelEvent -> this.cancelButtonConfirmDialog.close()); // open dialog this.cancelButtonConfirmDialog.open(); } else { changeToReadOnlyMode(); } }); // save-button this.saveButton.addClickListener(event -> { synchronized (userDao){ String changedUsername = this.userNameTextField.getValue().trim(); String newPassword = this.newPasswordField.getValue().trim(); boolean dataSaveSuccess = true; /* Check if changed */ // username if (Property.USER_NAME.hasChanged()) { Property.USER_NAME.setReadyToSave(checkUsername(changedUsername)); } // password if (Property.PASSWORD.hasChanged()) { Property.PASSWORD.setReadyToSave(checkPassword( newPassword, this.currentPasswortField.getValue().trim(), this.userDao.getCurrentUser())); } // profile-picture Property.PROFILE_PICTURE.setReadyToSave(Property.PROFILE_PICTURE.hasChanged()); /* Save Data */ if (Property.USER_NAME.hasChanged() && Property.USER_NAME.isReadyToSave() && Property.PASSWORD.hasChanged() && Property.PASSWORD.isReadyToSave()) { User user = this.userDao.getCurrentUser(); if (user != null) { user.setUserName(changedUsername); user.changePassword(newPassword); userDao.setCurrentUser(this.userDao.save(user));
package com.buschmais.frontend.views.user; //@Route(value = StringConstantsFrontend.USER_PATH, layout = MainLayout.class) @CssImport(value = "./themes/adr-workbench/vaadin-components/buttons.css") @CssImport(value = "./themes/adr-workbench/user/user.css") @CssImport(value = "./themes/adr-workbench/vaadin-components/vaadin-text-field-styles.css", themeFor = "vaadin-text-field vaadin-password-field") @PageTitle("User") public class UserView extends VerticalLayout implements BroadcastListener { // TODO: Check about all passwords attributes (Password Hash - clear password), beautifying and error handling /* Property enum */ private enum Property { USER_NAME("Benutzername"), PASSWORD("Passwort"), PROFILE_PICTURE("Profilbild"); private final String name; private final static List<Property> changedProperties = new ArrayList<>(); private boolean hasChanged = false; private boolean isReadyToSave = false; Property(String name) { this.name = name; } public String getName() { return this.name; } public boolean hasChanged() { return this.hasChanged; } public boolean isReadyToSave() { return this.isReadyToSave; } public void setHasChanged(boolean hasChanged) { this.hasChanged = hasChanged; if (hasChanged) { changedProperties.add(this); } else { changedProperties.remove(this); } } public void setReadyToSave(boolean readyToSave) { this.isReadyToSave = readyToSave; } } // buttons private Button editButton; private Button saveButton; private Button cancelButton; // text-fields private TextField userNameTextField; private PasswordField newPasswordField; private PasswordField currentPasswortField; private Label changePasswordLabel; // layouts private VerticalLayout userNameLayout; private VerticalLayout changePasswordLayout; private VerticalLayout profilePictureLayout; private VerticalLayout buttonLayout; // confirm dialog private com.buschmais.frontend.components.ConfirmDialog cancelButtonConfirmDialog; // other class instances private final UserDao userDao; private final ImageDao imageDao; private final ImageCtx imageCtx; public UserView(@Autowired UserDao userDao, @Autowired ImageDao imageDao) { this.userDao = userDao; this.imageDao = imageDao; synchronized (this.userDao){ Optional<User> found_user = userDao.findByUserName(userDao.getCurrentUser().getUserName()); found_user.ifPresent(userDao::setCurrentUser); imageCtx = new ImageCtx(this.userDao, this.imageDao); Property.changedProperties.clear(); setupComponents(); createDefaultLayout(); // Attach listeners for broadcasting and detachment Broadcaster.registerListener(this); addDetachListener((DetachEvent e) -> Broadcaster.unregisterListener(this)); } } /** * This method creates the instances of the components and adds classnames to them. * Additionally it changes properties of a component. */ private void setupComponents() { /* Create Instances */ //labels Label userNameLabel; Label profilePictureLabel; { // username-field, password field this.userNameTextField = new TextField(); this.newPasswordField = new PasswordField("Neues Passwort"); this.currentPasswortField = new PasswordField("Aktuelles Passwort"); // all buttons this.editButton = new Button(StringConstantsFrontend.USERVIEW_BUTTON_EDIT_PROFILE); this.saveButton = new Button(StringConstantsFrontend.GENERAL_DIALOG_BUTTON_SAVE); this.cancelButton = new Button(StringConstantsFrontend.GENERAL_DIALOG_BUTTON_CANCEL); // labels userNameLabel = new Label(StringConstantsFrontend.GENERAL_USERNAME_TEXT); this.changePasswordLabel = new Label(StringConstantsFrontend.USERVIEW_CHANGE_PASSWORD); profilePictureLabel = new Label(StringConstantsFrontend.USERVIEW_PROFILE_PICTURE); // layouts this.userNameLayout = new VerticalLayout(userNameLabel, this.userNameTextField); this.changePasswordLayout = new VerticalLayout(); this.profilePictureLayout = new VerticalLayout(profilePictureLabel, imageCtx.img); this.buttonLayout = new VerticalLayout(this.editButton); } /* Set Properties for components */ { // username-field, password-field this.userNameTextField.addClassName("user-name-text-field"); this.userNameTextField.setValue(userDao.getCurrentUser().getUserName()); userNameLabel.addClassName("sub-heading"); this.changePasswordLabel.addClassName("sub-heading"); // buttons this.editButton.addClassName("confirm-button"); this.saveButton.addClassName("confirm-button"); this.cancelButton.addClassName("cancel-button"); // profile-picture, upload profilePictureLabel.addClassName("sub-heading"); } /* Add Listener */ addClickListener(); addValueChangeListener(); imageCtx.loadImage(); } /** * This method adds a ClickListener to the buttons. */ private void addClickListener() { // edit-button this.editButton.addClickListener(event -> changeToEditMode()); // cancel-button this.cancelButton.addClickListener(event -> { StringBuilder unsavedChanges = new StringBuilder(StringConstantsFrontend.USERVIEW_UNSAVED_CHANGES + " ("); for (Property property : Property.changedProperties) { unsavedChanges.append(property.getName()).append(", "); } unsavedChanges = new StringBuilder(unsavedChanges.substring(0, unsavedChanges.length() - 2)); //remove last, and space letter unsavedChanges.append("). " + StringConstantsFrontend.USERVIEW_UNSAVED_CHANGES_WILL_GET_LOST + " " + StringConstantsFrontend.USERVIEW_UNSAVED_CHANGES_REALLY_ABORT); if (!Property.changedProperties.isEmpty()) { // confirm message dialog this.cancelButtonConfirmDialog = new com.buschmais.frontend.components.ConfirmDialog( StringConstantsFrontend.USERVIEW_UNSAVED_CHANGES_REALLY_ABORT, unsavedChanges.toString(), StringConstantsFrontend.USERVIEW_CONFIRM_DIALOG_BUTTON_LABEL_DISCARD_CHANGES, confirmEvent -> {this.cancelButtonConfirmDialog.close(); changeToReadOnlyMode();}, StringConstantsFrontend.USERVIEW_CONFIRM_DIALOG_BUTTON_LABEL_CONTINUE_EDITING, cancelEvent -> this.cancelButtonConfirmDialog.close()); // open dialog this.cancelButtonConfirmDialog.open(); } else { changeToReadOnlyMode(); } }); // save-button this.saveButton.addClickListener(event -> { synchronized (userDao){ String changedUsername = this.userNameTextField.getValue().trim(); String newPassword = this.newPasswordField.getValue().trim(); boolean dataSaveSuccess = true; /* Check if changed */ // username if (Property.USER_NAME.hasChanged()) { Property.USER_NAME.setReadyToSave(checkUsername(changedUsername)); } // password if (Property.PASSWORD.hasChanged()) { Property.PASSWORD.setReadyToSave(checkPassword( newPassword, this.currentPasswortField.getValue().trim(), this.userDao.getCurrentUser())); } // profile-picture Property.PROFILE_PICTURE.setReadyToSave(Property.PROFILE_PICTURE.hasChanged()); /* Save Data */ if (Property.USER_NAME.hasChanged() && Property.USER_NAME.isReadyToSave() && Property.PASSWORD.hasChanged() && Property.PASSWORD.isReadyToSave()) { User user = this.userDao.getCurrentUser(); if (user != null) { user.setUserName(changedUsername); user.changePassword(newPassword); userDao.setCurrentUser(this.userDao.save(user));
new SuccessNotification(StringConstantsFrontend.USERVIEW_SUCCESS_USERNAME_AND_PASSWORD_CHANGED).open();
6
2023-10-25 15:18:06+00:00
12k
rudraparmar76/Student-Portal
Student-Portal/Home_Frame.java
[ { "identifier": "Home_Bhagubhai", "path": "Student-Portal/Colleges/Bhagubhai_College/Home_Bhagubhai.java", "snippet": "public class Home_Bhagubhai extends javax.swing.JFrame {\n\n /**\n * Creates new form Home_Bhagubhai\n */\n public Home_Bhagubhai() {\n initComponents();\n }\n\n...
import Colleges.Bhagubhai_College.Home_Bhagubhai; import Colleges.NM.Home_NM; import javax.swing.JFrame;
7,216
.addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelMin, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabelClose) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); jPanel2.setBackground(new java.awt.Color(27, 156, 252)); jPanel2.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jLabel1.setBackground(java.awt.SystemColor.window); jLabel1.setFont(new java.awt.Font("SansSerif", 1, 18)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("*** Please Select Your College ***"); jLabel9.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel9.setForeground(new java.awt.Color(255, 255, 255)); jLabel9.setText("1.Shri Bhagubhai Mafatlal Polytechnic"); jLabel9.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel9MouseClicked(evt); } }); jLabel10.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel10.setForeground(new java.awt.Color(255, 255, 255)); jLabel10.setText("3.Mithibai College"); jLabel11.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel11.setForeground(new java.awt.Color(255, 255, 255)); jLabel11.setText("4.NMIMS"); jLabel12.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel12.setForeground(new java.awt.Color(255, 255, 255)); jLabel12.setText("2.Narsee Monjee College"); jLabel12.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel12MouseClicked(evt); } }); jLabel13.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel13.setForeground(new java.awt.Color(255, 255, 255)); jLabel13.setText("5.D.J Sanghavi College of Engineering"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(145, 145, 145) .addComponent(jLabel1)) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(36, 36, 36) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel10) .addComponent(jLabel9) .addComponent(jLabel11) .addComponent(jLabel12) .addComponent(jLabel13)))) .addContainerGap(163, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(28, 28, 28) .addComponent(jLabel1) .addGap(51, 51, 51) .addComponent(jLabel9) .addGap(18, 18, 18) .addComponent(jLabel12) .addGap(18, 18, 18) .addComponent(jLabel10) .addGap(18, 18, 18) .addComponent(jLabel11) .addGap(18, 18, 18) .addComponent(jLabel13) .addContainerGap(45, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(322, Short.MAX_VALUE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 55, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jLabelCloseMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelCloseMouseClicked System.exit(0); }//GEN-LAST:event_jLabelCloseMouseClicked private void jLabelMinMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelMinMouseClicked this.setState(Home_Frame.ICONIFIED); }//GEN-LAST:event_jLabelMinMouseClicked private void jLabel9MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel9MouseClicked // TODO add your handling code here:
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template */ /** * * @author rudra */ public class Home_Frame extends javax.swing.JFrame { /** * Creates new form Home_Frame */ public Home_Frame() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabelClose = new javax.swing.JLabel(); jLabelMin = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setUndecorated(true); jPanel1.setBackground(new java.awt.Color(37, 204, 247)); jLabelClose.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jLabelClose.setForeground(new java.awt.Color(255, 255, 255)); jLabelClose.setText("X"); jLabelClose.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jLabelClose.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabelCloseMouseClicked(evt); } }); jLabelMin.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jLabelMin.setForeground(new java.awt.Color(255, 255, 255)); jLabelMin.setText("-"); jLabelMin.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jLabelMin.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabelMinMouseClicked(evt); } }); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jLabel2.setForeground(new java.awt.Color(255, 255, 255)); jLabel2.setText("Home Page"); jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/download (2).jpeg"))); // NOI18N jLabel8.setText("jLabel8"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 324, Short.MAX_VALUE) .addComponent(jLabelMin) .addGap(18, 18, 18) .addComponent(jLabelClose) .addGap(21, 21, 21)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelMin, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabelClose) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); jPanel2.setBackground(new java.awt.Color(27, 156, 252)); jPanel2.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jLabel1.setBackground(java.awt.SystemColor.window); jLabel1.setFont(new java.awt.Font("SansSerif", 1, 18)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("*** Please Select Your College ***"); jLabel9.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel9.setForeground(new java.awt.Color(255, 255, 255)); jLabel9.setText("1.Shri Bhagubhai Mafatlal Polytechnic"); jLabel9.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel9MouseClicked(evt); } }); jLabel10.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel10.setForeground(new java.awt.Color(255, 255, 255)); jLabel10.setText("3.Mithibai College"); jLabel11.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel11.setForeground(new java.awt.Color(255, 255, 255)); jLabel11.setText("4.NMIMS"); jLabel12.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel12.setForeground(new java.awt.Color(255, 255, 255)); jLabel12.setText("2.Narsee Monjee College"); jLabel12.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel12MouseClicked(evt); } }); jLabel13.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel13.setForeground(new java.awt.Color(255, 255, 255)); jLabel13.setText("5.D.J Sanghavi College of Engineering"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(145, 145, 145) .addComponent(jLabel1)) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(36, 36, 36) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel10) .addComponent(jLabel9) .addComponent(jLabel11) .addComponent(jLabel12) .addComponent(jLabel13)))) .addContainerGap(163, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(28, 28, 28) .addComponent(jLabel1) .addGap(51, 51, 51) .addComponent(jLabel9) .addGap(18, 18, 18) .addComponent(jLabel12) .addGap(18, 18, 18) .addComponent(jLabel10) .addGap(18, 18, 18) .addComponent(jLabel11) .addGap(18, 18, 18) .addComponent(jLabel13) .addContainerGap(45, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(322, Short.MAX_VALUE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 55, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jLabelCloseMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelCloseMouseClicked System.exit(0); }//GEN-LAST:event_jLabelCloseMouseClicked private void jLabelMinMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelMinMouseClicked this.setState(Home_Frame.ICONIFIED); }//GEN-LAST:event_jLabelMinMouseClicked private void jLabel9MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel9MouseClicked // TODO add your handling code here:
Home_Bhagubhai hb = new Home_Bhagubhai();
0
2023-10-27 17:08:02+00:00
12k
aerospike/graph-synth
graph-synth/src/test/java/com/aerospike/synth/emitter/generator/TestGenerator.java
[ { "identifier": "EdgeGenerator", "path": "graph-synth/src/main/java/com/aerospike/graph/synth/emitter/generator/EdgeGenerator.java", "snippet": "public class EdgeGenerator {\n public final EdgeSchema edgeSchema;\n public final GraphSchema graphSchema;\n private GeneratedVertex nextVertex;\n ...
import com.aerospike.graph.synth.emitter.generator.EdgeGenerator; import com.aerospike.graph.synth.emitter.generator.GeneratedVertex; import com.aerospike.graph.synth.emitter.generator.Generator; import com.aerospike.movement.config.core.ConfigurationBase; import com.aerospike.graph.synth.emitter.generator.schema.seralization.YAMLSchemaParser; import com.aerospike.movement.logging.core.Logger; import com.aerospike.movement.runtime.core.Runtime; import com.aerospike.movement.runtime.core.driver.impl.GeneratedOutputIdDriver; import com.aerospike.movement.runtime.core.local.RunningPhase; import com.aerospike.graph.synth.test.generator.SchemaTestConstants; import com.aerospike.movement.test.mock.MockCallback; import com.aerospike.movement.test.mock.driver.MockOutputIdDriver; import com.aerospike.movement.util.core.runtime.RuntimeUtil; import com.aerospike.movement.util.core.iterator.OneShotIteratorSupplier; import com.aerospike.movement.runtime.core.driver.impl.SuppliedWorkChunkDriver; import com.aerospike.movement.runtime.core.local.LocalParallelStreamRuntime; import com.aerospike.movement.test.core.AbstractMovementTest; import com.aerospike.movement.test.mock.MockUtil; import com.aerospike.movement.test.mock.encoder.MockEncoder; import com.aerospike.movement.test.mock.output.MockOutput; import com.aerospike.movement.util.core.configuration.ConfigurationUtil; import com.aerospike.movement.util.core.runtime.IOUtil; import com.aerospike.movement.util.core.iterator.PrimitiveIteratorWrap; import org.apache.commons.configuration2.Configuration; import org.apache.commons.configuration2.MapConfiguration; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.LongStream; import static com.aerospike.movement.runtime.core.local.LocalParallelStreamRuntime.Config.Keys.THREADS; import static com.aerospike.movement.test.mock.MockUtil.*; import static junit.framework.TestCase.*;
7,359
final Map<String, String> configMap = new HashMap<>() {{ put(THREADS, String.valueOf(THREAD_COUNT)); put(Generator.Config.Keys.SCALE_FACTOR, String.valueOf(TEST_SIZE)); put(YAMLSchemaParser.Config.Keys.YAML_FILE_PATH, IOUtil.copyFromResourcesIntoNewTempFile("example_schema.yaml").getAbsolutePath()); }}; final Configuration mockConfig = getMockConfiguration(configMap); final Configuration defaultConfig = ConfigurationUtil.configurationWithOverrides(mockConfig, emitterConfig); final Configuration config = ConfigurationUtil.configurationWithOverrides(defaultConfig, new MapConfiguration(new HashMap<>() {{ put(ConfigurationBase.Keys.OUTPUT_ID_DRIVER, GeneratedOutputIdDriver.class.getName()); put(ConfigurationBase.Keys.WORK_CHUNK_DRIVER_PHASE_ONE, SuppliedWorkChunkDriver.class.getName()); put(ConfigurationBase.Keys.WORK_CHUNK_DRIVER_PHASE_TWO, SuppliedWorkChunkDriver.class.getName()); put(GeneratedOutputIdDriver.Config.Keys.RANGE_BOTTOM, String.valueOf(TEST_SIZE + 1)); put(GeneratedOutputIdDriver.Config.Keys.RANGE_TOP, String.valueOf(Long.MAX_VALUE)); put(LocalParallelStreamRuntime.Config.Keys.THREADS, 8); }})); registerCleanupCallback(() -> { LocalParallelStreamRuntime.getInstance(config).close(); }); System.out.println(ConfigurationUtil.configurationToPropertiesFormat(config)); final Set<Object> emittedIds = Collections.synchronizedSet(new HashSet<>()); SuppliedWorkChunkDriver.setIteratorSupplierForPhase(Runtime.PHASE.ONE, OneShotIteratorSupplier.of(() -> PrimitiveIteratorWrap.wrap(LongStream.range(0, TEST_SIZE).iterator()))); SuppliedWorkChunkDriver.setIteratorSupplierForPhase(Runtime.PHASE.TWO, OneShotIteratorSupplier.of(() -> PrimitiveIteratorWrap.wrap(LongStream.range(0, TEST_SIZE).iterator()))); MockUtil.setDefaultMockCallbacks(); final AtomicBoolean duplicateIdDetected = new AtomicBoolean(false); MockUtil.setDuplicateIdOutputVerification(emittedIds, duplicateIdDetected); assertFalse(duplicateIdDetected.get()); MockUtil.setCallback(MockEncoder.class, MockEncoder.Methods.ENCODE, MockCallback.create((object, args) -> { MockUtil.incrementHitCounter(MockEncoder.class, MockEncoder.Methods.ENCODE); if (args.length == 1 && args[0] instanceof GeneratedVertex) { MockUtil.incrementHitCounter(GeneratedVertex.class, MockEncoder.Methods.ENCODE); MockUtil.incrementMetadataCounter(((GeneratedVertex) args[0]).label(), GeneratedVertex.class.getSimpleName()); } if (args.length == 1 && args[0] instanceof EdgeGenerator.GeneratedEdge) { MockUtil.incrementHitCounter(EdgeGenerator.GeneratedEdge.class, MockEncoder.Methods.ENCODE); MockUtil.incrementMetadataCounter(((EdgeGenerator.GeneratedEdge) args[0]).label(), EdgeGenerator.GeneratedEdge.class.getSimpleName()); } return Optional.of(args[0]); })); } @Test public void testGenerateElementCounts() { final long TEST_SIZE = 100_000; final Map<String, String> configMap = new HashMap<>() {{ put(THREADS, String.valueOf(THREAD_COUNT)); put(Generator.Config.Keys.SCALE_FACTOR, String.valueOf(TEST_SIZE)); put(YAMLSchemaParser.Config.Keys.YAML_FILE_PATH, IOUtil.copyFromResourcesIntoNewTempFile("example_schema.yaml").getAbsolutePath()); }}; final Configuration mockConfig = getMockConfiguration(configMap); final Configuration defaultConfig = ConfigurationUtil.configurationWithOverrides(mockConfig, emitterConfig); final Configuration config = ConfigurationUtil.configurationWithOverrides(defaultConfig, new MapConfiguration(new HashMap<>() {{ put(ConfigurationBase.Keys.OUTPUT_ID_DRIVER, GeneratedOutputIdDriver.class.getName()); put(ConfigurationBase.Keys.WORK_CHUNK_DRIVER_PHASE_ONE, SuppliedWorkChunkDriver.class.getName()); put(ConfigurationBase.Keys.WORK_CHUNK_DRIVER_PHASE_TWO, SuppliedWorkChunkDriver.class.getName()); put(GeneratedOutputIdDriver.Config.Keys.RANGE_BOTTOM, String.valueOf(TEST_SIZE + 1)); put(GeneratedOutputIdDriver.Config.Keys.RANGE_TOP, String.valueOf(Long.MAX_VALUE)); put(LocalParallelStreamRuntime.Config.Keys.THREADS, 8); }})); registerCleanupCallback(() -> { LocalParallelStreamRuntime.getInstance(config).close(); }); System.out.println(ConfigurationUtil.configurationToPropertiesFormat(config)); final Set<Object> emittedIds = Collections.synchronizedSet(new HashSet<>()); final Runtime runtime = LocalParallelStreamRuntime.getInstance(config); SuppliedWorkChunkDriver.setIteratorSupplierForPhase(Runtime.PHASE.ONE, OneShotIteratorSupplier.of(() -> PrimitiveIteratorWrap.wrap(LongStream.range(0, TEST_SIZE).iterator()))); SuppliedWorkChunkDriver.setIteratorSupplierForPhase(Runtime.PHASE.TWO, OneShotIteratorSupplier.of(() -> PrimitiveIteratorWrap.wrap(LongStream.range(0, TEST_SIZE).iterator()))); MockUtil.setDefaultMockCallbacks(); final AtomicBoolean duplicateIdDetected = new AtomicBoolean(false); MockUtil.setDuplicateIdOutputVerification(emittedIds, duplicateIdDetected); assertFalse(duplicateIdDetected.get()); MockUtil.setCallback(MockEncoder.class, MockEncoder.Methods.ENCODE, MockCallback.create((object, args) -> { MockUtil.incrementHitCounter(MockEncoder.class, MockEncoder.Methods.ENCODE); if (args.length == 1 && args[0] instanceof GeneratedVertex) { MockUtil.incrementHitCounter(GeneratedVertex.class, MockEncoder.Methods.ENCODE); MockUtil.incrementMetadataCounter(((GeneratedVertex) args[0]).label(), GeneratedVertex.class.getSimpleName()); } if (args.length == 1 && args[0] instanceof EdgeGenerator.GeneratedEdge) { MockUtil.incrementHitCounter(EdgeGenerator.GeneratedEdge.class, MockEncoder.Methods.ENCODE); MockUtil.incrementMetadataCounter(((EdgeGenerator.GeneratedEdge) args[0]).label(), EdgeGenerator.GeneratedEdge.class.getSimpleName()); } return Optional.of(args[0]); })); final Iterator<RunningPhase> x = runtime.runPhases( List.of(Runtime.PHASE.ONE, Runtime.PHASE.TWO), config); iteratePhasesAndCloseRuntime(x,runtime); assertEquals(TEST_SIZE * 15, getHitCounter(MockEncoder.class, MockEncoder.Methods.ENCODE)); assertEquals(TEST_SIZE * 15, getHitCounter(MockOutput.class, MockOutput.Methods.WRITE_TO_OUTPUT)); logger.info(String.format("%d verticies encoded", getHitCounter(GeneratedVertex.class, MockEncoder.Methods.ENCODE))); logger.info(String.format("%d edges encoded", getHitCounter(EdgeGenerator.GeneratedEdge.class, MockEncoder.Methods.ENCODE))); getMetadataTypes().forEach(metadataTypeName -> { MockUtil.getMetadataSubtypes(metadataTypeName).forEach(subtype -> { logger.info(String.format("%d %s of type %s encoded", getMetadataHitCounter(metadataTypeName, subtype), metadataTypeName, subtype)); }); }); final String GenVertexName = GeneratedVertex.class.getSimpleName(); final String GenEdgeName = EdgeGenerator.GeneratedEdge.class.getSimpleName();
/* * @author Grant Haywood <grant.haywood@aerospike.com> * Developed May 2023 - Oct 2023 * Copyright (c) 2023 Aerospike Inc. */ package com.aerospike.synth.emitter.generator; public class TestGenerator extends AbstractMovementTest { final int THREAD_COUNT = 4; final int TEST_SIZE = 20; final Logger logger = RuntimeUtil.getLogger(this); final Configuration emitterConfig = Generator.getEmitterConfig(); @Before public void setup() { super.setup(); } @After public void cleanup() { super.cleanup(); } @Test public void doesNotGenerateDuplicateIds() { final long DUPLICATE_TEST_SIZE = 100_000; final Map<String, String> configMap = new HashMap<>() {{ put(THREADS, String.valueOf(THREAD_COUNT)); put(Generator.Config.Keys.SCALE_FACTOR, String.valueOf(TEST_SIZE)); put(YAMLSchemaParser.Config.Keys.YAML_FILE_PATH, IOUtil.copyFromResourcesIntoNewTempFile("example_schema.yaml").getAbsolutePath()); }}; final Configuration mockConfig = getMockConfiguration(configMap); final Configuration defaultConfig = ConfigurationUtil.configurationWithOverrides(mockConfig, emitterConfig); final Configuration config = ConfigurationUtil.configurationWithOverrides(defaultConfig, new MapConfiguration(new HashMap<>() {{ put(ConfigurationBase.Keys.OUTPUT_ID_DRIVER, GeneratedOutputIdDriver.class.getName()); put(ConfigurationBase.Keys.WORK_CHUNK_DRIVER_PHASE_ONE, SuppliedWorkChunkDriver.class.getName()); put(ConfigurationBase.Keys.WORK_CHUNK_DRIVER_PHASE_TWO, SuppliedWorkChunkDriver.class.getName()); put(GeneratedOutputIdDriver.Config.Keys.RANGE_BOTTOM, String.valueOf(DUPLICATE_TEST_SIZE + 1)); put(GeneratedOutputIdDriver.Config.Keys.RANGE_TOP, String.valueOf(Long.MAX_VALUE)); }})); registerCleanupCallback(() -> { LocalParallelStreamRuntime.getInstance(config).close(); }); final Set<Object> emittedIds = Collections.synchronizedSet(new HashSet<>()); final Runtime runtime = LocalParallelStreamRuntime.getInstance(config); SuppliedWorkChunkDriver.setIteratorSupplierForPhase(Runtime.PHASE.ONE, OneShotIteratorSupplier.of(() -> PrimitiveIteratorWrap.wrap(LongStream.range(0, DUPLICATE_TEST_SIZE).iterator()))); SuppliedWorkChunkDriver.setIteratorSupplierForPhase(Runtime.PHASE.TWO, OneShotIteratorSupplier.of(() -> PrimitiveIteratorWrap.wrap(LongStream.range(0, DUPLICATE_TEST_SIZE).iterator()))); MockUtil.setDefaultMockCallbacks(); final AtomicBoolean duplicateIdDetected = new AtomicBoolean(false); MockUtil.setDuplicateIdOutputVerification(emittedIds, duplicateIdDetected); assertFalse(duplicateIdDetected.get()); final long msTaken = iteratePhasesTimed(runtime, config); assertEquals(DUPLICATE_TEST_SIZE * 15, getHitCounter(MockEncoder.class, MockEncoder.Methods.ENCODE)); assertEquals(DUPLICATE_TEST_SIZE * 15, getHitCounter(MockOutput.class, MockOutput.Methods.WRITE_TO_OUTPUT)); } public void runGeneratorHighLevel() { final long TEST_SIZE = 100_000; final Map<String, String> configMap = new HashMap<>() {{ put(THREADS, String.valueOf(THREAD_COUNT)); put(Generator.Config.Keys.SCALE_FACTOR, String.valueOf(TEST_SIZE)); put(YAMLSchemaParser.Config.Keys.YAML_FILE_PATH, IOUtil.copyFromResourcesIntoNewTempFile("example_schema.yaml").getAbsolutePath()); }}; final Configuration mockConfig = getMockConfiguration(configMap); final Configuration defaultConfig = ConfigurationUtil.configurationWithOverrides(mockConfig, emitterConfig); final Configuration config = ConfigurationUtil.configurationWithOverrides(defaultConfig, new MapConfiguration(new HashMap<>() {{ put(ConfigurationBase.Keys.OUTPUT_ID_DRIVER, GeneratedOutputIdDriver.class.getName()); put(ConfigurationBase.Keys.WORK_CHUNK_DRIVER_PHASE_ONE, SuppliedWorkChunkDriver.class.getName()); put(ConfigurationBase.Keys.WORK_CHUNK_DRIVER_PHASE_TWO, SuppliedWorkChunkDriver.class.getName()); put(GeneratedOutputIdDriver.Config.Keys.RANGE_BOTTOM, String.valueOf(TEST_SIZE + 1)); put(GeneratedOutputIdDriver.Config.Keys.RANGE_TOP, String.valueOf(Long.MAX_VALUE)); put(LocalParallelStreamRuntime.Config.Keys.THREADS, 8); }})); registerCleanupCallback(() -> { LocalParallelStreamRuntime.getInstance(config).close(); }); System.out.println(ConfigurationUtil.configurationToPropertiesFormat(config)); final Set<Object> emittedIds = Collections.synchronizedSet(new HashSet<>()); SuppliedWorkChunkDriver.setIteratorSupplierForPhase(Runtime.PHASE.ONE, OneShotIteratorSupplier.of(() -> PrimitiveIteratorWrap.wrap(LongStream.range(0, TEST_SIZE).iterator()))); SuppliedWorkChunkDriver.setIteratorSupplierForPhase(Runtime.PHASE.TWO, OneShotIteratorSupplier.of(() -> PrimitiveIteratorWrap.wrap(LongStream.range(0, TEST_SIZE).iterator()))); MockUtil.setDefaultMockCallbacks(); final AtomicBoolean duplicateIdDetected = new AtomicBoolean(false); MockUtil.setDuplicateIdOutputVerification(emittedIds, duplicateIdDetected); assertFalse(duplicateIdDetected.get()); MockUtil.setCallback(MockEncoder.class, MockEncoder.Methods.ENCODE, MockCallback.create((object, args) -> { MockUtil.incrementHitCounter(MockEncoder.class, MockEncoder.Methods.ENCODE); if (args.length == 1 && args[0] instanceof GeneratedVertex) { MockUtil.incrementHitCounter(GeneratedVertex.class, MockEncoder.Methods.ENCODE); MockUtil.incrementMetadataCounter(((GeneratedVertex) args[0]).label(), GeneratedVertex.class.getSimpleName()); } if (args.length == 1 && args[0] instanceof EdgeGenerator.GeneratedEdge) { MockUtil.incrementHitCounter(EdgeGenerator.GeneratedEdge.class, MockEncoder.Methods.ENCODE); MockUtil.incrementMetadataCounter(((EdgeGenerator.GeneratedEdge) args[0]).label(), EdgeGenerator.GeneratedEdge.class.getSimpleName()); } return Optional.of(args[0]); })); } @Test public void testGenerateElementCounts() { final long TEST_SIZE = 100_000; final Map<String, String> configMap = new HashMap<>() {{ put(THREADS, String.valueOf(THREAD_COUNT)); put(Generator.Config.Keys.SCALE_FACTOR, String.valueOf(TEST_SIZE)); put(YAMLSchemaParser.Config.Keys.YAML_FILE_PATH, IOUtil.copyFromResourcesIntoNewTempFile("example_schema.yaml").getAbsolutePath()); }}; final Configuration mockConfig = getMockConfiguration(configMap); final Configuration defaultConfig = ConfigurationUtil.configurationWithOverrides(mockConfig, emitterConfig); final Configuration config = ConfigurationUtil.configurationWithOverrides(defaultConfig, new MapConfiguration(new HashMap<>() {{ put(ConfigurationBase.Keys.OUTPUT_ID_DRIVER, GeneratedOutputIdDriver.class.getName()); put(ConfigurationBase.Keys.WORK_CHUNK_DRIVER_PHASE_ONE, SuppliedWorkChunkDriver.class.getName()); put(ConfigurationBase.Keys.WORK_CHUNK_DRIVER_PHASE_TWO, SuppliedWorkChunkDriver.class.getName()); put(GeneratedOutputIdDriver.Config.Keys.RANGE_BOTTOM, String.valueOf(TEST_SIZE + 1)); put(GeneratedOutputIdDriver.Config.Keys.RANGE_TOP, String.valueOf(Long.MAX_VALUE)); put(LocalParallelStreamRuntime.Config.Keys.THREADS, 8); }})); registerCleanupCallback(() -> { LocalParallelStreamRuntime.getInstance(config).close(); }); System.out.println(ConfigurationUtil.configurationToPropertiesFormat(config)); final Set<Object> emittedIds = Collections.synchronizedSet(new HashSet<>()); final Runtime runtime = LocalParallelStreamRuntime.getInstance(config); SuppliedWorkChunkDriver.setIteratorSupplierForPhase(Runtime.PHASE.ONE, OneShotIteratorSupplier.of(() -> PrimitiveIteratorWrap.wrap(LongStream.range(0, TEST_SIZE).iterator()))); SuppliedWorkChunkDriver.setIteratorSupplierForPhase(Runtime.PHASE.TWO, OneShotIteratorSupplier.of(() -> PrimitiveIteratorWrap.wrap(LongStream.range(0, TEST_SIZE).iterator()))); MockUtil.setDefaultMockCallbacks(); final AtomicBoolean duplicateIdDetected = new AtomicBoolean(false); MockUtil.setDuplicateIdOutputVerification(emittedIds, duplicateIdDetected); assertFalse(duplicateIdDetected.get()); MockUtil.setCallback(MockEncoder.class, MockEncoder.Methods.ENCODE, MockCallback.create((object, args) -> { MockUtil.incrementHitCounter(MockEncoder.class, MockEncoder.Methods.ENCODE); if (args.length == 1 && args[0] instanceof GeneratedVertex) { MockUtil.incrementHitCounter(GeneratedVertex.class, MockEncoder.Methods.ENCODE); MockUtil.incrementMetadataCounter(((GeneratedVertex) args[0]).label(), GeneratedVertex.class.getSimpleName()); } if (args.length == 1 && args[0] instanceof EdgeGenerator.GeneratedEdge) { MockUtil.incrementHitCounter(EdgeGenerator.GeneratedEdge.class, MockEncoder.Methods.ENCODE); MockUtil.incrementMetadataCounter(((EdgeGenerator.GeneratedEdge) args[0]).label(), EdgeGenerator.GeneratedEdge.class.getSimpleName()); } return Optional.of(args[0]); })); final Iterator<RunningPhase> x = runtime.runPhases( List.of(Runtime.PHASE.ONE, Runtime.PHASE.TWO), config); iteratePhasesAndCloseRuntime(x,runtime); assertEquals(TEST_SIZE * 15, getHitCounter(MockEncoder.class, MockEncoder.Methods.ENCODE)); assertEquals(TEST_SIZE * 15, getHitCounter(MockOutput.class, MockOutput.Methods.WRITE_TO_OUTPUT)); logger.info(String.format("%d verticies encoded", getHitCounter(GeneratedVertex.class, MockEncoder.Methods.ENCODE))); logger.info(String.format("%d edges encoded", getHitCounter(EdgeGenerator.GeneratedEdge.class, MockEncoder.Methods.ENCODE))); getMetadataTypes().forEach(metadataTypeName -> { MockUtil.getMetadataSubtypes(metadataTypeName).forEach(subtype -> { logger.info(String.format("%d %s of type %s encoded", getMetadataHitCounter(metadataTypeName, subtype), metadataTypeName, subtype)); }); }); final String GenVertexName = GeneratedVertex.class.getSimpleName(); final String GenEdgeName = EdgeGenerator.GeneratedEdge.class.getSimpleName();
SchemaTestConstants.verifyCount(SchemaTestConstants.SchemaKeys.GOLDEN_ENTITY,
4
2023-10-27 22:54:12+00:00
12k
Java-Game-Engine-Merger/Libgdx-Processing
framework0004/framework0004-terminal/src/main/java/com/jediterm/terminal/ui/settings/DefaultSettingsProvider.java
[ { "identifier": "fromAwtToTerminalColor", "path": "framework0004/framework0004-terminal/src/main/java/com/jediterm/terminal/ui/AwtTransformers.java", "snippet": "@Contract(\"null -> null; !null -> new\")\npublic static @Nullable TerminalColor fromAwtToTerminalColor(@Nullable java.awt.Color color) {\n r...
import static com.jediterm.terminal.ui.AwtTransformers.fromAwtToTerminalColor; import java.awt.Font; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.util.Collections; import javax.swing.KeyStroke; import org.jetbrains.annotations.NotNull; import com.jediterm.terminal.HyperlinkStyle; import com.jediterm.terminal.TerminalColor; import com.jediterm.terminal.TextStyle; import com.jediterm.terminal.emulator.ColorPalette; import com.jediterm.terminal.emulator.ColorPaletteImpl; import com.jediterm.terminal.model.LinesBuffer; import com.jediterm.terminal.model.TerminalTypeAheadSettings; import com.jediterm.terminal.ui.TerminalActionPresentation; import com.jediterm.terminal.ui.UIUtil; import pama1234.gdx.terminal.DeprecatedAwt;
7,219
package com.jediterm.terminal.ui.settings; @DeprecatedAwt public class DefaultSettingsProvider implements SettingsProvider{ @Override public @NotNull TerminalActionPresentation getOpenUrlActionPresentation() { return new TerminalActionPresentation("Open as URL",Collections.emptyList()); } @Override public @NotNull TerminalActionPresentation getCopyActionPresentation() { KeyStroke keyStroke=UIUtil.isMac ?KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.META_DOWN_MASK) // CTRL + C is used for signal; use CTRL + SHIFT + C instead :KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.CTRL_DOWN_MASK|InputEvent.SHIFT_DOWN_MASK); return new TerminalActionPresentation("Copy",keyStroke); } @Override public @NotNull TerminalActionPresentation getPasteActionPresentation() { KeyStroke keyStroke=UIUtil.isMac ?KeyStroke.getKeyStroke(KeyEvent.VK_V,InputEvent.META_DOWN_MASK) // CTRL + V is used for signal; use CTRL + SHIFT + V instead :KeyStroke.getKeyStroke(KeyEvent.VK_V,InputEvent.CTRL_DOWN_MASK|InputEvent.SHIFT_DOWN_MASK); return new TerminalActionPresentation("Paste",keyStroke); } @Override public @NotNull TerminalActionPresentation getClearBufferActionPresentation() { return new TerminalActionPresentation("Clear Buffer",UIUtil.isMac ?KeyStroke.getKeyStroke(KeyEvent.VK_K,InputEvent.META_DOWN_MASK) :KeyStroke.getKeyStroke(KeyEvent.VK_L,InputEvent.CTRL_DOWN_MASK)); } @Override public @NotNull TerminalActionPresentation getPageUpActionPresentation() { return new TerminalActionPresentation("Page Up", KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP,InputEvent.SHIFT_DOWN_MASK)); } @Override public @NotNull TerminalActionPresentation getPageDownActionPresentation() { return new TerminalActionPresentation("Page Down", KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN,InputEvent.SHIFT_DOWN_MASK)); } @Override public @NotNull TerminalActionPresentation getLineUpActionPresentation() { return new TerminalActionPresentation("Line Up",UIUtil.isMac ?KeyStroke.getKeyStroke(KeyEvent.VK_UP,InputEvent.META_DOWN_MASK) :KeyStroke.getKeyStroke(KeyEvent.VK_UP,InputEvent.CTRL_DOWN_MASK)); } @Override public @NotNull TerminalActionPresentation getLineDownActionPresentation() { return new TerminalActionPresentation("Line Down",UIUtil.isMac ?KeyStroke.getKeyStroke(KeyEvent.VK_DOWN,InputEvent.META_DOWN_MASK) :KeyStroke.getKeyStroke(KeyEvent.VK_DOWN,InputEvent.CTRL_DOWN_MASK)); } @Override public @NotNull TerminalActionPresentation getFindActionPresentation() { return new TerminalActionPresentation("Find",UIUtil.isMac ?KeyStroke.getKeyStroke(KeyEvent.VK_F,InputEvent.META_DOWN_MASK) :KeyStroke.getKeyStroke(KeyEvent.VK_F,InputEvent.CTRL_DOWN_MASK)); } @Override public @NotNull TerminalActionPresentation getSelectAllActionPresentation() { return new TerminalActionPresentation("Select All",Collections.emptyList()); } @Override public ColorPalette getTerminalColorPalette() { return UIUtil.isWindows?ColorPaletteImpl.WINDOWS_PALETTE:ColorPaletteImpl.XTERM_PALETTE; } @Override public Font getTerminalFont() { String fontName; if(UIUtil.isWindows) { fontName="Consolas"; }else if(UIUtil.isMac) { fontName="Menlo"; }else { fontName="Monospaced"; } return new Font(fontName,Font.PLAIN,(int)getTerminalFontSize()); } @Override public float getTerminalFontSize() { return 14; } @Override public TextStyle getDefaultStyle() { return new TextStyle(TerminalColor.BLACK,TerminalColor.WHITE); // return new TextStyle(TerminalColor.WHITE, TerminalColor.rgb(24, 24, 24)); } @Override public @NotNull TextStyle getSelectionColor() { return new TextStyle(TerminalColor.WHITE,TerminalColor.rgb(82,109,165)); } @Override public @NotNull TextStyle getFoundPatternColor() { return new TextStyle(TerminalColor.BLACK,TerminalColor.rgb(255,255,0)); } @Override public TextStyle getHyperlinkColor() { return new TextStyle(fromAwtToTerminalColor(java.awt.Color.BLUE),TerminalColor.WHITE); } @Override
package com.jediterm.terminal.ui.settings; @DeprecatedAwt public class DefaultSettingsProvider implements SettingsProvider{ @Override public @NotNull TerminalActionPresentation getOpenUrlActionPresentation() { return new TerminalActionPresentation("Open as URL",Collections.emptyList()); } @Override public @NotNull TerminalActionPresentation getCopyActionPresentation() { KeyStroke keyStroke=UIUtil.isMac ?KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.META_DOWN_MASK) // CTRL + C is used for signal; use CTRL + SHIFT + C instead :KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.CTRL_DOWN_MASK|InputEvent.SHIFT_DOWN_MASK); return new TerminalActionPresentation("Copy",keyStroke); } @Override public @NotNull TerminalActionPresentation getPasteActionPresentation() { KeyStroke keyStroke=UIUtil.isMac ?KeyStroke.getKeyStroke(KeyEvent.VK_V,InputEvent.META_DOWN_MASK) // CTRL + V is used for signal; use CTRL + SHIFT + V instead :KeyStroke.getKeyStroke(KeyEvent.VK_V,InputEvent.CTRL_DOWN_MASK|InputEvent.SHIFT_DOWN_MASK); return new TerminalActionPresentation("Paste",keyStroke); } @Override public @NotNull TerminalActionPresentation getClearBufferActionPresentation() { return new TerminalActionPresentation("Clear Buffer",UIUtil.isMac ?KeyStroke.getKeyStroke(KeyEvent.VK_K,InputEvent.META_DOWN_MASK) :KeyStroke.getKeyStroke(KeyEvent.VK_L,InputEvent.CTRL_DOWN_MASK)); } @Override public @NotNull TerminalActionPresentation getPageUpActionPresentation() { return new TerminalActionPresentation("Page Up", KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP,InputEvent.SHIFT_DOWN_MASK)); } @Override public @NotNull TerminalActionPresentation getPageDownActionPresentation() { return new TerminalActionPresentation("Page Down", KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN,InputEvent.SHIFT_DOWN_MASK)); } @Override public @NotNull TerminalActionPresentation getLineUpActionPresentation() { return new TerminalActionPresentation("Line Up",UIUtil.isMac ?KeyStroke.getKeyStroke(KeyEvent.VK_UP,InputEvent.META_DOWN_MASK) :KeyStroke.getKeyStroke(KeyEvent.VK_UP,InputEvent.CTRL_DOWN_MASK)); } @Override public @NotNull TerminalActionPresentation getLineDownActionPresentation() { return new TerminalActionPresentation("Line Down",UIUtil.isMac ?KeyStroke.getKeyStroke(KeyEvent.VK_DOWN,InputEvent.META_DOWN_MASK) :KeyStroke.getKeyStroke(KeyEvent.VK_DOWN,InputEvent.CTRL_DOWN_MASK)); } @Override public @NotNull TerminalActionPresentation getFindActionPresentation() { return new TerminalActionPresentation("Find",UIUtil.isMac ?KeyStroke.getKeyStroke(KeyEvent.VK_F,InputEvent.META_DOWN_MASK) :KeyStroke.getKeyStroke(KeyEvent.VK_F,InputEvent.CTRL_DOWN_MASK)); } @Override public @NotNull TerminalActionPresentation getSelectAllActionPresentation() { return new TerminalActionPresentation("Select All",Collections.emptyList()); } @Override public ColorPalette getTerminalColorPalette() { return UIUtil.isWindows?ColorPaletteImpl.WINDOWS_PALETTE:ColorPaletteImpl.XTERM_PALETTE; } @Override public Font getTerminalFont() { String fontName; if(UIUtil.isWindows) { fontName="Consolas"; }else if(UIUtil.isMac) { fontName="Menlo"; }else { fontName="Monospaced"; } return new Font(fontName,Font.PLAIN,(int)getTerminalFontSize()); } @Override public float getTerminalFontSize() { return 14; } @Override public TextStyle getDefaultStyle() { return new TextStyle(TerminalColor.BLACK,TerminalColor.WHITE); // return new TextStyle(TerminalColor.WHITE, TerminalColor.rgb(24, 24, 24)); } @Override public @NotNull TextStyle getSelectionColor() { return new TextStyle(TerminalColor.WHITE,TerminalColor.rgb(82,109,165)); } @Override public @NotNull TextStyle getFoundPatternColor() { return new TextStyle(TerminalColor.BLACK,TerminalColor.rgb(255,255,0)); } @Override public TextStyle getHyperlinkColor() { return new TextStyle(fromAwtToTerminalColor(java.awt.Color.BLUE),TerminalColor.WHITE); } @Override
public HyperlinkStyle.HighlightMode getHyperlinkHighlightingMode() {
1
2023-10-27 05:47:39+00:00
12k
llllllxy/tinycloud
tinycloud-user/src/main/java/org/tinycloud/user/controller/TestController.java
[ { "identifier": "RedisClient", "path": "tinycloud-common/src/main/java/org/tinycloud/common/config/redis/RedisClient.java", "snippet": "public class RedisClient {\n final static Logger log = LoggerFactory.getLogger(RedisClient.class);\n\n private RedisTemplate<String, Object> redisTemplate;\n\n ...
import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.tinycloud.common.config.redis.RedisClient; import org.tinycloud.common.model.ApiResult; import org.tinycloud.user.config.TinyCloudUserConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.HashMap; import java.util.Map;
9,136
package org.tinycloud.user.controller; @Api(tags = "用户中心-测试", value = "用户中心-测试") @RestController @RequestMapping("/test") public class TestController { private static final Logger log = LoggerFactory.getLogger(TestController.class); @Autowired private TinyCloudUserConfig tinyCloudUserConfig; @Autowired private RedisClient redisClient; @ApiOperation(value = "测试配置动态刷新", notes = "测试配置动态刷新") @RequestMapping(value = "/testConfig", method = RequestMethod.GET)
package org.tinycloud.user.controller; @Api(tags = "用户中心-测试", value = "用户中心-测试") @RestController @RequestMapping("/test") public class TestController { private static final Logger log = LoggerFactory.getLogger(TestController.class); @Autowired private TinyCloudUserConfig tinyCloudUserConfig; @Autowired private RedisClient redisClient; @ApiOperation(value = "测试配置动态刷新", notes = "测试配置动态刷新") @RequestMapping(value = "/testConfig", method = RequestMethod.GET)
public ApiResult<?> testConfig() {
1
2023-10-28 02:05:15+00:00
12k
llllllxy/bluewind-base
src/main/java/com/bluewind/base/module/system/demoperson/controller/DemoPersonController.java
[ { "identifier": "UserInfoUtil", "path": "src/main/java/com/bluewind/base/common/config/auth/util/UserInfoUtil.java", "snippet": "public class UserInfoUtil {\n private static final Logger logger = LoggerFactory.getLogger(UserInfoUtil.class);\n\n\n private static RedisUtils redisUtils;\n\n privat...
import com.bluewind.base.common.annotation.DataSource; import com.bluewind.base.common.annotation.LogAround; import com.bluewind.base.common.config.auth.util.UserInfoUtil; import com.bluewind.base.common.util.redis.RedisUtils; import com.bluewind.base.module.system.demoperson.service.DemoPersonService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map;
8,295
package com.bluewind.base.module.system.demoperson.controller; /** * @author liuxingyu01 * @date 2021-09-12-21:17 **/ @Api(value = "系统用户管理控制器", tags = "系统用户管理控制器") @Controller @RequestMapping("/demoperson") public class DemoPersonController { private static Logger logger = LoggerFactory.getLogger(DemoPersonController.class); @Autowired private DemoPersonService demoPersonService; @Autowired private RedisUtils redisUtils; @LogAround("testAuth") @RequestMapping(value = "/testAuth",method = RequestMethod.GET) @ResponseBody public Object testAuth() { logger.info("测试会话控制成功"); return "测试会话控制成功"; } @LogAround("testPermissions") @RequiresPermissions("system:user:init") @RequestMapping(value = "/testPermissions",method = RequestMethod.GET) @ResponseBody public Object testPermissions() { logger.info("测试testPermissions成功");
package com.bluewind.base.module.system.demoperson.controller; /** * @author liuxingyu01 * @date 2021-09-12-21:17 **/ @Api(value = "系统用户管理控制器", tags = "系统用户管理控制器") @Controller @RequestMapping("/demoperson") public class DemoPersonController { private static Logger logger = LoggerFactory.getLogger(DemoPersonController.class); @Autowired private DemoPersonService demoPersonService; @Autowired private RedisUtils redisUtils; @LogAround("testAuth") @RequestMapping(value = "/testAuth",method = RequestMethod.GET) @ResponseBody public Object testAuth() { logger.info("测试会话控制成功"); return "测试会话控制成功"; } @LogAround("testPermissions") @RequiresPermissions("system:user:init") @RequestMapping(value = "/testPermissions",method = RequestMethod.GET) @ResponseBody public Object testPermissions() { logger.info("测试testPermissions成功");
logger.info("UserInfoUtil.getUserName() = {}", UserInfoUtil.getUserName());
0
2023-10-26 10:02:07+00:00
12k
danielbatres/orthodontic-dentistry-clinical-management
src/com/view/dashboard/ConsultaTarget.java
[ { "identifier": "ApplicationContext", "path": "src/com/context/ApplicationContext.java", "snippet": "public class ApplicationContext {\r\n public static SesionUsuario sesionUsuario;\r\n public static LoadingApp loading = new LoadingApp();\r\n public static LoadingApplication loadingApplication ...
import com.context.ApplicationContext; import com.context.ChoosedPalette; import com.context.StateColors; import com.model.ConsultaModel; import com.utils.Styles;
10,784
); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 10, Short.MAX_VALUE) ); container.add(jPanel3, java.awt.BorderLayout.PAGE_END); jPanel4.setMinimumSize(new java.awt.Dimension(10, 100)); jPanel4.setOpaque(false); jPanel4.setPreferredSize(new java.awt.Dimension(10, 90)); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 10, Short.MAX_VALUE) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 120, Short.MAX_VALUE) ); container.add(jPanel4, java.awt.BorderLayout.LINE_START); jPanel5.setMinimumSize(new java.awt.Dimension(10, 100)); jPanel5.setOpaque(false); jPanel5.setPreferredSize(new java.awt.Dimension(10, 90)); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 10, Short.MAX_VALUE) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 120, Short.MAX_VALUE) ); container.add(jPanel5, java.awt.BorderLayout.LINE_END); jPanel6.setOpaque(false); jPanel6.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); tratamientoContainer.setkEndColor(new java.awt.Color(204, 204, 204)); tratamientoContainer.setkStartColor(new java.awt.Color(204, 204, 204)); tratamientoContainer.setMaximumSize(new java.awt.Dimension(32767, 25)); tratamientoContainer.setMinimumSize(new java.awt.Dimension(100, 25)); tratamientoContainer.setOpaque(false); tratamientoText.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N tratamientoText.setForeground(new java.awt.Color(51, 51, 51)); tratamientoText.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); tratamientoText.setText("Tratamiento"); javax.swing.GroupLayout tratamientoContainerLayout = new javax.swing.GroupLayout(tratamientoContainer); tratamientoContainer.setLayout(tratamientoContainerLayout); tratamientoContainerLayout.setHorizontalGroup( tratamientoContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tratamientoText, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE) ); tratamientoContainerLayout.setVerticalGroup( tratamientoContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tratamientoText, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE) ); jPanel6.add(tratamientoContainer, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, 30)); facturarButton.setkEndColor(new java.awt.Color(204, 204, 204)); facturarButton.setkStartColor(new java.awt.Color(204, 204, 204)); facturarButton.setMaximumSize(new java.awt.Dimension(32767, 25)); facturarButton.setMinimumSize(new java.awt.Dimension(100, 25)); facturarButton.setOpaque(false); facturarButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { facturarButtonMouseClicked(evt); } }); factura.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 12)); // NOI18N factura.setForeground(new java.awt.Color(51, 51, 51)); factura.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); factura.setText("Facturar"); factura.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); javax.swing.GroupLayout facturarButtonLayout = new javax.swing.GroupLayout(facturarButton); facturarButton.setLayout(facturarButtonLayout); facturarButtonLayout.setHorizontalGroup( facturarButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(factura, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE) ); facturarButtonLayout.setVerticalGroup( facturarButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(factura, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE) ); jPanel6.add(facturarButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 90, 120, 30)); nombres.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 14)); // NOI18N nombres.setForeground(new java.awt.Color(51, 51, 51)); nombres.setText("Damian Alexander García Lewis"); jPanel6.add(nombres, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 40, 260, -1)); fechaText.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N fechaText.setText("19/09/22 06:54 AM"); jPanel6.add(fechaText, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 60, 220, 20)); contactoText.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 12)); // NOI18N contactoText.setForeground(new java.awt.Color(51, 51, 51)); contactoText.setText("6450 0770"); contactoText.setToolTipText("Contacto"); jPanel6.add(contactoText, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 90, 120, 30)); container.add(jPanel6, java.awt.BorderLayout.CENTER); add(container, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents private void facturarButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_facturarButtonMouseClicked
package com.view.dashboard; /** * * @author Daniel Batres */ public class ConsultaTarget extends Styles { private final ConsultaModel CONSULTA_MODEL; /** * Creates new form ConsultaTarget * @param consulta */ public ConsultaTarget(ConsultaModel consulta) { initComponents(); styleMyComponentBaby(); CONSULTA_MODEL = consulta; tratamientoText.setText(consulta.getTratamientoDeConsulta()); nombres.setText(consulta.getNombres() + " " + consulta.getApellidos()); fechaText.setText(consulta.getDiaDeConsulta() + "/" + consulta.getMesDeConsulta() + "/" + consulta.getAnnioDeConsulta()); contactoText.setText(consulta.getContacto()); } @Override public void addTitlesAndSubtitles() { TITLES_AND_SUBTITLES.add(nombres); TITLES_AND_SUBTITLES.add(contactoText); } @Override public void addPlainText() { PLAIN_TEXT.add(fechaText); } @Override public void addContainers() { CONTAINERS.add(container); } @Override public void colorBasics() { paintAll(); facturarButton.setkStartColor(ChoosedPalette.getMidColor()); facturarButton.setkStartColor(ChoosedPalette.getMidColor()); factura.setForeground(ChoosedPalette.getWhite()); } public void tipoTratamiento() { switch (tratamientoText.getText()) { case "Odontolog\u00eda": paintOnePlainText(tratamientoText, ChoosedPalette.getMidColor()); paintOneContainer(tratamientoContainer, ChoosedPalette.getPrimaryLightColor()); break; case "Ortodoncia": paintOnePlainText(tratamientoText, StateColors.getSuccess()); paintOneContainer(tratamientoContainer, ChoosedPalette.getSecondaryLightColor()); break; default: break; } } @Override public void light() { container.setkFillBackground(false); tipoTratamiento(); } @Override public void dark() { container.setkFillBackground(true); container.setkStartColor(ChoosedPalette.getSecondaryBackground()); container.setkEndColor(ChoosedPalette.getSecondaryBackground()); container.repaint(); tipoTratamiento(); tratamientoText.setForeground(ChoosedPalette.getWhite()); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); container = new com.k33ptoo.components.KGradientPanel(); jPanel2 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); jPanel5 = new javax.swing.JPanel(); jPanel6 = new javax.swing.JPanel(); tratamientoContainer = new com.k33ptoo.components.KGradientPanel(); tratamientoText = new javax.swing.JLabel(); facturarButton = new com.k33ptoo.components.KGradientPanel(); factura = new javax.swing.JLabel(); nombres = new javax.swing.JLabel(); fechaText = new javax.swing.JLabel(); contactoText = new javax.swing.JLabel(); setMaximumSize(new java.awt.Dimension(123434, 150)); setMinimumSize(new java.awt.Dimension(250, 150)); setOpaque(false); setPreferredSize(new java.awt.Dimension(250, 150)); setLayout(new java.awt.BorderLayout()); jPanel1.setMinimumSize(new java.awt.Dimension(100, 10)); jPanel1.setOpaque(false); jPanel1.setPreferredSize(new java.awt.Dimension(250, 10)); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 289, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 10, Short.MAX_VALUE) ); add(jPanel1, java.awt.BorderLayout.PAGE_END); container.setkEndColor(new java.awt.Color(204, 204, 204)); container.setkFillBackground(false); container.setkStartColor(new java.awt.Color(204, 204, 204)); container.setOpaque(false); container.setLayout(new java.awt.BorderLayout()); jPanel2.setMinimumSize(new java.awt.Dimension(100, 10)); jPanel2.setOpaque(false); jPanel2.setPreferredSize(new java.awt.Dimension(250, 10)); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 289, Short.MAX_VALUE) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 10, Short.MAX_VALUE) ); container.add(jPanel2, java.awt.BorderLayout.PAGE_START); jPanel3.setMinimumSize(new java.awt.Dimension(100, 10)); jPanel3.setOpaque(false); jPanel3.setPreferredSize(new java.awt.Dimension(250, 10)); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 289, Short.MAX_VALUE) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 10, Short.MAX_VALUE) ); container.add(jPanel3, java.awt.BorderLayout.PAGE_END); jPanel4.setMinimumSize(new java.awt.Dimension(10, 100)); jPanel4.setOpaque(false); jPanel4.setPreferredSize(new java.awt.Dimension(10, 90)); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 10, Short.MAX_VALUE) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 120, Short.MAX_VALUE) ); container.add(jPanel4, java.awt.BorderLayout.LINE_START); jPanel5.setMinimumSize(new java.awt.Dimension(10, 100)); jPanel5.setOpaque(false); jPanel5.setPreferredSize(new java.awt.Dimension(10, 90)); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 10, Short.MAX_VALUE) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 120, Short.MAX_VALUE) ); container.add(jPanel5, java.awt.BorderLayout.LINE_END); jPanel6.setOpaque(false); jPanel6.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); tratamientoContainer.setkEndColor(new java.awt.Color(204, 204, 204)); tratamientoContainer.setkStartColor(new java.awt.Color(204, 204, 204)); tratamientoContainer.setMaximumSize(new java.awt.Dimension(32767, 25)); tratamientoContainer.setMinimumSize(new java.awt.Dimension(100, 25)); tratamientoContainer.setOpaque(false); tratamientoText.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N tratamientoText.setForeground(new java.awt.Color(51, 51, 51)); tratamientoText.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); tratamientoText.setText("Tratamiento"); javax.swing.GroupLayout tratamientoContainerLayout = new javax.swing.GroupLayout(tratamientoContainer); tratamientoContainer.setLayout(tratamientoContainerLayout); tratamientoContainerLayout.setHorizontalGroup( tratamientoContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tratamientoText, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE) ); tratamientoContainerLayout.setVerticalGroup( tratamientoContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tratamientoText, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE) ); jPanel6.add(tratamientoContainer, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, 30)); facturarButton.setkEndColor(new java.awt.Color(204, 204, 204)); facturarButton.setkStartColor(new java.awt.Color(204, 204, 204)); facturarButton.setMaximumSize(new java.awt.Dimension(32767, 25)); facturarButton.setMinimumSize(new java.awt.Dimension(100, 25)); facturarButton.setOpaque(false); facturarButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { facturarButtonMouseClicked(evt); } }); factura.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 12)); // NOI18N factura.setForeground(new java.awt.Color(51, 51, 51)); factura.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); factura.setText("Facturar"); factura.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); javax.swing.GroupLayout facturarButtonLayout = new javax.swing.GroupLayout(facturarButton); facturarButton.setLayout(facturarButtonLayout); facturarButtonLayout.setHorizontalGroup( facturarButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(factura, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE) ); facturarButtonLayout.setVerticalGroup( facturarButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(factura, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE) ); jPanel6.add(facturarButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 90, 120, 30)); nombres.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 14)); // NOI18N nombres.setForeground(new java.awt.Color(51, 51, 51)); nombres.setText("Damian Alexander García Lewis"); jPanel6.add(nombres, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 40, 260, -1)); fechaText.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N fechaText.setText("19/09/22 06:54 AM"); jPanel6.add(fechaText, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 60, 220, 20)); contactoText.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 12)); // NOI18N contactoText.setForeground(new java.awt.Color(51, 51, 51)); contactoText.setText("6450 0770"); contactoText.setToolTipText("Contacto"); jPanel6.add(contactoText, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 90, 120, 30)); container.add(jPanel6, java.awt.BorderLayout.CENTER); add(container, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents private void facturarButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_facturarButtonMouseClicked
ApplicationContext.facturaData.setPacientName(nombres.getText(), CONSULTA_MODEL.getId());
0
2023-10-26 19:35:40+00:00
12k
kdetard/koki
app/src/main/java/io/github/kdetard/koki/feature/main/MainController.java
[ { "identifier": "AssetsController", "path": "app/src/main/java/io/github/kdetard/koki/feature/assets/AssetsController.java", "snippet": "public class AssetsController extends MapController {\n @EntryPoint\n @InstallIn(SingletonComponent.class)\n interface AssetsEntryPoint {\n OpenRemoteS...
import android.view.View; import androidx.annotation.NonNull; import com.bluelinelabs.conductor.Router; import com.bluelinelabs.conductor.RouterTransaction; import com.bluelinelabs.conductor.changehandler.FadeChangeHandler; import com.bluelinelabs.conductor.viewpager2.RouterStateAdapter; import java.util.Map; import java.util.Objects; import io.github.kdetard.koki.R; import io.github.kdetard.koki.databinding.ControllerMainBinding; import io.github.kdetard.koki.feature.assets.AssetsController; import io.github.kdetard.koki.feature.base.BaseController; import io.github.kdetard.koki.feature.home.HomeController; import io.github.kdetard.koki.feature.monitoring.MonitoringController; import io.github.kdetard.koki.feature.settings.SettingsMainController;
8,365
package io.github.kdetard.koki.feature.main; public class MainController extends BaseController { ControllerMainBinding binding; RouterStateAdapter pagerAdapter; private static final Map<Integer, Integer> navBarMap = Map.of( R.id.nav_home, 0, R.id.nav_assets, 1, R.id.nav_monitoring, 2, R.id.nav_settings, 3 ); private int currentNavItemId = R.id.nav_home; public MainController() { super(R.layout.controller_main); pagerAdapter = new RouterStateAdapter(this) { @Override public void configureRouter(@NonNull Router router, int i) { if (!router.hasRootController()) { var page = switch (i) { case 0 -> new HomeController(); case 1 -> new AssetsController(); case 2 -> new MonitoringController();
package io.github.kdetard.koki.feature.main; public class MainController extends BaseController { ControllerMainBinding binding; RouterStateAdapter pagerAdapter; private static final Map<Integer, Integer> navBarMap = Map.of( R.id.nav_home, 0, R.id.nav_assets, 1, R.id.nav_monitoring, 2, R.id.nav_settings, 3 ); private int currentNavItemId = R.id.nav_home; public MainController() { super(R.layout.controller_main); pagerAdapter = new RouterStateAdapter(this) { @Override public void configureRouter(@NonNull Router router, int i) { if (!router.hasRootController()) { var page = switch (i) { case 0 -> new HomeController(); case 1 -> new AssetsController(); case 2 -> new MonitoringController();
case 3 -> new SettingsMainController();
4
2023-10-30 00:44:59+00:00
12k
inceptive-tech/ENTSOEDataRetrieval
src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/csv/transformers/CSVTransformer.java
[ { "identifier": "DataRetrievalError", "path": "src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/exceptions/DataRetrievalError.java", "snippet": "public class DataRetrievalError extends RuntimeException{\n private static final Logger LOGGER = LogManager.getLogger(DataRetrievalError.class);\n\n ...
import java.io.BufferedWriter; import java.io.OutputStream; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; import java.util.stream.IntStream; import javax.xml.datatype.DatatypeConstants; import javax.xml.datatype.Duration; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import tech.inceptive.ai4czc.entsoedataretrieval.csv.ColumnDefinition; import tech.inceptive.ai4czc.entsoedataretrieval.exceptions.DataRetrievalError; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.Point; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.TimeSeries;
9,079
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package tech.inceptive.ai4czc.entsoedataretrieval.csv.transformers; /** * CSVTransformer. There may be many csv transformer for one column, and some periods can overlap. But these * overlappings are equal. * * @author Andres Bel Alonso */ public abstract class CSVTransformer { private static final Logger LOGGER = LogManager.getLogger(CSVTransformer.class); /** * A time serie with a selected point. Selected period : the period index selected on ts Selected point : the * selected index on ts.getPeriod.getPoint */ public record MarkedTS(TimeSeries ts, int selectedPeriod, int selectedPoint) { /** * The value of the selected point of this time serie * * @return */ public int getSelectedPointValue() { return ts.getPeriod().get(selectedPeriod).getPoint().get(selectedPoint).getQuantity().intValue(); } } ; private final String csvSeparator; private final String csvEscapeChar; private List<ColumnDefinition> columnDefinition = null; public CSVTransformer(String csvSeparator, String csvEscapeChar) { this.csvSeparator = csvSeparator; this.csvEscapeChar = csvEscapeChar; } public List<ColumnDefinition> getColumnDefinition() { if (columnDefinition == null) { columnDefinition = computeColumnDef(); } return columnDefinition; } /** * Writes the next line of the given time stamp.Starts with the separator. * * @param os * @return true if the entry was writed, false otherwise */ public abstract boolean writeNextEntry(LocalDateTime timeStamp, BufferedWriter os); protected abstract List<ColumnDefinition> computeColumnDef(); /** * * @param startingPoint * @param timeStamp * @return */ protected static List<GLDocumentCSVTransformer.MarkedTS> getPeriodForTimeStamp(List<TimeSeries> timeSeries, LocalDateTime timeStamp) { // search for the correct ts // compute the corresponding positions // we assume that is there is many point of interest, they will be in different ts List<Integer> tsPositions = computeTSPosition(timeSeries,timeStamp); if (tsPositions.isEmpty()) { return new ArrayList<>(); } // start of the time series List<GLDocumentCSVTransformer.MarkedTS> res = new ArrayList<>(); for (int tsPosition : tsPositions) { for (int periodPosition = 0; periodPosition < timeSeries.size(); periodPosition++) { LocalDateTime startDT = timeSeries.get(tsPosition).getPeriod().get(0).getTimeInterval().getLDTStart(); int resolutionInt = getResolutionInMinutes(timeSeries.get(tsPosition).getPeriod().get(0).getResolution()); long gapMinutes = ChronoUnit.MINUTES.between(startDT, timeStamp); long selectPosition = (gapMinutes / resolutionInt); if (selectPosition > Integer.MAX_VALUE) { throw new DataRetrievalError("The position to select is to big. Please use smaller queries"); }
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package tech.inceptive.ai4czc.entsoedataretrieval.csv.transformers; /** * CSVTransformer. There may be many csv transformer for one column, and some periods can overlap. But these * overlappings are equal. * * @author Andres Bel Alonso */ public abstract class CSVTransformer { private static final Logger LOGGER = LogManager.getLogger(CSVTransformer.class); /** * A time serie with a selected point. Selected period : the period index selected on ts Selected point : the * selected index on ts.getPeriod.getPoint */ public record MarkedTS(TimeSeries ts, int selectedPeriod, int selectedPoint) { /** * The value of the selected point of this time serie * * @return */ public int getSelectedPointValue() { return ts.getPeriod().get(selectedPeriod).getPoint().get(selectedPoint).getQuantity().intValue(); } } ; private final String csvSeparator; private final String csvEscapeChar; private List<ColumnDefinition> columnDefinition = null; public CSVTransformer(String csvSeparator, String csvEscapeChar) { this.csvSeparator = csvSeparator; this.csvEscapeChar = csvEscapeChar; } public List<ColumnDefinition> getColumnDefinition() { if (columnDefinition == null) { columnDefinition = computeColumnDef(); } return columnDefinition; } /** * Writes the next line of the given time stamp.Starts with the separator. * * @param os * @return true if the entry was writed, false otherwise */ public abstract boolean writeNextEntry(LocalDateTime timeStamp, BufferedWriter os); protected abstract List<ColumnDefinition> computeColumnDef(); /** * * @param startingPoint * @param timeStamp * @return */ protected static List<GLDocumentCSVTransformer.MarkedTS> getPeriodForTimeStamp(List<TimeSeries> timeSeries, LocalDateTime timeStamp) { // search for the correct ts // compute the corresponding positions // we assume that is there is many point of interest, they will be in different ts List<Integer> tsPositions = computeTSPosition(timeSeries,timeStamp); if (tsPositions.isEmpty()) { return new ArrayList<>(); } // start of the time series List<GLDocumentCSVTransformer.MarkedTS> res = new ArrayList<>(); for (int tsPosition : tsPositions) { for (int periodPosition = 0; periodPosition < timeSeries.size(); periodPosition++) { LocalDateTime startDT = timeSeries.get(tsPosition).getPeriod().get(0).getTimeInterval().getLDTStart(); int resolutionInt = getResolutionInMinutes(timeSeries.get(tsPosition).getPeriod().get(0).getResolution()); long gapMinutes = ChronoUnit.MINUTES.between(startDT, timeStamp); long selectPosition = (gapMinutes / resolutionInt); if (selectPosition > Integer.MAX_VALUE) { throw new DataRetrievalError("The position to select is to big. Please use smaller queries"); }
List<Point> points = timeSeries.get(tsPosition).getPeriod().get(0).getPoint();
1
2023-10-30 09:09:53+00:00
12k
EricFan2002/SC2002
src/app/ui/overlayactions/OverlayTextInputAction.java
[ { "identifier": "WidgetButton", "path": "src/app/ui/widgets/WidgetButton.java", "snippet": "public class WidgetButton extends Widget implements ITextInput, ISelectable{\n private boolean pressed;\n\n /**\n * Constructs a WidgetButton with specified position, length, and text.\n * The butto...
import app.ui.widgets.WidgetButton; import app.ui.widgets.WidgetLabel; import app.ui.widgets.WidgetTextBox; import app.ui.windows.ICallBack; import app.ui.windows.Window; import app.ui.windows.WindowOverlayClass; import java.util.List;
7,285
package app.ui.overlayactions; /** * The {@code OverlayTextInputAction} class represents an overlay window for receiving text input with options to enter or cancel. * It extends the {@code WindowOverlayClass} and implements the {@code ICallBack} interface. */ public class OverlayTextInputAction extends WindowOverlayClass { /** * The button to cancel the text input. */ WidgetButton cancelButton; /** * The selected choice index. */ private int chose; /** * The selected choice string. */ private String choseString; /** * The list of choices presented to the user. */ List<WidgetButton> choices; /** * The callback window to notify upon completion. */
package app.ui.overlayactions; /** * The {@code OverlayTextInputAction} class represents an overlay window for receiving text input with options to enter or cancel. * It extends the {@code WindowOverlayClass} and implements the {@code ICallBack} interface. */ public class OverlayTextInputAction extends WindowOverlayClass { /** * The button to cancel the text input. */ WidgetButton cancelButton; /** * The selected choice index. */ private int chose; /** * The selected choice string. */ private String choseString; /** * The list of choices presented to the user. */ List<WidgetButton> choices; /** * The callback window to notify upon completion. */
Window callbackWindow;
4
2023-11-01 05:18:29+00:00
12k
LLNL/response
src/main/java/gov/llnl/gnem/response/ToResponseLookupKey.java
[ { "identifier": "ChannelMatchPolicy", "path": "src/main/java/com/isti/jevalresp/ChannelMatchPolicy.java", "snippet": "public class ChannelMatchPolicy implements Serializable {\r\n\r\n private static final long serialVersionUID = 6639216586376908870L;\r\n\r\n public static enum Policy {\r\n ...
import java.util.logging.Logger; import javax.measure.Quantity; import javax.measure.Unit; import com.isti.jevalresp.ChannelMatchPolicy; import com.isti.jevalresp.ResponseUnits; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.reflect.Field; import java.util.Objects; import java.util.logging.Level;
7,581
/*- * #%L * Seismic Response Processing Module * LLNL-CODE-856351 * This work was performed under the auspices of the U.S. Department of Energy * by Lawrence Livermore National Laboratory under Contract DE-AC52-07NA27344. * %% * Copyright (C) 2023 Lawrence Livermore National Laboratory * %% * 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. * #L% */ package gov.llnl.gnem.response; /** * * @author dodge1 */ public class ToResponseLookupKey implements Serializable{ private static final long serialVersionUID = -2181120151631745321L; private final int nfft; private final double samprate; private final String network; private final String sta; private final String chan; private final String locid; private final ResponseMetaData rmd; private final ChannelMatchPolicy policy; private final Unit<?> requestedUnits; private final Unit<? extends Quantity<?>> forcedInputUnits; private void writeObject(ObjectOutputStream s) throws IOException { s.writeInt(nfft); s.writeDouble(samprate); s.writeObject(network); s.writeObject(sta); s.writeObject(chan); s.writeObject(locid); s.writeObject(rmd); s.writeObject(policy); s.writeObject(requestedUnits.toString()); s.writeObject(forcedInputUnits != null ? forcedInputUnits.toString() : null); } private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { try { Class type = ToResponseLookupKey.class; Field field = type.getDeclaredField("nfft"); // make the field non final field.setAccessible(true); field.set(this, s.readInt()); // make the field final again field.setAccessible(false); field = type.getDeclaredField("samprate"); field.setAccessible(true); field.set(this, s.readDouble()); field.setAccessible(false); field = type.getDeclaredField("network"); field.setAccessible(true); field.set(this, (String)s.readObject()); field.setAccessible(false); field = type.getDeclaredField("sta"); field.setAccessible(true); field.set(this, (String)s.readObject()); field.setAccessible(false); field = type.getDeclaredField("chan"); field.setAccessible(true); field.set(this, (String)s.readObject()); field.setAccessible(false); field = type.getDeclaredField("locid"); field.setAccessible(true); field.set(this, (String)s.readObject()); field.setAccessible(false); field = type.getDeclaredField("rmd"); field.setAccessible(true); field.set(this, (ResponseMetaData)s.readObject()); field.setAccessible(false); field = type.getDeclaredField("policy"); field.setAccessible(true); field.set(this, (ChannelMatchPolicy)s.readObject()); field.setAccessible(false); String tmp = (String) s.readObject(); field = type.getDeclaredField("requestedUnits"); field.setAccessible(true);
/*- * #%L * Seismic Response Processing Module * LLNL-CODE-856351 * This work was performed under the auspices of the U.S. Department of Energy * by Lawrence Livermore National Laboratory under Contract DE-AC52-07NA27344. * %% * Copyright (C) 2023 Lawrence Livermore National Laboratory * %% * 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. * #L% */ package gov.llnl.gnem.response; /** * * @author dodge1 */ public class ToResponseLookupKey implements Serializable{ private static final long serialVersionUID = -2181120151631745321L; private final int nfft; private final double samprate; private final String network; private final String sta; private final String chan; private final String locid; private final ResponseMetaData rmd; private final ChannelMatchPolicy policy; private final Unit<?> requestedUnits; private final Unit<? extends Quantity<?>> forcedInputUnits; private void writeObject(ObjectOutputStream s) throws IOException { s.writeInt(nfft); s.writeDouble(samprate); s.writeObject(network); s.writeObject(sta); s.writeObject(chan); s.writeObject(locid); s.writeObject(rmd); s.writeObject(policy); s.writeObject(requestedUnits.toString()); s.writeObject(forcedInputUnits != null ? forcedInputUnits.toString() : null); } private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { try { Class type = ToResponseLookupKey.class; Field field = type.getDeclaredField("nfft"); // make the field non final field.setAccessible(true); field.set(this, s.readInt()); // make the field final again field.setAccessible(false); field = type.getDeclaredField("samprate"); field.setAccessible(true); field.set(this, s.readDouble()); field.setAccessible(false); field = type.getDeclaredField("network"); field.setAccessible(true); field.set(this, (String)s.readObject()); field.setAccessible(false); field = type.getDeclaredField("sta"); field.setAccessible(true); field.set(this, (String)s.readObject()); field.setAccessible(false); field = type.getDeclaredField("chan"); field.setAccessible(true); field.set(this, (String)s.readObject()); field.setAccessible(false); field = type.getDeclaredField("locid"); field.setAccessible(true); field.set(this, (String)s.readObject()); field.setAccessible(false); field = type.getDeclaredField("rmd"); field.setAccessible(true); field.set(this, (ResponseMetaData)s.readObject()); field.setAccessible(false); field = type.getDeclaredField("policy"); field.setAccessible(true); field.set(this, (ChannelMatchPolicy)s.readObject()); field.setAccessible(false); String tmp = (String) s.readObject(); field = type.getDeclaredField("requestedUnits"); field.setAccessible(true);
field.set(this, tmp != null ? ResponseUnits.parse(tmp) : null);
1
2023-10-30 21:06:43+00:00
12k
TNO/PPS
plugins/nl.esi.pps.tmsc.analysis.ui/src/nl/esi/pps/tmsc/analysis/ui/handlers/NormalizeTimingHandler.java
[ { "identifier": "DEFAULT_LOG_SEVERITIES", "path": "plugins/nl.esi.pps.common.ide.ui/src/nl/esi/pps/common/ide/ui/jobs/StatusReportingJob.java", "snippet": "public static final Collection<Integer> DEFAULT_LOG_SEVERITIES = Collections\n\t\t.unmodifiableCollection(Arrays.asList(IStatus.WARNING, IStatus.ERR...
import static nl.esi.pps.common.ide.ui.jobs.StatusReportingJob.DEFAULT_LOG_SEVERITIES; import static nl.esi.pps.tmsc.analysis.ui.Activator.getPluginID; import static nl.esi.pps.ui.handlers.AbstractCommandHandler.DEFAULT_DIALOG_SEVERITIES; import static org.eclipse.core.runtime.IStatus.ERROR; import static org.eclipse.lsat.common.queries.QueryableIterable.from; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Named; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.e4.core.di.annotations.CanExecute; import org.eclipse.e4.core.di.annotations.Evaluate; import org.eclipse.e4.core.di.annotations.Execute; import org.eclipse.e4.core.di.annotations.Optional; import org.eclipse.e4.ui.services.IServiceConstants; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.lsat.common.emf.common.util.URIHelper; import org.eclipse.lsat.common.emf.ecore.resource.Persistor; import org.eclipse.lsat.common.emf.ecore.resource.PersistorFactory; import org.eclipse.lsat.common.queries.QueryableIterable; import nl.esi.pps.common.core.runtime.ErrorStatusException; import nl.esi.pps.common.core.runtime.FailOnErrorStatus; import nl.esi.pps.common.core.runtime.jobs.IStatusJobFunction; import nl.esi.pps.common.core.runtime.jobs.JobUtils; import nl.esi.pps.common.ide.ui.jobs.StatusReportingJob; import nl.esi.pps.preferences.PPSPreferences; import nl.esi.pps.tmsc.FullScopeTMSC; import nl.esi.pps.tmsc.TmscPlugin; import nl.esi.pps.tmsc.analysis.NormalizeTiming;
9,188
/* * Copyright (c) 2018-2023 TNO and Contributors to the GitHub community * * This program and the accompanying materials are made available * under the terms of the MIT License which is available at * https://opensource.org/licenses/MIT * * SPDX-License-Identifier: MIT */ package nl.esi.pps.tmsc.analysis.ui.handlers; public class NormalizeTimingHandler { @Evaluate @CanExecute public boolean canExecute(@Named(IServiceConstants.ACTIVE_SELECTION) @Optional IStructuredSelection selection) { if (selection == null || selection.size() != 1 || !PPSPreferences.isAdvancedFeaturesEnabled()) { return false; } return from((Iterable<?>) selection).forAll(e -> e instanceof IFile && TmscPlugin.isTmscFile((IFile) e)); } @Execute public void execute(@Named(IServiceConstants.ACTIVE_SELECTION) IStructuredSelection selection) { IFile modelIFile = (IFile) selection.getFirstElement(); IStatusJobFunction jobFunction = monitor -> doJob(modelIFile, monitor); String jobName = "Normalize timing"; Job job = new StatusReportingJob(jobName, jobFunction, getPluginID(), DEFAULT_DIALOG_SEVERITIES,
/* * Copyright (c) 2018-2023 TNO and Contributors to the GitHub community * * This program and the accompanying materials are made available * under the terms of the MIT License which is available at * https://opensource.org/licenses/MIT * * SPDX-License-Identifier: MIT */ package nl.esi.pps.tmsc.analysis.ui.handlers; public class NormalizeTimingHandler { @Evaluate @CanExecute public boolean canExecute(@Named(IServiceConstants.ACTIVE_SELECTION) @Optional IStructuredSelection selection) { if (selection == null || selection.size() != 1 || !PPSPreferences.isAdvancedFeaturesEnabled()) { return false; } return from((Iterable<?>) selection).forAll(e -> e instanceof IFile && TmscPlugin.isTmscFile((IFile) e)); } @Execute public void execute(@Named(IServiceConstants.ACTIVE_SELECTION) IStructuredSelection selection) { IFile modelIFile = (IFile) selection.getFirstElement(); IStatusJobFunction jobFunction = monitor -> doJob(modelIFile, monitor); String jobName = "Normalize timing"; Job job = new StatusReportingJob(jobName, jobFunction, getPluginID(), DEFAULT_DIALOG_SEVERITIES,
DEFAULT_LOG_SEVERITIES);
0
2023-10-30 16:00:25+00:00
12k
CERBON-MODS/Bosses-of-Mass-Destruction-FORGE
src/main/java/com/cerbon/bosses_of_mass_destruction/mixin/BossHealthOverlayMixin.java
[ { "identifier": "NodeBossBarRenderer", "path": "src/main/java/com/cerbon/bosses_of_mass_destruction/client/render/NodeBossBarRenderer.java", "snippet": "public class NodeBossBarRenderer {\n private final String entityTypeKey;\n private final List<Float> hpPercentages;\n private final ResourceLo...
import com.cerbon.bosses_of_mass_destruction.client.render.NodeBossBarRenderer; import com.cerbon.bosses_of_mass_destruction.entity.BMDEntities; import com.cerbon.bosses_of_mass_destruction.entity.custom.lich.LichUtils; import com.cerbon.bosses_of_mass_destruction.entity.custom.obsidilith.ObsidilithUtils; import com.cerbon.bosses_of_mass_destruction.entity.custom.void_blossom.VoidBlossomEntity; import com.cerbon.bosses_of_mass_destruction.util.BMDConstants; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.BossHealthOverlay; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.BossEvent; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
7,546
package com.cerbon.bosses_of_mass_destruction.mixin; @Mixin(BossHealthOverlay.class) public class BossHealthOverlayMixin { @Shadow @Final private static ResourceLocation[] BAR_BACKGROUND_SPRITES; @Shadow @Final private static ResourceLocation[] BAR_PROGRESS_SPRITES; @Inject(method = "drawBar(Lnet/minecraft/client/gui/GuiGraphics;IILnet/minecraft/world/BossEvent;)V", at = @At("HEAD"), cancellable = true) private void drawCustomBossBar(GuiGraphics guiGraphics, int x, int y, BossEvent bossEvent, CallbackInfo ci) { NodeBossBarRenderer lichBossBarRenderer = new NodeBossBarRenderer( BMDEntities.LICH.get().getDescriptionId(), LichUtils.hpPercentRageModes, new ResourceLocation(BMDConstants.MOD_ID, "textures/gui/lich_boss_bar_dividers.png"), LichUtils.textureSize ); NodeBossBarRenderer voidBlossomBarRenderer = new NodeBossBarRenderer( BMDEntities.VOID_BLOSSOM.get().getDescriptionId(),
package com.cerbon.bosses_of_mass_destruction.mixin; @Mixin(BossHealthOverlay.class) public class BossHealthOverlayMixin { @Shadow @Final private static ResourceLocation[] BAR_BACKGROUND_SPRITES; @Shadow @Final private static ResourceLocation[] BAR_PROGRESS_SPRITES; @Inject(method = "drawBar(Lnet/minecraft/client/gui/GuiGraphics;IILnet/minecraft/world/BossEvent;)V", at = @At("HEAD"), cancellable = true) private void drawCustomBossBar(GuiGraphics guiGraphics, int x, int y, BossEvent bossEvent, CallbackInfo ci) { NodeBossBarRenderer lichBossBarRenderer = new NodeBossBarRenderer( BMDEntities.LICH.get().getDescriptionId(), LichUtils.hpPercentRageModes, new ResourceLocation(BMDConstants.MOD_ID, "textures/gui/lich_boss_bar_dividers.png"), LichUtils.textureSize ); NodeBossBarRenderer voidBlossomBarRenderer = new NodeBossBarRenderer( BMDEntities.VOID_BLOSSOM.get().getDescriptionId(),
VoidBlossomEntity.hpMilestones,
4
2023-10-25 16:28:17+00:00
12k
sinch/sinch-sdk-java
client/src/main/com/sinch/sdk/domains/sms/BatchesService.java
[ { "identifier": "ApiException", "path": "core/src/main/com/sinch/sdk/core/exceptions/ApiException.java", "snippet": "public class ApiException extends RuntimeException {\n\n private static final long serialVersionUID = -1L;\n private int code = 0;\n\n public ApiException() {}\n\n public ApiException...
import com.sinch.sdk.core.exceptions.ApiException; import com.sinch.sdk.domains.sms.models.BaseBatch; import com.sinch.sdk.domains.sms.models.Batch; import com.sinch.sdk.domains.sms.models.DryRun; import com.sinch.sdk.domains.sms.models.requests.BatchesListRequestParameters; import com.sinch.sdk.domains.sms.models.requests.UpdateBaseBatchRequest; import com.sinch.sdk.domains.sms.models.responses.BatchesListResponse; import java.util.Collection;
8,121
package com.sinch.sdk.domains.sms; /** * Batches Service * * @see <a * href="https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches">https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/</a> * @since 1.0 */ public interface BatchesService { /** * Get a batch message <br> * This operation returns a specific batch that matches the provided batch ID. * * @param batchId The batch ID you received from sending a message * @param <T> A type of Batch * @return Batch information * @see <a * href="https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/#tag/Batches/operation/GetBatchMessage">https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/#tag/Batches/operation/GetBatchMessage</a> * @since 1.0 */ <T extends Batch<?>> T get(String batchId) throws ApiException; /** * Send a message or a batch of messages <br> * Depending on the length of the body, one message might be split into multiple parts and charged * accordingly. <br> * Any groups targeted in a scheduled batch will be evaluated at the time of sending. If a group * is deleted between batch creation and scheduled date, it will be considered empty. <br> * Be sure to use the correct region in the server URL. * * @param batch The batch to be created * @param <T> A type of Batch * @return Batch information * @see <a * href="https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/#tag/Batches/operation/SendSMS">https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/#tag/Batches/operation/SendSMS</a> * @since 1.0 */ <T extends Batch<?>> T send(BaseBatch<?> batch) throws ApiException; /** * Dry run <br> * This operation will perform a dry run of a batch which calculates the bodies and number of * parts for all messages in the batch without actually sending any messages. * * @param perRecipient Whether to include per recipient details in the response * @param numberOfRecipient Max number of recipients to include per recipient details for in the * response * @param batch The batch to be send * @return Details about dryRun execution * @see <a * href="https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/#tag/Batches/operation/Dry_Run">https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/#tag/Batches/operation/Dry_Run</a> * @since 1.0 */ DryRun dryRun(boolean perRecipient, int numberOfRecipient, BaseBatch<?> batch) throws ApiException; /** * List Batches <br> * With the list operation you can list batch messages created in the last 14 days that you have * created. This operation supports pagination. * * @param parameters Query parameters filtering returned batches * @return Paginated list of Batches * @since 1.0 * @see <a * href="https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/#tag/Batches/operation/ListBatches">https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/#tag/Batches/operation/ListBatches</a> */
package com.sinch.sdk.domains.sms; /** * Batches Service * * @see <a * href="https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches">https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/</a> * @since 1.0 */ public interface BatchesService { /** * Get a batch message <br> * This operation returns a specific batch that matches the provided batch ID. * * @param batchId The batch ID you received from sending a message * @param <T> A type of Batch * @return Batch information * @see <a * href="https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/#tag/Batches/operation/GetBatchMessage">https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/#tag/Batches/operation/GetBatchMessage</a> * @since 1.0 */ <T extends Batch<?>> T get(String batchId) throws ApiException; /** * Send a message or a batch of messages <br> * Depending on the length of the body, one message might be split into multiple parts and charged * accordingly. <br> * Any groups targeted in a scheduled batch will be evaluated at the time of sending. If a group * is deleted between batch creation and scheduled date, it will be considered empty. <br> * Be sure to use the correct region in the server URL. * * @param batch The batch to be created * @param <T> A type of Batch * @return Batch information * @see <a * href="https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/#tag/Batches/operation/SendSMS">https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/#tag/Batches/operation/SendSMS</a> * @since 1.0 */ <T extends Batch<?>> T send(BaseBatch<?> batch) throws ApiException; /** * Dry run <br> * This operation will perform a dry run of a batch which calculates the bodies and number of * parts for all messages in the batch without actually sending any messages. * * @param perRecipient Whether to include per recipient details in the response * @param numberOfRecipient Max number of recipients to include per recipient details for in the * response * @param batch The batch to be send * @return Details about dryRun execution * @see <a * href="https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/#tag/Batches/operation/Dry_Run">https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/#tag/Batches/operation/Dry_Run</a> * @since 1.0 */ DryRun dryRun(boolean perRecipient, int numberOfRecipient, BaseBatch<?> batch) throws ApiException; /** * List Batches <br> * With the list operation you can list batch messages created in the last 14 days that you have * created. This operation supports pagination. * * @param parameters Query parameters filtering returned batches * @return Paginated list of Batches * @since 1.0 * @see <a * href="https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/#tag/Batches/operation/ListBatches">https://developers.sinch.com/docs/sms/api-reference/sms/tag/Batches/#tag/Batches/operation/ListBatches</a> */
BatchesListResponse list(BatchesListRequestParameters parameters) throws ApiException;
6
2023-10-31 08:32:59+00:00
12k
SpCoGov/SpCoBot
src/main/java/top/spco/service/command/commands/valorant/ValorantCommand.java
[ { "identifier": "SpCoBot", "path": "src/main/java/top/spco/SpCoBot.java", "snippet": "public class SpCoBot {\n private static SpCoBot instance;\n public static Logger logger;\n public static File dataFolder;\n public static File configFolder;\n public long botId;\n public long botOwner...
import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import top.spco.SpCoBot; import top.spco.api.*; import top.spco.api.message.Message; import top.spco.service.chat.Chat; import top.spco.service.chat.ChatBuilder; import top.spco.service.chat.ChatType; import top.spco.service.chat.Stage; import top.spco.service.command.*; import top.spco.service.command.commands.util.PermissionsValidator; import top.spco.user.BotUser; import java.io.BufferedInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.LinkedList; import java.util.List;
7,497
/* * Copyright 2023 SpCo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package top.spco.service.command.commands.valorant; /** * Valorant相关功能 * * @author SpCo * @version 1.3.0 * @since 1.3.0 */ public class ValorantCommand extends AbstractCommand { { List<CommandParam> loginParams = new ArrayList<>(); loginParams.add(new CommandParam("行为类型", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.SELECTION, "login")); loginParams.add(new CommandParam("账号", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT)); loginParams.add(new CommandParam("密码", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT)); loginUsage = new CommandUsage(getLabels()[0], "登录拳头账户", loginParams); } public static CommandUsage loginUsage; @Override public String[] getLabels() { return new String[]{"valorant"}; } @Override public String getDescriptions() { return "Valorant相关功能"; } @Override public List<CommandUsage> getUsages() { List<CommandParam> shopParams = new ArrayList<>(); shopParams.add(new CommandParam("行为类型", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.SELECTION, "shop")); return List.of(loginUsage, new CommandUsage(getLabels()[0], "获取每日商店皮肤", shopParams)); } @Override public void onCommand(Bot bot, Interactive from, User sender, BotUser user, Message message, int time, String command, String label, String[] args, CommandMeta meta, String usageName) throws CommandSyntaxException { switch (usageName) { case "登录拳头账户" -> { if (from instanceof Group) { // 检测机器人是否有权限撤回用户发送的消息
/* * Copyright 2023 SpCo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package top.spco.service.command.commands.valorant; /** * Valorant相关功能 * * @author SpCo * @version 1.3.0 * @since 1.3.0 */ public class ValorantCommand extends AbstractCommand { { List<CommandParam> loginParams = new ArrayList<>(); loginParams.add(new CommandParam("行为类型", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.SELECTION, "login")); loginParams.add(new CommandParam("账号", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT)); loginParams.add(new CommandParam("密码", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT)); loginUsage = new CommandUsage(getLabels()[0], "登录拳头账户", loginParams); } public static CommandUsage loginUsage; @Override public String[] getLabels() { return new String[]{"valorant"}; } @Override public String getDescriptions() { return "Valorant相关功能"; } @Override public List<CommandUsage> getUsages() { List<CommandParam> shopParams = new ArrayList<>(); shopParams.add(new CommandParam("行为类型", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.SELECTION, "shop")); return List.of(loginUsage, new CommandUsage(getLabels()[0], "获取每日商店皮肤", shopParams)); } @Override public void onCommand(Bot bot, Interactive from, User sender, BotUser user, Message message, int time, String command, String label, String[] args, CommandMeta meta, String usageName) throws CommandSyntaxException { switch (usageName) { case "登录拳头账户" -> { if (from instanceof Group) { // 检测机器人是否有权限撤回用户发送的消息
if (PermissionsValidator.verifyBotPermissions(from, message, (NormalMember) sender, false)) {
6
2023-10-26 10:27:47+00:00
12k
cty1928/GreenTravel
src/Android/Maps-master/app/src/main/java/org/zarroboogs/maps/ui/maps/MapsFragment.java
[ { "identifier": "DrawerStateListener", "path": "src/Android/Maps-master/app/src/main/java/org/zarroboogs/maps/DrawerStateListener.java", "snippet": "public interface DrawerStateListener {\n public void onDrawerSlide(View drawerView, float slideOffset);\n\n public void onDrawerOpened(View drawerVie...
import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.net.Uri; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnKeyListener; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import androidx.fragment.app.Fragment; import com.amap.api.maps.AMap; import com.amap.api.maps.MapView; import com.amap.api.maps.overlay.PoiOverlay; import com.amap.api.navi.AMapNavi; import com.amap.api.navi.model.NaviLatLng; import com.amap.api.services.core.AMapException; import com.amap.api.services.core.PoiItem; import com.amap.api.services.help.Inputtips; import com.amap.api.services.help.Tip; import org.zarroboogs.maps.DrawerStateListener; import org.zarroboogs.maps.MapsApplication; import org.zarroboogs.maps.beans.PoiSearchTip; import org.zarroboogs.maps.ui.anim.AnimEndListener; import org.zarroboogs.maps.ui.anim.ViewAnimUtils; import org.zarroboogs.maps.ui.poi.PoiSearchAdapter; import org.zarroboogs.maps.R; import org.zarroboogs.maps.ui.navi.NaviRouteActivity; import org.zarroboogs.maps.presenters.iviews.ISearchMapsView; import org.zarroboogs.maps.ui.MapsModule; import org.zarroboogs.maps.presenters.SearchMapsPresenter; import org.zarroboogs.maps.utils.SettingUtils; import org.zarroboogs.maps.utils.ToastUtil; import java.util.ArrayList; import java.util.List;
10,240
} catch (AMapException e) { e.printStackTrace(); } } @Override public void afterTextChanged(Editable editable) { } }); mListView = (ListView) view.findViewById(R.id.search_result_list_view); mListView.setAdapter(mPoiSearchAdapter); mListView.requestFocus(); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { hideKeyboard(mSearchEditText); // stop follow mode mMapsModule.disableAutoLocation(); PoiSearchAdapter adapter = (PoiSearchAdapter) parent.getAdapter(); PoiSearchTip tip = (PoiSearchTip) adapter.getItem(position); mSearchEditText.setText(tip.getName()); mSearchEditText.setSelection(mSearchEditText.getText().toString().length()); Log.d("Search_OnItemClick ", "" + tip.toString()); mSearchMapsPresenter.searchPoi(getActivity(), tip.getName(), tip.getAdcode()); } }); mSearchFloatWindow = (RelativeLayout) view.findViewById(R.id.search_float_rl); mSearchPoiTitle = (TextView) view.findViewById(R.id.search_result_title); mSearchPoiSummary = (TextView) view.findViewById(R.id.search_poi_summary); mLineBtn = (ImageButton) view.findViewById(R.id.maps_drive_line_btn); mSearchPoiTel = (TextView) view.findViewById(R.id.search_poi_tel); } public AMap getGaoDeMap() { return aMap; } public ImageButton getMyLocationBtn() { return mMyLocation; } public float getDevicesDirection() { return mDevicesDirection; } /** * 初始化 */ private void init() { if (aMap == null) { aMap = mapView.getMap(); } } @Override public void onResume() { super.onResume(); mapView.onResume(); Sensor mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); Sensor mPSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mSensorManager.registerListener(mEventListener, mSensor, SensorManager.SENSOR_DELAY_UI); mSensorManager.registerListener(mEventListener,mPSensor, SensorManager.SENSOR_DELAY_UI); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mapView.onSaveInstanceState(outState); } @Override public void onDestroy() { super.onDestroy(); mMapsModule.onDestroy(); mapView.onDestroy(); } @Override public void onPause() { super.onPause(); mapView.onPause(); mSensorManager.unregisterListener(mEventListener); } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } public void onLeftDrawerViewClick(int id){ if (id == R.id.left_drawer_satellite){
package org.zarroboogs.maps.ui.maps; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link MapsFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link MapsFragment#newInstance} factory method to * create an instance of this fragment. */ public class MapsFragment extends Fragment implements View.OnClickListener, DrawerStateListener, ISearchMapsView, OnKeyListener { private static final boolean DEBUG = false; // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private boolean mLandscape = false; private float mOri = 0; private AMap aMap; private MapView mapView; private MapsModule mMapsModule; private SensorManager mSensorManager; private MySensorEventListener mEventListener = new MySensorEventListener(); private float mDevicesDirection = 0f; private ImageButton mCompass; private ImageButton mMyLocation; private EditText mSearchEditText; private SearchMapsPresenter mSearchMapsPresenter; private OnFragmentInteractionListener mListener; private ListView mListView; private PoiSearchAdapter mPoiSearchAdapter; private SearchViewHelper mSearchViewHelper; // float window private RelativeLayout mSearchFloatWindow; private TextView mSearchPoiTitle; private TextView mSearchPoiSummary; private TextView mSearchPoiTel; private ImageButton mLineBtn; // progress dialog private ProgressDialog mSearchProgressDialog; private PoiItem mPoiItem; /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment MapsFragment. */ // TODO: Rename and change types and number of parameters public static MapsFragment newInstance(String param1, String param2) { MapsFragment fragment = new MapsFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } public MapsFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } mLandscape = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; mSensorManager = (SensorManager) getActivity().getApplicationContext().getSystemService(Context.SENSOR_SERVICE); mSearchMapsPresenter = new SearchMapsPresenter(this); mPoiSearchAdapter = new PoiSearchAdapter(getActivity().getApplicationContext()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_maps, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mCompass = (ImageButton) view.findViewById(R.id.ori_compass); mMyLocation = (ImageButton) view.findViewById(R.id.my_location_btn); mapView = (MapView) view.findViewById(R.id.map); mapView.onCreate(savedInstanceState);// 此方法必须重写 init(); mMapsModule = new MapsModule(this, aMap); mMapsModule.init(); aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_ROTATE); ImageButton mDrawerSwitch = (ImageButton) view.findViewById(R.id.left_drawer_switch); mDrawerSwitch.setOnClickListener(this); ImageButton mSearchBtn = (ImageButton) view.findViewById(R.id.cancel_search); mSearchBtn.setOnClickListener(this); mSearchEditText = (EditText) view.findViewById(R.id.poi_search_in_maps); mSearchEditText.setOnClickListener(this); mSearchViewHelper = new SearchViewHelper(view); mSearchEditText.setOnKeyListener(this); mSearchEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { String newText = charSequence.toString().trim(); Inputtips inputTips = new Inputtips(getActivity().getApplicationContext(), new Inputtips.InputtipsListener() { @Override public void onGetInputtips(List<Tip> tipList, int rCode) { if (rCode == 0 && tipList != null) {// 正确返回 List<PoiSearchTip> tips = new ArrayList<>(); MapsApplication.getDaoSession().getPoiSearchTipDao().deleteAll(); for (Tip tip : tipList) { PoiSearchTip mtip = new PoiSearchTip(tip.getName(), tip.getDistrict(), tip.getAdcode()); MapsApplication.getDaoSession().getPoiSearchTipDao().insert(mtip); tips.add(mtip); } List<String> listString = new ArrayList<>(); for (int i = 0; i < tipList.size(); i++) { listString.add(tipList.get(i).getName()); } mPoiSearchAdapter.addResultTips(tips); if (mListView.getVisibility() == View.GONE){ mListView.setVisibility(View.VISIBLE); } } } }); try { inputTips.requestInputtips(newText, "");// 第一个参数表示提示关键字,第二个参数默认代表全国,也可以为城市区号 } catch (AMapException e) { e.printStackTrace(); } } @Override public void afterTextChanged(Editable editable) { } }); mListView = (ListView) view.findViewById(R.id.search_result_list_view); mListView.setAdapter(mPoiSearchAdapter); mListView.requestFocus(); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { hideKeyboard(mSearchEditText); // stop follow mode mMapsModule.disableAutoLocation(); PoiSearchAdapter adapter = (PoiSearchAdapter) parent.getAdapter(); PoiSearchTip tip = (PoiSearchTip) adapter.getItem(position); mSearchEditText.setText(tip.getName()); mSearchEditText.setSelection(mSearchEditText.getText().toString().length()); Log.d("Search_OnItemClick ", "" + tip.toString()); mSearchMapsPresenter.searchPoi(getActivity(), tip.getName(), tip.getAdcode()); } }); mSearchFloatWindow = (RelativeLayout) view.findViewById(R.id.search_float_rl); mSearchPoiTitle = (TextView) view.findViewById(R.id.search_result_title); mSearchPoiSummary = (TextView) view.findViewById(R.id.search_poi_summary); mLineBtn = (ImageButton) view.findViewById(R.id.maps_drive_line_btn); mSearchPoiTel = (TextView) view.findViewById(R.id.search_poi_tel); } public AMap getGaoDeMap() { return aMap; } public ImageButton getMyLocationBtn() { return mMyLocation; } public float getDevicesDirection() { return mDevicesDirection; } /** * 初始化 */ private void init() { if (aMap == null) { aMap = mapView.getMap(); } } @Override public void onResume() { super.onResume(); mapView.onResume(); Sensor mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); Sensor mPSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mSensorManager.registerListener(mEventListener, mSensor, SensorManager.SENSOR_DELAY_UI); mSensorManager.registerListener(mEventListener,mPSensor, SensorManager.SENSOR_DELAY_UI); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mapView.onSaveInstanceState(outState); } @Override public void onDestroy() { super.onDestroy(); mMapsModule.onDestroy(); mapView.onDestroy(); } @Override public void onPause() { super.onPause(); mapView.onPause(); mSensorManager.unregisterListener(mEventListener); } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } public void onLeftDrawerViewClick(int id){ if (id == R.id.left_drawer_satellite){
int currentStyle = SettingUtils.readCurrentMapsStyle();
10
2023-10-31 01:21:54+00:00
12k
zxzf1234/jimmer-ruoyivuepro
backend/yudao-module-member/yudao-module-member-biz/src/main/java/cn/iocoder/yudao/module/member/service/auth/MemberAuthServiceImpl.java
[ { "identifier": "CommonStatusEnum", "path": "backend/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/enums/CommonStatusEnum.java", "snippet": "@Getter\n@AllArgsConstructor\npublic enum CommonStatusEnum implements IntArrayValuable {\n\n ENABLE(0, \"开启\"),\n DISABLE(1, \...
import cn.binarywang.wx.miniapp.api.WxMaService; import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo; import cn.hutool.core.lang.Assert; import cn.hutool.core.util.ObjectUtil; import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.enums.UserTypeEnum; import cn.iocoder.yudao.framework.common.util.monitor.TracerUtils; import cn.iocoder.yudao.framework.common.util.servlet.ServletUtils; import cn.iocoder.yudao.module.member.controller.app.auth.vo.*; import cn.iocoder.yudao.module.member.convert.auth.AuthConvert; import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO; import cn.iocoder.yudao.module.member.dal.mysql.user.MemberUserMapper; import cn.iocoder.yudao.module.member.service.user.MemberUserService; import cn.iocoder.yudao.service.api.infra.logger.LoginLogApi; import cn.iocoder.yudao.service.api.infra.logger.dto.LoginLogCreateReqDTO; import cn.iocoder.yudao.service.api.infra.oauth2.OAuth2TokenApi; import cn.iocoder.yudao.service.api.infra.oauth2.dto.OAuth2AccessTokenCreateReqDTO; import cn.iocoder.yudao.service.api.infra.oauth2.dto.OAuth2AccessTokenRespDTO; import cn.iocoder.yudao.service.api.system.sms.SmsCodeApi; import cn.iocoder.yudao.service.api.system.social.SocialUserApi; import cn.iocoder.yudao.service.api.system.social.dto.SocialUserBindReqDTO; import cn.iocoder.yudao.service.enums.infra.logger.LoginLogTypeEnum; import cn.iocoder.yudao.service.enums.infra.logger.LoginResultEnum; import cn.iocoder.yudao.service.enums.infra.oauth2.OAuth2ClientConstants; import cn.iocoder.yudao.service.enums.system.sms.SmsSceneEnum; import cn.iocoder.yudao.service.enums.system.social.SocialTypeEnum; import com.google.common.annotations.VisibleForTesting; import lombok.extern.slf4j.Slf4j; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.Objects; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; import static cn.iocoder.yudao.framework.common.util.servlet.ServletUtils.getClientIP; import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.*;
7,953
package cn.iocoder.yudao.module.member.service.auth; /** * 会员的认证 Service 接口 * * @author 芋道源码 */ @Service @Slf4j public class MemberAuthServiceImpl implements MemberAuthService { @Resource private MemberUserService userService; @Resource private SmsCodeApi smsCodeApi; @Resource private LoginLogApi loginLogApi; @Resource private SocialUserApi socialUserApi; @Resource private OAuth2TokenApi oauth2TokenApi; @Resource private WxMaService wxMaService; @Resource private PasswordEncoder passwordEncoder; @Resource private MemberUserMapper userMapper; @Override public AppAuthLoginRespVO login(AppAuthLoginReqVO reqVO) { // 使用手机 + 密码,进行登录。 MemberUserDO user = login0(reqVO.getMobile(), reqVO.getPassword()); // 如果 socialType 非空,说明需要绑定社交用户 if (reqVO.getSocialType() != null) { socialUserApi.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType().getValue(), reqVO.getSocialType(), reqVO.getSocialCode(), reqVO.getSocialState())); } // 创建 Token 令牌,记录登录日志 return createTokenAfterLoginSuccess(user, reqVO.getMobile(), LoginLogTypeEnum.LOGIN_MOBILE); } @Override @Transactional public AppAuthLoginRespVO smsLogin(AppAuthSmsLoginReqVO reqVO) { // 校验验证码 String userIp = getClientIP(); smsCodeApi.useSmsCode(AuthConvert.INSTANCE.convert(reqVO, SmsSceneEnum.MEMBER_LOGIN.getScene(), userIp)); // 获得获得注册用户 MemberUserDO user = userService.createUserIfAbsent(reqVO.getMobile(), userIp); Assert.notNull(user, "获取用户失败,结果为空"); // 如果 socialType 非空,说明需要绑定社交用户 if (reqVO.getSocialType() != null) { socialUserApi.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType().getValue(), reqVO.getSocialType(), reqVO.getSocialCode(), reqVO.getSocialState())); } // 创建 Token 令牌,记录登录日志 return createTokenAfterLoginSuccess(user, reqVO.getMobile(), LoginLogTypeEnum.LOGIN_SMS); } @Override public AppAuthLoginRespVO socialLogin(AppAuthSocialLoginReqVO reqVO) { // 使用 code 授权码,进行登录。然后,获得到绑定的用户编号 Long userId = socialUserApi.getBindUserId(UserTypeEnum.MEMBER.getValue(), reqVO.getType(), reqVO.getCode(), reqVO.getState()); if (userId == null) { throw exception(AUTH_THIRD_LOGIN_NOT_BIND); } // 自动登录 MemberUserDO user = userService.getUser(userId); if (user == null) { throw exception(USER_NOT_EXISTS); } // 创建 Token 令牌,记录登录日志 return createTokenAfterLoginSuccess(user, user.getMobile(), LoginLogTypeEnum.LOGIN_SOCIAL); } @Override public AppAuthLoginRespVO weixinMiniAppLogin(AppAuthWeixinMiniAppLoginReqVO reqVO) { // 获得对应的手机号信息 WxMaPhoneNumberInfo phoneNumberInfo; try { phoneNumberInfo = wxMaService.getUserService().getNewPhoneNoInfo(reqVO.getPhoneCode()); } catch (Exception exception) { throw exception(AUTH_WEIXIN_MINI_APP_PHONE_CODE_ERROR); } // 获得获得注册用户 MemberUserDO user = userService.createUserIfAbsent(phoneNumberInfo.getPurePhoneNumber(), getClientIP()); Assert.notNull(user, "获取用户失败,结果为空"); // 绑定社交用户 socialUserApi.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType().getValue(), SocialTypeEnum.WECHAT_MINI_APP.getType(), reqVO.getLoginCode(), "")); // 创建 Token 令牌,记录登录日志 return createTokenAfterLoginSuccess(user, user.getMobile(), LoginLogTypeEnum.LOGIN_SOCIAL); } private AppAuthLoginRespVO createTokenAfterLoginSuccess(MemberUserDO user, String mobile, LoginLogTypeEnum logType) { // 插入登陆日志 createLoginLog(user.getId(), mobile, logType, LoginResultEnum.SUCCESS); // 创建 Token 令牌 OAuth2AccessTokenRespDTO accessTokenRespDTO = oauth2TokenApi.createAccessToken(new OAuth2AccessTokenCreateReqDTO() .setUserId(user.getId()).setUserType(getUserType().getValue())
package cn.iocoder.yudao.module.member.service.auth; /** * 会员的认证 Service 接口 * * @author 芋道源码 */ @Service @Slf4j public class MemberAuthServiceImpl implements MemberAuthService { @Resource private MemberUserService userService; @Resource private SmsCodeApi smsCodeApi; @Resource private LoginLogApi loginLogApi; @Resource private SocialUserApi socialUserApi; @Resource private OAuth2TokenApi oauth2TokenApi; @Resource private WxMaService wxMaService; @Resource private PasswordEncoder passwordEncoder; @Resource private MemberUserMapper userMapper; @Override public AppAuthLoginRespVO login(AppAuthLoginReqVO reqVO) { // 使用手机 + 密码,进行登录。 MemberUserDO user = login0(reqVO.getMobile(), reqVO.getPassword()); // 如果 socialType 非空,说明需要绑定社交用户 if (reqVO.getSocialType() != null) { socialUserApi.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType().getValue(), reqVO.getSocialType(), reqVO.getSocialCode(), reqVO.getSocialState())); } // 创建 Token 令牌,记录登录日志 return createTokenAfterLoginSuccess(user, reqVO.getMobile(), LoginLogTypeEnum.LOGIN_MOBILE); } @Override @Transactional public AppAuthLoginRespVO smsLogin(AppAuthSmsLoginReqVO reqVO) { // 校验验证码 String userIp = getClientIP(); smsCodeApi.useSmsCode(AuthConvert.INSTANCE.convert(reqVO, SmsSceneEnum.MEMBER_LOGIN.getScene(), userIp)); // 获得获得注册用户 MemberUserDO user = userService.createUserIfAbsent(reqVO.getMobile(), userIp); Assert.notNull(user, "获取用户失败,结果为空"); // 如果 socialType 非空,说明需要绑定社交用户 if (reqVO.getSocialType() != null) { socialUserApi.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType().getValue(), reqVO.getSocialType(), reqVO.getSocialCode(), reqVO.getSocialState())); } // 创建 Token 令牌,记录登录日志 return createTokenAfterLoginSuccess(user, reqVO.getMobile(), LoginLogTypeEnum.LOGIN_SMS); } @Override public AppAuthLoginRespVO socialLogin(AppAuthSocialLoginReqVO reqVO) { // 使用 code 授权码,进行登录。然后,获得到绑定的用户编号 Long userId = socialUserApi.getBindUserId(UserTypeEnum.MEMBER.getValue(), reqVO.getType(), reqVO.getCode(), reqVO.getState()); if (userId == null) { throw exception(AUTH_THIRD_LOGIN_NOT_BIND); } // 自动登录 MemberUserDO user = userService.getUser(userId); if (user == null) { throw exception(USER_NOT_EXISTS); } // 创建 Token 令牌,记录登录日志 return createTokenAfterLoginSuccess(user, user.getMobile(), LoginLogTypeEnum.LOGIN_SOCIAL); } @Override public AppAuthLoginRespVO weixinMiniAppLogin(AppAuthWeixinMiniAppLoginReqVO reqVO) { // 获得对应的手机号信息 WxMaPhoneNumberInfo phoneNumberInfo; try { phoneNumberInfo = wxMaService.getUserService().getNewPhoneNoInfo(reqVO.getPhoneCode()); } catch (Exception exception) { throw exception(AUTH_WEIXIN_MINI_APP_PHONE_CODE_ERROR); } // 获得获得注册用户 MemberUserDO user = userService.createUserIfAbsent(phoneNumberInfo.getPurePhoneNumber(), getClientIP()); Assert.notNull(user, "获取用户失败,结果为空"); // 绑定社交用户 socialUserApi.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType().getValue(), SocialTypeEnum.WECHAT_MINI_APP.getType(), reqVO.getLoginCode(), "")); // 创建 Token 令牌,记录登录日志 return createTokenAfterLoginSuccess(user, user.getMobile(), LoginLogTypeEnum.LOGIN_SOCIAL); } private AppAuthLoginRespVO createTokenAfterLoginSuccess(MemberUserDO user, String mobile, LoginLogTypeEnum logType) { // 插入登陆日志 createLoginLog(user.getId(), mobile, logType, LoginResultEnum.SUCCESS); // 创建 Token 令牌 OAuth2AccessTokenRespDTO accessTokenRespDTO = oauth2TokenApi.createAccessToken(new OAuth2AccessTokenCreateReqDTO() .setUserId(user.getId()).setUserType(getUserType().getValue())
.setClientId(OAuth2ClientConstants.CLIENT_ID_DEFAULT));
18
2023-10-27 06:35:24+00:00
12k
SUFIAG/Hotel-Reservation-System-Java-And-PHP
src/app/src/main/java/com/sameetasadullah/i180479_i180531/presentationLayer/Main_Screen.java
[ { "identifier": "writerAndReader", "path": "src/app/src/main/java/com/sameetasadullah/i180479_i180531/dataLayer/writerAndReader.java", "snippet": "public class writerAndReader {\n Context context;\n String directoryUrl = \"http://192.168.18.81/PHP_Files/\";\n\n public writerAndReader(Context co...
import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.RelativeLayout; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.sameetasadullah.i180479_i180531.R; import com.sameetasadullah.i180479_i180531.dataLayer.writerAndReader; import com.sameetasadullah.i180479_i180531.logicLayer.Customer; import com.sameetasadullah.i180479_i180531.logicLayer.Hotel; import com.sameetasadullah.i180479_i180531.logicLayer.Room; import com.sameetasadullah.i180479_i180531.logicLayer.Vendor; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.HashMap; import java.util.Map; import java.util.Vector;
9,155
package com.sameetasadullah.i180479_i180531.presentationLayer; public class Main_Screen extends AppCompatActivity { RelativeLayout customer; RelativeLayout vendor; String Page; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_screen); customer = findViewById(R.id.rl_customer_button); vendor = findViewById(R.id.rl_vendor_button); customer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Page= "Customer"; Intent intent=new Intent(Main_Screen.this,Login_Screen.class); intent.putExtra("Page",Page); startActivity(intent); } }); vendor.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) {
package com.sameetasadullah.i180479_i180531.presentationLayer; public class Main_Screen extends AppCompatActivity { RelativeLayout customer; RelativeLayout vendor; String Page; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_screen); customer = findViewById(R.id.rl_customer_button); vendor = findViewById(R.id.rl_vendor_button); customer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Page= "Customer"; Intent intent=new Intent(Main_Screen.this,Login_Screen.class); intent.putExtra("Page",Page); startActivity(intent); } }); vendor.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) {
Page= "Vendor";
4
2023-10-25 20:58:45+00:00
12k
MachineMC/Cogwheel
cogwheel-core/src/main/java/org/machinemc/cogwheel/config/ConfigNode.java
[ { "identifier": "KeyFormatter", "path": "cogwheel-core/src/main/java/org/machinemc/cogwheel/keyformatter/KeyFormatter.java", "snippet": "public interface KeyFormatter {\n\n Pattern CAMEL_CASE_PATTERN = Pattern.compile(\"([a-z])([A-Z])\");\n\n String format(String key);\n\n}" }, { "identifi...
import org.machinemc.cogwheel.keyformatter.KeyFormatter; import org.machinemc.cogwheel.serialization.Serializer; import org.machinemc.cogwheel.serialization.SerializerContext; import org.machinemc.cogwheel.serialization.Serializers; import org.jetbrains.annotations.Nullable; import org.machinemc.cogwheel.annotations.*; import org.machinemc.cogwheel.util.JavaUtils; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.AnnotatedType; import java.util.Optional; import java.util.StringJoiner; import java.util.function.Function;
7,278
package org.machinemc.cogwheel.config; public sealed abstract class ConfigNode<A extends AnnotatedElement> permits FieldNode, RecordComponentNode { protected final A element; private final String formattedName; private final String @Nullable [] comments; private final @Nullable String inlineComment; private final boolean optional, hidden; public ConfigNode(A element, Function<ConfigNode<A>, SerializerContext> contextFunction) { this.element = element; SerializerContext context = contextFunction.apply(this); String name = getAnnotation(Key.class).map(Key::value).orElse(getName()); KeyFormatter formatter = getAnnotation(FormatKeyWith.class) .map(FormatKeyWith::value)
package org.machinemc.cogwheel.config; public sealed abstract class ConfigNode<A extends AnnotatedElement> permits FieldNode, RecordComponentNode { protected final A element; private final String formattedName; private final String @Nullable [] comments; private final @Nullable String inlineComment; private final boolean optional, hidden; public ConfigNode(A element, Function<ConfigNode<A>, SerializerContext> contextFunction) { this.element = element; SerializerContext context = contextFunction.apply(this); String name = getAnnotation(Key.class).map(Key::value).orElse(getName()); KeyFormatter formatter = getAnnotation(FormatKeyWith.class) .map(FormatKeyWith::value)
.map(JavaUtils::newInstance)
3
2023-10-25 11:31:02+00:00
12k
F4pl0/iex-cloud-java
src/main/java/io/github/f4pl0/IEXCloudClient.java
[ { "identifier": "CompanyData", "path": "src/main/java/io/github/f4pl0/companydata/CompanyData.java", "snippet": "public class CompanyData {\n private final IEXHttpClient httpClient = IEXHttpClient.getInstance();\n private final ObjectMapper mapper = new ObjectMapper();\n\n /**\n * Company I...
import io.github.f4pl0.companydata.CompanyData; import io.github.f4pl0.config.ConfigInjector; import io.github.f4pl0.config.IEXCloudConfig; import io.github.f4pl0.equitiesmarketdata.EquitiesMarketData; import io.github.f4pl0.historicaldata.HistoricalData; import io.github.f4pl0.reference.Reference;
7,973
package io.github.f4pl0; /** * The IEXCloudClient is the main entry point for the IEX Cloud API. * You will need to set the publishable token before building the client. */ public class IEXCloudClient { public final EquitiesMarketData equitiesMarketData;
package io.github.f4pl0; /** * The IEXCloudClient is the main entry point for the IEX Cloud API. * You will need to set the publishable token before building the client. */ public class IEXCloudClient { public final EquitiesMarketData equitiesMarketData;
private final Reference reference;
5
2023-10-27 17:56:14+00:00
12k
frc7787/FTC-Centerstage
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/RoadRunner/util/LogFiles.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 android.annotation.SuppressLint; import android.content.Context; import com.acmerobotics.roadrunner.geometry.Pose2d; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.qualcomm.hardware.rev.RevHubOrientationOnRobot; import com.qualcomm.robotcore.eventloop.opmode.OpMode; import com.qualcomm.robotcore.eventloop.opmode.OpModeManagerImpl; import com.qualcomm.robotcore.eventloop.opmode.OpModeManagerNotifier; import com.qualcomm.robotcore.util.RobotLog; import com.qualcomm.robotcore.util.WebHandlerManager; import org.firstinspires.ftc.ftccommon.external.WebHandlerRegistrar; import org.firstinspires.ftc.robotcore.internal.system.AppUtil; import org.firstinspires.ftc.teamcode.RoadRunner.drive.DriveConstants; import org.firstinspires.ftc.teamcode.RoadRunner.drive.SampleMecanumDrive; import org.firstinspires.ftc.teamcode.RoadRunner.drive.SampleTankDrive; import org.firstinspires.ftc.teamcode.RoadRunner.drive.StandardTrackingWheelLocalizer; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Objects; import fi.iki.elonen.NanoHTTPD;
7,284
package org.firstinspires.ftc.teamcode.RoadRunner.util; public final class LogFiles { private static final File ROOT = new File(AppUtil.ROOT_FOLDER + "/RoadRunner/logs/"); public static LogFile log = new LogFile("uninitialized"); public static class LogFile { public String version = "quickstart1 v2"; public String opModeName; public long msInit = System.currentTimeMillis(); public long nsInit = System.nanoTime(); public long nsStart, nsStop; public double ticksPerRev = DriveConstants.TICKS_PER_REV; public double maxRpm = DriveConstants.MAX_RPM; public boolean runUsingEncoder = DriveConstants.RUN_USING_ENCODER; public double motorP = DriveConstants.MOTOR_VELO_PID.p; public double motorI = DriveConstants.MOTOR_VELO_PID.i; public double motorD = DriveConstants.MOTOR_VELO_PID.d; public double motorF = DriveConstants.MOTOR_VELO_PID.f; public double wheelRadius = DriveConstants.WHEEL_RADIUS; public double gearRatio = DriveConstants.GEAR_RATIO; public double trackWidth = DriveConstants.TRACK_WIDTH; public double kV = DriveConstants.kV; public double kA = DriveConstants.kA; public double kStatic = DriveConstants.kStatic; public double maxVel = DriveConstants.MAX_VEL; public double maxAccel = DriveConstants.MAX_ACCEL; public double maxAngVel = DriveConstants.MAX_ANG_VEL; public double maxAngAccel = DriveConstants.MAX_ANG_ACCEL;
package org.firstinspires.ftc.teamcode.RoadRunner.util; public final class LogFiles { private static final File ROOT = new File(AppUtil.ROOT_FOLDER + "/RoadRunner/logs/"); public static LogFile log = new LogFile("uninitialized"); public static class LogFile { public String version = "quickstart1 v2"; public String opModeName; public long msInit = System.currentTimeMillis(); public long nsInit = System.nanoTime(); public long nsStart, nsStop; public double ticksPerRev = DriveConstants.TICKS_PER_REV; public double maxRpm = DriveConstants.MAX_RPM; public boolean runUsingEncoder = DriveConstants.RUN_USING_ENCODER; public double motorP = DriveConstants.MOTOR_VELO_PID.p; public double motorI = DriveConstants.MOTOR_VELO_PID.i; public double motorD = DriveConstants.MOTOR_VELO_PID.d; public double motorF = DriveConstants.MOTOR_VELO_PID.f; public double wheelRadius = DriveConstants.WHEEL_RADIUS; public double gearRatio = DriveConstants.GEAR_RATIO; public double trackWidth = DriveConstants.TRACK_WIDTH; public double kV = DriveConstants.kV; public double kA = DriveConstants.kA; public double kStatic = DriveConstants.kStatic; public double maxVel = DriveConstants.MAX_VEL; public double maxAccel = DriveConstants.MAX_ACCEL; public double maxAngVel = DriveConstants.MAX_ANG_VEL; public double maxAngAccel = DriveConstants.MAX_ANG_ACCEL;
public double mecTransP = SampleMecanumDrive.TRANSLATIONAL_PID_FB.kP;
1
2023-10-31 16:06:46+00:00
12k
slatepowered/slate
slate-master/src/main/java/slatepowered/slate/master/Master.java
[ { "identifier": "IntegratedCluster", "path": "slate-master/src/main/java/slatepowered/slate/cluster/IntegratedCluster.java", "snippet": "public class IntegratedCluster extends Cluster<IntegratedClusterInstance> {\r\n\r\n /**\r\n * The master instance.\r\n */\r\n protected final Master mast...
import slatepowered.slate.cluster.IntegratedCluster; import slatepowered.slate.cluster.IntegratedClusterInstance; import slatepowered.slate.communication.CommunicationKey; import slatepowered.slate.communication.CommunicationStrategy; import slatepowered.slate.model.MasterManagedNode; import slatepowered.slate.model.MasterNetwork; import slatepowered.slate.network.NetworkInfoService; import slatepowered.slate.packages.PackageManager; import slatepowered.slate.packages.service.ProvidedPackageService; import slatepowered.slate.plugin.SlatePlugin; import slatepowered.slate.plugin.SlatePluginManager; import slatepowered.veru.data.Pair; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collection; import java.util.stream.Collectors;
8,763
package slatepowered.slate.master; /** * The master bootstrap/network. */ public class Master extends MasterNetwork { /** * The working directory. */ protected final Path directory; /** * The local package manager for locally managing packages. */ protected final PackageManager localPackageManager; /** * The {@link slatepowered.slate.cluster.Cluster} impl of the integrated cluster. */
package slatepowered.slate.master; /** * The master bootstrap/network. */ public class Master extends MasterNetwork { /** * The working directory. */ protected final Path directory; /** * The local package manager for locally managing packages. */ protected final PackageManager localPackageManager; /** * The {@link slatepowered.slate.cluster.Cluster} impl of the integrated cluster. */
protected final IntegratedCluster integratedClusterImpl;
0
2023-10-30 08:58:02+00:00
12k
Melledy/LunarCore
src/main/java/emu/lunarcore/data/excel/ShopGoodsExcel.java
[ { "identifier": "GameData", "path": "src/main/java/emu/lunarcore/data/GameData.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class GameData {\n // Excels\n @Getter private static Int2ObjectMap<AvatarExcel> avatarExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2O...
import java.util.ArrayList; import java.util.List; import emu.lunarcore.data.GameData; import emu.lunarcore.data.GameResource; import emu.lunarcore.data.ResourceType; import emu.lunarcore.data.ResourceType.LoadPriority; import emu.lunarcore.data.common.ItemParam; import emu.lunarcore.proto.GoodsOuterClass.Goods; import lombok.AccessLevel; import lombok.Getter;
7,888
package emu.lunarcore.data.excel; @Getter @ResourceType(name = {"ShopGoodsConfig.json"}, loadPriority = LoadPriority.LOW) public class ShopGoodsExcel extends GameResource { private int GoodsID; private int ItemID; private int ItemCount; private int ShopID; @Getter(AccessLevel.NONE) private int[] CurrencyList; @Getter(AccessLevel.NONE) private int[] CurrencyCostList;
package emu.lunarcore.data.excel; @Getter @ResourceType(name = {"ShopGoodsConfig.json"}, loadPriority = LoadPriority.LOW) public class ShopGoodsExcel extends GameResource { private int GoodsID; private int ItemID; private int ItemCount; private int ShopID; @Getter(AccessLevel.NONE) private int[] CurrencyList; @Getter(AccessLevel.NONE) private int[] CurrencyCostList;
private transient List<ItemParam> costList;
2
2023-10-10 12:57:35+00:00
12k
jar-analyzer/jar-analyzer
src/main/java/me/n1ar4/jar/analyzer/gui/MainForm.java
[ { "identifier": "ConfigEngine", "path": "src/main/java/me/n1ar4/jar/analyzer/config/ConfigEngine.java", "snippet": "public class ConfigEngine {\n private static final Logger logger = LogManager.getLogger();\n public static final String CONFIG_FILE_PATH = \".jar-analyzer\";\n\n public static boo...
import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; import com.intellij.uiDesigner.core.Spacer; import me.n1ar4.jar.analyzer.config.ConfigEngine; import me.n1ar4.jar.analyzer.config.ConfigFile; import me.n1ar4.jar.analyzer.engine.CoreEngine; import me.n1ar4.jar.analyzer.engine.DecompileEngine; import me.n1ar4.jar.analyzer.entity.ClassResult; import me.n1ar4.jar.analyzer.entity.MethodResult; import me.n1ar4.jar.analyzer.gui.action.*; import me.n1ar4.jar.analyzer.gui.adapter.*; import me.n1ar4.jar.analyzer.gui.font.FontHelper; import me.n1ar4.jar.analyzer.gui.render.AllMethodsRender; import me.n1ar4.jar.analyzer.gui.render.ClassRender; import me.n1ar4.jar.analyzer.gui.render.MethodCallRender; import me.n1ar4.jar.analyzer.gui.render.SpringMethodRender; import me.n1ar4.jar.analyzer.gui.state.State; import me.n1ar4.jar.analyzer.gui.tree.FileTree; import me.n1ar4.jar.analyzer.gui.update.UpdateChecker; import me.n1ar4.jar.analyzer.gui.util.*; import me.n1ar4.jar.analyzer.gui.vul.*; import me.n1ar4.jar.analyzer.starter.Const; import me.n1ar4.jar.analyzer.utils.DirUtil; import me.n1ar4.log.LogManager; import me.n1ar4.log.Logger; import javax.swing.*; import javax.swing.border.TitledBorder; import javax.swing.plaf.FontUIResource; import javax.swing.text.StyleContext; import java.awt.*; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Locale;
9,191
package me.n1ar4.jar.analyzer.gui; public class MainForm { private static final Logger logger = LogManager.getLogger(); private JPanel masterPanel; private JTabbedPane tabbedPanel; private JPanel codePanel; private JPanel corePanel; private JPanel startPanel; private JButton choseBtn; private JTextField fileText; private JButton startEngineButton; private JCheckBox resolveJarsInJarCheckBox; private JPanel chosePanel; private JRadioButton fernRadio; private JPanel decompilerPanel; private JProgressBar buildBar; private JPanel infoPanel; private JLabel totalClassLabel; private JLabel totalClassVal; private JLabel totalMethodLabel; private JLabel totalMethodVal; private JLabel totalJarLabel; private JLabel totalJarVal; private JLabel databaseSizeLabel; private JLabel databaseSizeVal; private JRadioButton methodDefinitionRadioButton; private JRadioButton methodCallRadioButton; private JButton startSearchButton; private JRadioButton stringContainsRadioButton; private JRadioButton binarySearchRadioButton; private JTextField searchClassText; private JPanel leftPanel; private JScrollPane treeScrollPanel;
package me.n1ar4.jar.analyzer.gui; public class MainForm { private static final Logger logger = LogManager.getLogger(); private JPanel masterPanel; private JTabbedPane tabbedPanel; private JPanel codePanel; private JPanel corePanel; private JPanel startPanel; private JButton choseBtn; private JTextField fileText; private JButton startEngineButton; private JCheckBox resolveJarsInJarCheckBox; private JPanel chosePanel; private JRadioButton fernRadio; private JPanel decompilerPanel; private JProgressBar buildBar; private JPanel infoPanel; private JLabel totalClassLabel; private JLabel totalClassVal; private JLabel totalMethodLabel; private JLabel totalMethodVal; private JLabel totalJarLabel; private JLabel totalJarVal; private JLabel databaseSizeLabel; private JLabel databaseSizeVal; private JRadioButton methodDefinitionRadioButton; private JRadioButton methodCallRadioButton; private JButton startSearchButton; private JRadioButton stringContainsRadioButton; private JRadioButton binarySearchRadioButton; private JTextField searchClassText; private JPanel leftPanel; private JScrollPane treeScrollPanel;
private FileTree fileTree;
12
2023-10-07 15:42:35+00:00
12k
EasyProgramming/easy-mqtt
server/src/main/java/com/ep/mqtt/server/deal/DefaultDeal.java
[ { "identifier": "MqttServerProperties", "path": "server/src/main/java/com/ep/mqtt/server/config/MqttServerProperties.java", "snippet": "@Data\n@Configuration\n@ConfigurationProperties(prefix = \"mqtt.server\")\npublic class MqttServerProperties {\n\n /**\n * 是否开启Epoll模式, linux下建议开启\n */\n ...
import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.data.redis.core.*; import org.springframework.data.redis.core.script.DefaultRedisScript; import org.springframework.data.redis.core.script.RedisScript; import org.springframework.stereotype.Component; import com.ep.mqtt.server.config.MqttServerProperties; import com.ep.mqtt.server.listener.msg.CleanExistSessionMsg; import com.ep.mqtt.server.listener.msg.ManageRetainMessageMsg; import com.ep.mqtt.server.listener.msg.ManageTopicFilterMsg; import com.ep.mqtt.server.metadata.ChannelKey; import com.ep.mqtt.server.metadata.LuaScript; import com.ep.mqtt.server.metadata.StoreKey; import com.ep.mqtt.server.metadata.YesOrNo; import com.ep.mqtt.server.session.Session; import com.ep.mqtt.server.session.SessionManager; import com.ep.mqtt.server.store.RetainMessageStore; import com.ep.mqtt.server.store.SubscribeStore; import com.ep.mqtt.server.util.*; import com.ep.mqtt.server.vo.ClientInfoVo; import com.ep.mqtt.server.vo.MessageVo; import com.ep.mqtt.server.vo.TopicVo; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.mqtt.MqttConnectMessage; import io.netty.handler.codec.mqtt.MqttQoS; import lombok.Data; import lombok.extern.slf4j.Slf4j;
7,529
stringRedisTemplate.execute((RedisCallback<Void>)connection -> { for (TopicVo topicVo : topicVoList) { String clientTopicFilterKey = StoreKey.CLIENT_TOPIC_FILTER_KEY.formatKey(clientId); connection.hSet(clientTopicFilterKey.getBytes(), topicVo.getTopicFilter().getBytes(), String.valueOf(topicVo.getQos()).getBytes()); connection.hSet((StoreKey.TOPIC_FILTER_KEY.formatKey(topicVo.getTopicFilter())).getBytes(), clientId.getBytes(), String.valueOf(topicVo.getQos()).getBytes()); } return null; }); stringRedisTemplate.convertAndSend(ChannelKey.MANAGE_TOPIC_FILTER.getKey(), JsonUtil.obj2String(manageTopicFilterMsg)); return subscribeResultList; } public void unSubscribe(String clientId, List<TopicVo> topicVoList) { for (TopicVo topicVo : topicVoList) { TopicUtil.validateTopicFilter(topicVo.getTopicFilter()); } // 发送取消订阅广播 ManageTopicFilterMsg manageTopicFilterMsg = new ManageTopicFilterMsg(); manageTopicFilterMsg.setClientId(clientId); manageTopicFilterMsg.setManageType(ManageTopicFilterMsg.ManageType.UN_SUBSCRIBE.getKey()); manageTopicFilterMsg.setTopicVoList(topicVoList); stringRedisTemplate.convertAndSend(ChannelKey.MANAGE_TOPIC_FILTER.getKey(), JsonUtil.obj2String(manageTopicFilterMsg)); stringRedisTemplate.execute((RedisCallback<Void>)connection -> { for (TopicVo topicVo : topicVoList) { connection.hDel((StoreKey.CLIENT_TOPIC_FILTER_KEY.formatKey(clientId)).getBytes(), topicVo.getTopicFilter().getBytes()); connection.hDel((StoreKey.TOPIC_FILTER_KEY.formatKey(topicVo.getTopicFilter())).getBytes(), clientId.getBytes()); } return null; }); } public void dealMessage(MessageVo messageVo) { Integer isRetain = messageVo.getIsRetained(); MqttQoS fromMqttQoS = MqttQoS.valueOf(messageVo.getFromQos()); String payload = messageVo.getPayload(); if (YesOrNo.YES.getValue().equals(isRetain)) { // qos == 0 || payload 为零字节,清除该主题下的保留消息 if (MqttQoS.AT_MOST_ONCE == fromMqttQoS || StringUtils.isBlank(payload)) { delTopicRetainMessage(messageVo.getTopic()); } // 存储保留消息 else { saveTopicRetainMessage(messageVo); } } if (MqttQoS.EXACTLY_ONCE.equals(fromMqttQoS)) { saveRecMessage(messageVo); return; } sendMessage(messageVo); } public void sendMessage(MessageVo messageVo) { long startTime = System.currentTimeMillis(); // 先根据topic做匹配 Map<String, Integer> matchMap = subscribeStore.searchSubscribe(messageVo.getTopic()); List<MessageVo> batchSendMessageVoList = new ArrayList<>(); ArrayList<Map.Entry<String, Integer>> matchClientList = Lists.newArrayList(matchMap.entrySet()); for (int i = 0; i < matchClientList.size(); i++) { Map.Entry<String, Integer> entry = matchClientList.get(i); Integer toQos = Math.min(messageVo.getFromQos(), entry.getValue()); messageVo.setToQos(toQos); messageVo.setToClientId(entry.getKey()); Integer messageId = genMessageId(messageVo.getToClientId()); if (messageId != null) { messageVo.setToMessageId(String.valueOf(messageId)); switch (MqttQoS.valueOf(messageVo.getToQos())) { case AT_MOST_ONCE: batchSendMessageVoList.add(messageVo); break; case AT_LEAST_ONCE: case EXACTLY_ONCE: String messageKey = StoreKey.MESSAGE_KEY.formatKey(messageVo.getToClientId()); RedisScript<Long> redisScript = new DefaultRedisScript<>(LuaScript.SAVE_MESSAGE, Long.class); Long flag = stringRedisTemplate.execute(redisScript, Lists.newArrayList(messageKey), messageVo.getToMessageId(), JsonUtil.obj2String(messageVo)); if (flag != null) { batchSendMessageVoList.add(messageVo); } break; default: break; } } if (batchSendMessageVoList.size() >= 100 || i == matchMap.entrySet().size() - 1) { stringRedisTemplate.convertAndSend(ChannelKey.SEND_MESSAGE.getKey(), JsonUtil.obj2String(batchSendMessageVoList)); batchSendMessageVoList.clear(); } } log.info("complete send message, cost {}ms", System.currentTimeMillis() - startTime); } private Integer genMessageId(String clientId) { String genMessageIdKey = StoreKey.GEN_MESSAGE_ID_KEY.formatKey(clientId); RedisScript<Long> redisScript = new DefaultRedisScript<>(LuaScript.GEN_MESSAGE_ID, Long.class); Long messageId = stringRedisTemplate.execute(redisScript, Lists.newArrayList(genMessageIdKey)); if (messageId != null) { return Math.toIntExact(messageId % 65535 + 1); } return null; } public void delMessage(String clientId, Integer messageId) { stringRedisTemplate.opsForHash().delete(StoreKey.MESSAGE_KEY.formatKey(clientId), String.valueOf(messageId)); } public void saveTopicRetainMessage(MessageVo messageVo) { messageVo.setToQos(messageVo.getFromQos()); // 远程存储保留消息 stringRedisTemplate.opsForHash().put(StoreKey.RETAIN_MESSAGE_KEY.formatKey(), messageVo.getTopic(), JsonUtil.obj2String(messageVo)); // 发送redis消息,存储本地保留消息
package com.ep.mqtt.server.deal; /** * 请求broker * * @author zbz * @date 2023/7/15 17:10 */ @Slf4j @Component public class DefaultDeal { @Autowired private StringRedisTemplate stringRedisTemplate; @Autowired private SubscribeStore subscribeStore; @Autowired private MqttServerProperties mqttServerProperties; @Autowired private RetainMessageStore retainMessageStore; public boolean authentication(MqttConnectMessage mqttConnectMessage) { if (StringUtils.isBlank(mqttServerProperties.getAuthenticationUrl())) { return true; } String userName = mqttConnectMessage.payload().userName(); byte[] password = mqttConnectMessage.payload().passwordInBytes(); String returnStr = HttpUtil.getInstance().postJson(mqttServerProperties.getAuthenticationUrl(), JsonUtil.obj2String(new AuthenticationRequest(userName, new String(password))), null); return Boolean.parseBoolean(returnStr); } public void cleanExistSession(String clientId, String sessionId) { Session session = SessionManager.get(clientId); if (session != null && !session.getSessionId().equals(sessionId)) { session.getChannelHandlerContext().disconnect(); } CleanExistSessionMsg cleanExistSessionMsg = new CleanExistSessionMsg(); cleanExistSessionMsg.setClientId(clientId); cleanExistSessionMsg.setSessionId(sessionId); stringRedisTemplate.convertAndSend(ChannelKey.CLEAR_EXIST_SESSION.getKey(), JsonUtil.obj2String(cleanExistSessionMsg)); } public ClientInfoVo getClientInfo(String clientId) { HashOperations<String, String, String> hashOperations = stringRedisTemplate.opsForHash(); String clientJsonStr = hashOperations.get(StoreKey.CLIENT_INFO_KEY.formatKey(), clientId); return JsonUtil.string2Obj(clientJsonStr, ClientInfoVo.class); } public void clearClientData(String clientId) { cleanLocalData(clientId); cleanRemoteData(clientId); } private void cleanLocalData(String clientId) { // 发送取消订阅广播 ManageTopicFilterMsg manageTopicFilterMsg = new ManageTopicFilterMsg(); manageTopicFilterMsg.setClientId(clientId); manageTopicFilterMsg.setManageType(ManageTopicFilterMsg.ManageType.UN_SUBSCRIBE.getKey()); stringRedisTemplate.convertAndSend(ChannelKey.MANAGE_TOPIC_FILTER.getKey(), JsonUtil.obj2String(manageTopicFilterMsg)); } private void cleanRemoteData(String clientId) { HashOperations<String, String, Integer> stringObjectObjectHashOperations = stringRedisTemplate.opsForHash(); Map<String, Integer> clientTopicFilterMap = stringObjectObjectHashOperations.entries(StoreKey.CLIENT_TOPIC_FILTER_KEY.formatKey(clientId)); String messageKey = StoreKey.MESSAGE_KEY.formatKey(clientId); String recMessageKey = StoreKey.REC_MESSAGE_KEY.formatKey(clientId); String relMessageKey = StoreKey.REL_MESSAGE_KEY.formatKey(clientId); String clientTopicFilterKey = StoreKey.CLIENT_TOPIC_FILTER_KEY.formatKey(clientId); String genMessageIdKey = StoreKey.GEN_MESSAGE_ID_KEY.formatKey(clientId); stringRedisTemplate.execute(new SessionCallback<Void>() { @SuppressWarnings({"unchecked", "NullableProblems"}) @Override public Void execute(RedisOperations operations) throws DataAccessException { // 移除订阅关系 for (Map.Entry<String, Integer> clientTopicFilter : clientTopicFilterMap.entrySet()) { operations.opsForHash().delete((StoreKey.TOPIC_FILTER_KEY.formatKey(clientTopicFilter.getKey())), clientId); } // 移除客户端的相关数据 operations.delete( Sets.newHashSet(clientTopicFilterKey, messageKey, recMessageKey, relMessageKey, genMessageIdKey)); // 移除会话信息 operations.opsForHash().delete(StoreKey.CLIENT_INFO_KEY.formatKey(), clientId); return null; } }); } public void saveClientInfo(ClientInfoVo clientInfoVo) { stringRedisTemplate.opsForHash().put(StoreKey.CLIENT_INFO_KEY.formatKey(), clientInfoVo.getClientId(), JsonUtil.obj2String(clientInfoVo)); } public List<Integer> subscribe(String clientId, List<TopicVo> topicVoList) { List<Integer> subscribeResultList = Lists.newArrayList(); ManageTopicFilterMsg manageTopicFilterMsg = new ManageTopicFilterMsg(); manageTopicFilterMsg.setClientId(clientId); manageTopicFilterMsg.setTopicVoList(topicVoList); manageTopicFilterMsg.setManageType(ManageTopicFilterMsg.ManageType.SUBSCRIBE.getKey()); stringRedisTemplate.execute((RedisCallback<Void>)connection -> { for (TopicVo topicVo : topicVoList) { String clientTopicFilterKey = StoreKey.CLIENT_TOPIC_FILTER_KEY.formatKey(clientId); connection.hSet(clientTopicFilterKey.getBytes(), topicVo.getTopicFilter().getBytes(), String.valueOf(topicVo.getQos()).getBytes()); connection.hSet((StoreKey.TOPIC_FILTER_KEY.formatKey(topicVo.getTopicFilter())).getBytes(), clientId.getBytes(), String.valueOf(topicVo.getQos()).getBytes()); } return null; }); stringRedisTemplate.convertAndSend(ChannelKey.MANAGE_TOPIC_FILTER.getKey(), JsonUtil.obj2String(manageTopicFilterMsg)); return subscribeResultList; } public void unSubscribe(String clientId, List<TopicVo> topicVoList) { for (TopicVo topicVo : topicVoList) { TopicUtil.validateTopicFilter(topicVo.getTopicFilter()); } // 发送取消订阅广播 ManageTopicFilterMsg manageTopicFilterMsg = new ManageTopicFilterMsg(); manageTopicFilterMsg.setClientId(clientId); manageTopicFilterMsg.setManageType(ManageTopicFilterMsg.ManageType.UN_SUBSCRIBE.getKey()); manageTopicFilterMsg.setTopicVoList(topicVoList); stringRedisTemplate.convertAndSend(ChannelKey.MANAGE_TOPIC_FILTER.getKey(), JsonUtil.obj2String(manageTopicFilterMsg)); stringRedisTemplate.execute((RedisCallback<Void>)connection -> { for (TopicVo topicVo : topicVoList) { connection.hDel((StoreKey.CLIENT_TOPIC_FILTER_KEY.formatKey(clientId)).getBytes(), topicVo.getTopicFilter().getBytes()); connection.hDel((StoreKey.TOPIC_FILTER_KEY.formatKey(topicVo.getTopicFilter())).getBytes(), clientId.getBytes()); } return null; }); } public void dealMessage(MessageVo messageVo) { Integer isRetain = messageVo.getIsRetained(); MqttQoS fromMqttQoS = MqttQoS.valueOf(messageVo.getFromQos()); String payload = messageVo.getPayload(); if (YesOrNo.YES.getValue().equals(isRetain)) { // qos == 0 || payload 为零字节,清除该主题下的保留消息 if (MqttQoS.AT_MOST_ONCE == fromMqttQoS || StringUtils.isBlank(payload)) { delTopicRetainMessage(messageVo.getTopic()); } // 存储保留消息 else { saveTopicRetainMessage(messageVo); } } if (MqttQoS.EXACTLY_ONCE.equals(fromMqttQoS)) { saveRecMessage(messageVo); return; } sendMessage(messageVo); } public void sendMessage(MessageVo messageVo) { long startTime = System.currentTimeMillis(); // 先根据topic做匹配 Map<String, Integer> matchMap = subscribeStore.searchSubscribe(messageVo.getTopic()); List<MessageVo> batchSendMessageVoList = new ArrayList<>(); ArrayList<Map.Entry<String, Integer>> matchClientList = Lists.newArrayList(matchMap.entrySet()); for (int i = 0; i < matchClientList.size(); i++) { Map.Entry<String, Integer> entry = matchClientList.get(i); Integer toQos = Math.min(messageVo.getFromQos(), entry.getValue()); messageVo.setToQos(toQos); messageVo.setToClientId(entry.getKey()); Integer messageId = genMessageId(messageVo.getToClientId()); if (messageId != null) { messageVo.setToMessageId(String.valueOf(messageId)); switch (MqttQoS.valueOf(messageVo.getToQos())) { case AT_MOST_ONCE: batchSendMessageVoList.add(messageVo); break; case AT_LEAST_ONCE: case EXACTLY_ONCE: String messageKey = StoreKey.MESSAGE_KEY.formatKey(messageVo.getToClientId()); RedisScript<Long> redisScript = new DefaultRedisScript<>(LuaScript.SAVE_MESSAGE, Long.class); Long flag = stringRedisTemplate.execute(redisScript, Lists.newArrayList(messageKey), messageVo.getToMessageId(), JsonUtil.obj2String(messageVo)); if (flag != null) { batchSendMessageVoList.add(messageVo); } break; default: break; } } if (batchSendMessageVoList.size() >= 100 || i == matchMap.entrySet().size() - 1) { stringRedisTemplate.convertAndSend(ChannelKey.SEND_MESSAGE.getKey(), JsonUtil.obj2String(batchSendMessageVoList)); batchSendMessageVoList.clear(); } } log.info("complete send message, cost {}ms", System.currentTimeMillis() - startTime); } private Integer genMessageId(String clientId) { String genMessageIdKey = StoreKey.GEN_MESSAGE_ID_KEY.formatKey(clientId); RedisScript<Long> redisScript = new DefaultRedisScript<>(LuaScript.GEN_MESSAGE_ID, Long.class); Long messageId = stringRedisTemplate.execute(redisScript, Lists.newArrayList(genMessageIdKey)); if (messageId != null) { return Math.toIntExact(messageId % 65535 + 1); } return null; } public void delMessage(String clientId, Integer messageId) { stringRedisTemplate.opsForHash().delete(StoreKey.MESSAGE_KEY.formatKey(clientId), String.valueOf(messageId)); } public void saveTopicRetainMessage(MessageVo messageVo) { messageVo.setToQos(messageVo.getFromQos()); // 远程存储保留消息 stringRedisTemplate.opsForHash().put(StoreKey.RETAIN_MESSAGE_KEY.formatKey(), messageVo.getTopic(), JsonUtil.obj2String(messageVo)); // 发送redis消息,存储本地保留消息
ManageRetainMessageMsg manageRetainMessageMsg = new ManageRetainMessageMsg();
2
2023-10-08 06:41:33+00:00
12k
egorolegovichyakovlev/DroidRec
app/src/main/java/com/yakovlevegor/DroidRec/shake/OnShakeEventHelper.java
[ { "identifier": "OnShakePreferenceChangeEvent", "path": "app/src/main/java/com/yakovlevegor/DroidRec/shake/event/OnShakePreferenceChangeEvent.java", "snippet": "public class OnShakePreferenceChangeEvent {\n private String state;\n public OnShakePreferenceChangeEvent(String state) {\n this.s...
import static java.lang.Math.sqrt; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.yakovlevegor.DroidRec.shake.event.OnShakePreferenceChangeEvent; import com.yakovlevegor.DroidRec.ScreenRecorder; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe;
10,612
package com.yakovlevegor.DroidRec.shake; public class OnShakeEventHelper { private SensorEventListener currentListener; private boolean hasListenerChanged; private Context context; private ScreenRecorder.RecordingBinder recordingBinder; private float acceleration = 10f; private float currentAcceleration = SensorManager.GRAVITY_EARTH; private float lastAcceleration = SensorManager.GRAVITY_EARTH; private SensorManager sensorManager; private Toast toast; private SensorEventListener emptyListener = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent sensorEvent) { } @Override public void onAccuracyChanged(Sensor sensor, int i) { } }; public OnShakeEventHelper(ScreenRecorder.RecordingBinder recordingBinder, AppCompatActivity activity) { this.recordingBinder = recordingBinder; String initialValue = activity.getSharedPreferences(ScreenRecorder.prefsident, 0).getString("onshake", "Do nothing"); currentListener = giveMeSensorListenerFor(initialValue); sensorManager = (SensorManager) activity.getSystemService(Context.SENSOR_SERVICE); context = activity.getApplicationContext(); EventBus.getDefault().register(this); } public void registerListener() { sensorManager.registerListener( currentListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL ); hasListenerChanged = false; } public void unregisterListener() { sensorManager.unregisterListener(currentListener); } @Subscribe
package com.yakovlevegor.DroidRec.shake; public class OnShakeEventHelper { private SensorEventListener currentListener; private boolean hasListenerChanged; private Context context; private ScreenRecorder.RecordingBinder recordingBinder; private float acceleration = 10f; private float currentAcceleration = SensorManager.GRAVITY_EARTH; private float lastAcceleration = SensorManager.GRAVITY_EARTH; private SensorManager sensorManager; private Toast toast; private SensorEventListener emptyListener = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent sensorEvent) { } @Override public void onAccuracyChanged(Sensor sensor, int i) { } }; public OnShakeEventHelper(ScreenRecorder.RecordingBinder recordingBinder, AppCompatActivity activity) { this.recordingBinder = recordingBinder; String initialValue = activity.getSharedPreferences(ScreenRecorder.prefsident, 0).getString("onshake", "Do nothing"); currentListener = giveMeSensorListenerFor(initialValue); sensorManager = (SensorManager) activity.getSystemService(Context.SENSOR_SERVICE); context = activity.getApplicationContext(); EventBus.getDefault().register(this); } public void registerListener() { sensorManager.registerListener( currentListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL ); hasListenerChanged = false; } public void unregisterListener() { sensorManager.unregisterListener(currentListener); } @Subscribe
public void onShakePreferenceChanged(OnShakePreferenceChangeEvent event) {
0
2023-10-09 00:04:13+00:00
12k
lunasaw/gb28181-proxy
gb28181-client/src/main/java/io/github/lunasaw/gbproxy/client/transmit/request/subscribe/catalog/SubscribeCatalogQueryMessageHandler.java
[ { "identifier": "SipUserGenerateClient", "path": "gb28181-client/src/main/java/io/github/lunasaw/gbproxy/client/user/SipUserGenerateClient.java", "snippet": "public interface SipUserGenerateClient extends SipUserGenerate {\n\n}" }, { "identifier": "Device", "path": "sip-common/src/main/java/...
import javax.sip.RequestEvent; import javax.sip.header.ContentTypeHeader; import javax.sip.header.EventHeader; import javax.sip.header.ExpiresHeader; import javax.sip.message.Response; import io.github.lunasaw.gbproxy.client.user.SipUserGenerateClient; import io.github.lunasaw.sip.common.entity.Device; import io.github.lunasaw.gb28181.common.entity.response.DeviceSubscribe; import io.github.lunasaw.sip.common.enums.ContentTypeEnum; import io.github.lunasaw.sip.common.transmit.ResponseCmd; import io.github.lunasaw.sip.common.utils.SipRequestUtils; import org.springframework.stereotype.Component; import gov.nist.javax.sip.message.SIPRequest; import io.github.lunasaw.gbproxy.client.transmit.request.subscribe.SubscribeClientHandlerAbstract; import io.github.lunasaw.gbproxy.client.transmit.request.subscribe.SubscribeProcessorClient; import io.github.lunasaw.sip.common.entity.DeviceSession; import io.github.lunasaw.gb28181.common.entity.query.DeviceQuery; import io.github.lunasaw.gb28181.common.entity.enums.CmdTypeEnum; import io.github.lunasaw.sip.common.subscribe.SubscribeInfo; import io.github.lunasaw.sip.common.transmit.event.message.MessageHandler; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j;
8,270
package io.github.lunasaw.gbproxy.client.transmit.request.subscribe.catalog; /** * 处理设备通道订阅消息 回复OK * * @author luna * @date 2023/10/19 */ @Component @Slf4j @Getter @Setter public class SubscribeCatalogQueryMessageHandler extends SubscribeClientHandlerAbstract { public static final String CMD_TYPE = CmdTypeEnum.CATALOG.getType(); public SubscribeCatalogQueryMessageHandler(SubscribeProcessorClient subscribeProcessorClient, SipUserGenerateClient sipUserGenerate) { super(subscribeProcessorClient, sipUserGenerate); } @Override public String getRootType() { return MessageHandler.QUERY; } @Override public void handForEvt(RequestEvent event) { DeviceSession deviceSession = getDeviceSession(event); EventHeader header = (EventHeader) event.getRequest().getHeader(EventHeader.NAME); if (header == null){ log.info("handForEvt::event = {}", event); return; } // 订阅消息过来 String sipId = deviceSession.getSipId(); String userId = deviceSession.getUserId(); SIPRequest request = (SIPRequest)event.getRequest(); SubscribeInfo subscribeInfo = new SubscribeInfo(request, sipId);
package io.github.lunasaw.gbproxy.client.transmit.request.subscribe.catalog; /** * 处理设备通道订阅消息 回复OK * * @author luna * @date 2023/10/19 */ @Component @Slf4j @Getter @Setter public class SubscribeCatalogQueryMessageHandler extends SubscribeClientHandlerAbstract { public static final String CMD_TYPE = CmdTypeEnum.CATALOG.getType(); public SubscribeCatalogQueryMessageHandler(SubscribeProcessorClient subscribeProcessorClient, SipUserGenerateClient sipUserGenerate) { super(subscribeProcessorClient, sipUserGenerate); } @Override public String getRootType() { return MessageHandler.QUERY; } @Override public void handForEvt(RequestEvent event) { DeviceSession deviceSession = getDeviceSession(event); EventHeader header = (EventHeader) event.getRequest().getHeader(EventHeader.NAME); if (header == null){ log.info("handForEvt::event = {}", event); return; } // 订阅消息过来 String sipId = deviceSession.getSipId(); String userId = deviceSession.getUserId(); SIPRequest request = (SIPRequest)event.getRequest(); SubscribeInfo subscribeInfo = new SubscribeInfo(request, sipId);
Device fromDevice = sipUserGenerate.getFromDevice();
1
2023-10-11 06:56:28+00:00
12k
1415181920/yamis-admin
cocoyam-modules/cocoyam-module-sys/src/main/java/io/xiaoyu/sys/modular/admin/controller/admin/view/AdminUsersViewController.java
[ { "identifier": "AdminBaseViewController", "path": "cocoyam-common/src/main/java/io/xiaoyu/common/basic/controller/AdminBaseViewController.java", "snippet": "public class AdminBaseViewController implements AdminBaseViewInterface{\n\n protected HashMap<Object, Object> createButton(AdminBaseViewControl...
import io.xiaoyu.common.basic.controller.AdminBaseViewController; import io.xiaoyu.common.resp.CommonAdminResp; import io.xiaoyu.common.yaims.AmisFactory; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap;
7,216
package io.xiaoyu.sys.modular.admin.controller.admin.view; /** * 视图层控制器 */ @RestController @RequestMapping("/admin-api/sys/admin/admin-users")
package io.xiaoyu.sys.modular.admin.controller.admin.view; /** * 视图层控制器 */ @RestController @RequestMapping("/admin-api/sys/admin/admin-users")
public class AdminUsersViewController extends AdminBaseViewController{
0
2023-10-09 06:04:30+00:00
12k
Swofty-Developments/Continued-Slime-World-Manager
swoftyworldmanager-plugin/src/main/java/net/swofty/swm/plugin/commands/subtypes/subCommand_unloadworld.java
[ { "identifier": "SlimeWorld", "path": "swoftyworldmanager-api/src/main/java/net/swofty/swm/api/world/SlimeWorld.java", "snippet": "public interface SlimeWorld {\n\n /**\n * Returns the name of the world.\n *\n * @return The name of the world.\n */\n String getName();\n\n /**\n ...
import lombok.SneakyThrows; import net.swofty.swm.api.world.SlimeWorld; import net.swofty.swm.api.world.data.WorldData; import net.swofty.swm.api.world.data.WorldsConfig; import net.swofty.swm.plugin.SWMPlugin; import net.swofty.swm.plugin.commands.CommandCooldown; import net.swofty.swm.plugin.commands.CommandParameters; import net.swofty.swm.plugin.commands.CommandSource; import net.swofty.swm.plugin.commands.SWMCommand; import net.swofty.swm.plugin.config.ConfigManager; import net.swofty.swm.plugin.log.Logging; import org.bukkit.*; import org.bukkit.command.CommandSender; import java.util.Collections; import java.util.LinkedList; import java.util.List;
7,757
package net.swofty.swm.plugin.commands.subtypes; @CommandParameters(description = "Unload a world", inGameOnly = false, permission = "swm.unloadworld") public class subCommand_unloadworld extends SWMCommand implements CommandCooldown { @SneakyThrows @Override public void run(CommandSource sender, String[] args) { if (args.length == 0) { sender.send(Logging.COMMAND_PREFIX + ChatColor.RED + "Usage: /swm unloadworld <world>"); return; } WorldsConfig config = SWMPlugin.getInstance().getConfigManager().getWorldConfig(); WorldData worldData = config.getWorlds().get(args[0]); if (worldData == null || Bukkit.getWorld(args[0]) == null) { sender.send(Logging.COMMAND_PREFIX + ChatColor.RED + "Unknown slime world " + args[0] + "! Are you sure you've typed it correctly?"); return; }
package net.swofty.swm.plugin.commands.subtypes; @CommandParameters(description = "Unload a world", inGameOnly = false, permission = "swm.unloadworld") public class subCommand_unloadworld extends SWMCommand implements CommandCooldown { @SneakyThrows @Override public void run(CommandSource sender, String[] args) { if (args.length == 0) { sender.send(Logging.COMMAND_PREFIX + ChatColor.RED + "Usage: /swm unloadworld <world>"); return; } WorldsConfig config = SWMPlugin.getInstance().getConfigManager().getWorldConfig(); WorldData worldData = config.getWorlds().get(args[0]); if (worldData == null || Bukkit.getWorld(args[0]) == null) { sender.send(Logging.COMMAND_PREFIX + ChatColor.RED + "Unknown slime world " + args[0] + "! Are you sure you've typed it correctly?"); return; }
SlimeWorld world = SWMPlugin.getInstance().getNms().getSlimeWorld(Bukkit.getWorld(args[0]));
0
2023-10-08 10:54:28+00:00
12k
calicosun258/5c-client-N
src/main/java/fifthcolumn/n/mixins/DisconnectedScreenMixin.java
[ { "identifier": "NMod", "path": "src/main/java/fifthcolumn/n/NMod.java", "snippet": "public class NMod implements ModInitializer {\n\n // You can set this to false to enable cope service. DO THIS AT YOUR OWN RISK due to security reasons as the mod would connect to servers on the internet.\n public s...
import fifthcolumn.n.NMod; import fifthcolumn.n.client.ui.copenheimer.servers.CopeMultiplayerScreen; import fifthcolumn.n.copenheimer.CopeService; import fifthcolumn.n.modules.BanEvasion; import meteordevelopment.meteorclient.systems.modules.Modules; import net.minecraft.client.gui.screen.ConnectScreen; import net.minecraft.client.gui.screen.DisconnectedScreen; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.screen.TitleScreen; import net.minecraft.client.gui.widget.ButtonWidget; import net.minecraft.client.gui.widget.GridWidget; import net.minecraft.client.network.ServerAddress; import net.minecraft.text.Text; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
8,794
package fifthcolumn.n.mixins; @Mixin({DisconnectedScreen.class}) public abstract class DisconnectedScreenMixin extends Screen { @Unique private ButtonWidget switchAltButton; protected DisconnectedScreenMixin(Text title) { super(title); } @Inject( method = {"init"}, at = {@At( value = "INVOKE", target = "Lnet/minecraft/client/gui/widget/GridWidget;refreshPositions()V" )}, locals = LocalCapture.CAPTURE_FAILHARD ) private void n$banEvasion(CallbackInfo ci, GridWidget.Adder adder, ButtonWidget buttonWidget) {
package fifthcolumn.n.mixins; @Mixin({DisconnectedScreen.class}) public abstract class DisconnectedScreenMixin extends Screen { @Unique private ButtonWidget switchAltButton; protected DisconnectedScreenMixin(Text title) { super(title); } @Inject( method = {"init"}, at = {@At( value = "INVOKE", target = "Lnet/minecraft/client/gui/widget/GridWidget;refreshPositions()V" )}, locals = LocalCapture.CAPTURE_FAILHARD ) private void n$banEvasion(CallbackInfo ci, GridWidget.Adder adder, ButtonWidget buttonWidget) {
if (Modules.get().isActive(BanEvasion.class) && Modules.get().get(BanEvasion.class).evadeAndReconnect.get()) {
3
2023-10-14 19:18:35+00:00
12k
ZJU-ACES-ISE/chatunitest-core
src/main/java/zju/cst/aces/api/impl/ValidatorImpl.java
[ { "identifier": "Validator", "path": "src/main/java/zju/cst/aces/api/Validator.java", "snippet": "public interface Validator {\n\n boolean syntacticValidate(String code);\n boolean semanticValidate(String code, String className, Path outputPath, PromptInfo promptInfo);\n boolean runtimeValidate...
import com.github.javaparser.ParseProblemException; import com.github.javaparser.StaticJavaParser; import lombok.Data; import org.junit.platform.launcher.listeners.TestExecutionSummary; import zju.cst.aces.api.Validator; import zju.cst.aces.api.config.Config; import zju.cst.aces.dto.PromptInfo; import zju.cst.aces.util.TestCompiler; import java.nio.file.Path; import java.util.List; import zju.cst.aces.api.Validator;
7,802
package zju.cst.aces.api.impl; @Data public class ValidatorImpl implements Validator {
package zju.cst.aces.api.impl; @Data public class ValidatorImpl implements Validator {
TestCompiler compiler;
3
2023-10-14 07:15:10+00:00
12k
jmdevall/opencodeplan
src/test/java/jmdevall/opencodeplan/application/CodePlanTest.java
[ { "identifier": "DependencyGraphConstructorJavaparser", "path": "src/main/java/jmdevall/opencodeplan/adapter/out/javaparser/DependencyGraphConstructorJavaparser.java", "snippet": "public class DependencyGraphConstructorJavaparser implements DependencyGraphConstructor{\n\n\tprivate List<VoidVisitorAdapte...
import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.List; import org.junit.jupiter.api.Test; import jmdevall.opencodeplan.adapter.out.javaparser.DependencyGraphConstructorJavaparser; import jmdevall.opencodeplan.adapter.out.javaparser.ParserJavaParser; import jmdevall.opencodeplan.adapter.out.llm.cache.LlmEngineCacheAdapter; import jmdevall.opencodeplan.adapter.out.llm.debug.LlmEngineDebugAdapter; import jmdevall.opencodeplan.adapter.out.llm.ooba.LlmEngineOoba; import jmdevall.opencodeplan.adapter.out.llm.openai.LlmEngineOpenai; import jmdevall.opencodeplan.adapter.out.oracle.OracleDefault; import jmdevall.opencodeplan.adapter.out.repository.FiltersFactory; import jmdevall.opencodeplan.adapter.out.repository.RepositoryMulpleFolders; import jmdevall.opencodeplan.application.port.out.llm.LlmEngine; import jmdevall.opencodeplan.application.port.out.oracle.Oracle; import jmdevall.opencodeplan.application.port.out.parser.DependencyGraphConstructor; import jmdevall.opencodeplan.application.port.out.parser.Parser; import jmdevall.opencodeplan.application.port.out.repository.Repository; import jmdevall.opencodeplan.application.port.out.repository.SourceFolder; import jmdevall.opencodeplan.domain.dependencygraph.LineColPos; import jmdevall.opencodeplan.domain.instruction.DeltaSeeds; import jmdevall.opencodeplan.domain.instruction.InstructuionNatural; import jmdevall.opencodeplan.domain.instruction.NodeSearchDescriptor; import jmdevall.opencodeplan.domain.instruction.Seed; import jmdevall.opencodeplan.domain.plangraph.NodeTypeTag; import jmdevall.opencodeplan.domain.promptmaker.InstructionTemplate; import jmdevall.opencodeplan.domain.promptmaker.PromptMaker; import jmdevall.opencodeplan.domain.promptmaker.PromptMakerDefault;
8,248
package jmdevall.opencodeplan.application; public class CodePlanTest { @Test public void testCodePlan() { //initialize default dependencies....
package jmdevall.opencodeplan.application; public class CodePlanTest { @Test public void testCodePlan() { //initialize default dependencies....
Parser parser=new ParserJavaParser();
12
2023-10-14 18:27:18+00:00
12k
eahau/douyin-openapi
generator/src/main/java/com/github/eahau/openapi/douyin/generator/parser/HtmlParser.java
[ { "identifier": "DocField", "path": "generator/src/main/java/com/github/eahau/openapi/douyin/generator/DocField.java", "snippet": "@Getter\n@Setter\npublic class DocField {\n\n /**\n * 字段名称.\n */\n @SerializedName(value = \"name\", alternate = {\"key\"})\n private String name = \"\";\n\...
import com.github.eahau.openapi.douyin.generator.DocField; import com.github.eahau.openapi.douyin.generator.GeneratorContent; import com.github.eahau.openapi.douyin.generator.GeneratorContent.GeneratorContentBuilder; import com.github.eahau.openapi.douyin.generator.Misc; import com.github.eahau.openapi.douyin.generator.api.DouYinOpenDocApi.DocResponse; import com.google.common.collect.ImmutableRangeMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Range; import com.google.common.collect.RangeMap; import com.google.common.collect.Streams; import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.Configuration.Defaults; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.Option; import com.jayway.jsonpath.spi.json.GsonJsonProvider; import com.jayway.jsonpath.spi.json.JsonProvider; import com.jayway.jsonpath.spi.mapper.GsonMappingProvider; import com.jayway.jsonpath.spi.mapper.MappingProvider; import com.vladsch.flexmark.ast.Heading; import com.vladsch.flexmark.ast.HtmlBlock; import com.vladsch.flexmark.ast.ListBlock; import com.vladsch.flexmark.ast.Paragraph; import com.vladsch.flexmark.ast.Text; import com.vladsch.flexmark.ext.tables.TablesExtension; import com.vladsch.flexmark.parser.Parser; import com.vladsch.flexmark.util.ast.Block; import com.vladsch.flexmark.util.ast.Node; import com.vladsch.flexmark.util.sequence.BasedSequence; import io.swagger.v3.oas.models.PathItem.HttpMethod; import io.swagger.v3.oas.models.servers.Server; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.CharUtils; import org.apache.commons.lang3.StringUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.EnumSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.StringTokenizer; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream;
8,853
} else { final URL url = urls.get(0); path = url.getPath(); if (!url.toString().startsWith(Misc.API_BASE_URL)) { builder.addServer( new Server() .url(url.getProtocol() + ":" + url.getHost()) .description( Optional.ofNullable(next.getPrevious()) .map(Node::getChildChars) .map(String::valueOf) .orElse(null) ) ); } } builder.path(path); break; } } } }); } } protected void parseHeader(Node node) { Node next = node.getNext(); if (next instanceof HtmlBlock) { Document document = Jsoup.parse(next.getChars().toString()); builder.headFields(parseHead(document)); } else if (next instanceof ListBlock) { final List<String> textList = Streams.stream(next.getChildIterator()) .map(Node::getChildChars) .map(BasedSequence::trim) .map(BasedSequence::toString) .collect(Collectors.toList()); builder.headFields(parseHead(textList)); } if (StringUtils.contains(next.getChars(), "通用参数-平台请求开发者公共参数")) { return; } if (next.getNext() instanceof Heading) { if (((Heading) next.getNext()).getText().isEmpty()) { parseBaseInfo(next.getNext()); } } } protected void parseQuery(Node node) { final Heading heading = (Heading) ((node instanceof Heading) ? node : node.getPreviousAny(Heading.class)); visit(heading, next -> { if (next instanceof HtmlBlock || next instanceof Paragraph) { Optional.of(next) .map(Node::getChars) .map(String::valueOf) .map(Jsoup::parse) .map(this::parseTableOrData) .ifPresent(builder::queryFields); } }); } protected void parseBody(Node node) { Optional.ofNullable(node.getNextAny(HtmlBlock.class)) .filter(HtmlBlock.class::isInstance) .map(HtmlBlock.class::cast) .map(this::parseTable) .ifPresent(builder::bodyFields); } private String getHeadingText(Node node) { if (node == null) { return null; } return Streams.stream(node.getChildIterator()) .filter(it -> it instanceof Text) .findFirst() .map(Node::getChars) .map(BasedSequence::toString) .orElse(null); } /** * 获取当前节点带有 字段(英文)定义的 heading/paragraph. */ private String getPreHeadingText(Node node, Predicate<String> existObjectClassName) { if (node == null) { return null; } Node child = node.getFirstChild(); while (child != null) { if (child instanceof Text) { break; } child = child.getFirstChild(); } return Optional.ofNullable(child) .map(Node::getChars) .map(it -> it.split(" ")) .flatMap(array -> Arrays.stream(array) .map(it -> it.chars() .filter(c -> ((char) c) == '_' || CharUtils.isAsciiAlpha((char) c)) .mapToObj(c -> (char) c) .map(String::valueOf) .collect(Collectors.joining())) .findFirst() .map(String::valueOf)) .filter(StringUtils::isNotBlank) .filter(existObjectClassName) .orElseGet(() -> getPreHeadingText(node.getPrevious(), existObjectClassName)); }
/* * Copyright 2023 eahau@foxmail.com * * 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.github.eahau.openapi.douyin.generator.parser; @Slf4j public class HtmlParser { static final Parser PARSER = Parser.builder() .extensions(Collections.singletonList(TablesExtension.create())) .build(); static { Configuration.setDefaults( new Defaults() { final JsonProvider jsonProvider = new GsonJsonProvider(Misc.GSON); final MappingProvider mappingProvider = new GsonMappingProvider(Misc.GSON); @Override public JsonProvider jsonProvider() { return jsonProvider; } @Override public Set<Option> options() { return EnumSet.of(Option.SUPPRESS_EXCEPTIONS); } @Override public MappingProvider mappingProvider() { return mappingProvider; } } ); } final DocResponse response; final com.vladsch.flexmark.util.ast.Document markdown; final GeneratorContentBuilder builder = GeneratorContent.builder(); final List<Consumer<Heading>> consumers; /** * 只处理匹配的 heading 的子节点. */ private void visit(Heading heading, Consumer<Node> consumer) { for (Node next = heading.getNext(); next != null; next = next.getNext()) { if (next instanceof Heading && ((Heading) next).getLevel() <= heading.getLevel()) { break; } consumer.accept(next); } } public HtmlParser(final DocResponse response) { this.response = response; this.builder.title(response.getTitle()).docPath(response.getPath()); this.markdown = PARSER.parse(response.getContent()); this.consumers = Arrays.asList( it -> { if (it.getLevel() == 2 && StringUtils.equals(getHeadingText(it), "接口说明")) { final StringBuilder desc = new StringBuilder(); visit(it, node -> desc.append(node.getChars()).append("\n")); builder.desc(desc.toString()); } }, it -> { if (StringUtils.equalsAny(getHeadingText(it), "请求地址", "基本信息")) { parseBaseInfo(it); } }, it -> { if (it.getLevel() == 2 && StringUtils.equals(getHeadingText(it), "请求头")) { parseHeader(it); } }, it -> { if (it.getLevel() == 2 && StringUtils.equals(getHeadingText(it), "请求参数")) { visit(it, next -> { if (!(next instanceof Heading)) { return; } final String headingText = getHeadingText(next); if (StringUtils.contains(headingText, "Header")) { parseHeader(next); } else if (StringUtils.contains(headingText, "Body")) { parseBody(next); } else if (StringUtils.containsAny(headingText, "Query", "URL 请求")) { parseQuery(next); } }); } }, it -> { if (it.getLevel() == 2 && StringUtils.containsAny(getHeadingText(it), "响应参数", "返回值")) { parseResponse(it); } }, it -> { if (it.getLevel() != 3) { return; } if (StringUtils.containsAny(getHeadingText(it), "响应样例", "正常")) { parseResponseExample(it); } if (StringUtils.containsAny(getHeadingText(it), "异常", "失败", "错误")) { parseErrorResponseExample(it); } } ); } static Map<String, String> tableToMap(Document document) { final Elements tr = document.select("tr"); final Elements elements = tr.isEmpty() ? document.select("td") : tr; final Map<String, String> map = Maps.newHashMap(); for (final Element e : elements) { final Elements td = e.select("td"); final List<String> textList = (td.isEmpty() ? e.select("th") : td).eachText(); if (textList.size() == 2) { map.put(textList.get(0), textList.get(1)); } } return map; } static final Pattern pattern = Pattern.compile("((https?|http):((//)|(\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)", Pattern.CASE_INSENSITIVE); /** * copy from https://stackoverflow.com/a/28269120. */ @SneakyThrows static List<URL> extractUrls(String text) { List<URL> containedUrls = new ArrayList<>(); Matcher urlMatcher = pattern.matcher(text); while (urlMatcher.find()) { final URL url = new URL(text.substring(urlMatcher.start(0), urlMatcher.end(0))); containedUrls.add(url); } return containedUrls; } protected void parseBaseInfo(Node node) { if (node.getNext() instanceof HtmlBlock) { Document document = Jsoup.parse(node.getNext().getChars().toString()); final Map<String, String> baseInfoMap = tableToMap(document); Optional.ofNullable(baseInfoMap.get("HTTP URL")) .ifPresent(httpUrl -> { final List<URL> urls = extractUrls(httpUrl); if (urls.isEmpty()) { if (httpUrl.contains("/") && httpUrl.chars().allMatch(c -> CharUtils.isAscii((char) c))) { builder.path(httpUrl); } else { builder.callback(true); log.info("需要配置回调地址,但暂不支持 callback, docUrl {}", Misc.DOC_BASE_URL + response.getPath()); // final String[] pathArray = response.getPath().split("/"); // // final int length = pathArray.length; // // final String path = "/" + String.join("/", ArrayUtils.subarray(pathArray, length - 2, length)); // // builder.path(path); } } else { final StringTokenizer tokenizer = httpUrl.contains(":") ? new StringTokenizer(httpUrl, ":") : null; for (final URL url : urls) { String desc = (tokenizer != null && tokenizer.hasMoreTokens()) ? tokenizer.nextToken() : null; if (desc != null) { desc = desc.chars() .filter(c -> !CharUtils.isAscii((char) c)) .mapToObj(c -> String.valueOf((char) c)) .collect(Collectors.joining()); } builder.path(url.getPath()); if (!Misc.API_BASE_URL.contains(url.getHost())) { builder.addServer( new Server() .url(url.getProtocol() + "://" + url.getHost()) .description(desc) ); } } } }); Optional.ofNullable(baseInfoMap.get("HTTP Method")) .map(String::toUpperCase) .map(HttpMethod::valueOf) .ifPresent(builder::method); } else { visit((Heading) node, next -> { if (next instanceof Block) { final String text = next.getChildChars().toString().trim(); final StringTokenizer stringTokenizer = new StringTokenizer(text, "[]"); while (stringTokenizer.hasMoreTokens()) { final String token = stringTokenizer.nextToken(); final Optional<HttpMethod> httpMethodOptional = Arrays.stream(HttpMethod.values()) .filter(it -> token.startsWith(it.name())) .findFirst(); if (httpMethodOptional.isPresent()) { builder.method(httpMethodOptional.get()); final String pathOrUrl = token.split(" ")[1]; final String path; final List<URL> urls = extractUrls(token); if (urls.isEmpty()) { path = pathOrUrl; } else { final URL url = urls.get(0); path = url.getPath(); if (!url.toString().startsWith(Misc.API_BASE_URL)) { builder.addServer( new Server() .url(url.getProtocol() + ":" + url.getHost()) .description( Optional.ofNullable(next.getPrevious()) .map(Node::getChildChars) .map(String::valueOf) .orElse(null) ) ); } } builder.path(path); break; } } } }); } } protected void parseHeader(Node node) { Node next = node.getNext(); if (next instanceof HtmlBlock) { Document document = Jsoup.parse(next.getChars().toString()); builder.headFields(parseHead(document)); } else if (next instanceof ListBlock) { final List<String> textList = Streams.stream(next.getChildIterator()) .map(Node::getChildChars) .map(BasedSequence::trim) .map(BasedSequence::toString) .collect(Collectors.toList()); builder.headFields(parseHead(textList)); } if (StringUtils.contains(next.getChars(), "通用参数-平台请求开发者公共参数")) { return; } if (next.getNext() instanceof Heading) { if (((Heading) next.getNext()).getText().isEmpty()) { parseBaseInfo(next.getNext()); } } } protected void parseQuery(Node node) { final Heading heading = (Heading) ((node instanceof Heading) ? node : node.getPreviousAny(Heading.class)); visit(heading, next -> { if (next instanceof HtmlBlock || next instanceof Paragraph) { Optional.of(next) .map(Node::getChars) .map(String::valueOf) .map(Jsoup::parse) .map(this::parseTableOrData) .ifPresent(builder::queryFields); } }); } protected void parseBody(Node node) { Optional.ofNullable(node.getNextAny(HtmlBlock.class)) .filter(HtmlBlock.class::isInstance) .map(HtmlBlock.class::cast) .map(this::parseTable) .ifPresent(builder::bodyFields); } private String getHeadingText(Node node) { if (node == null) { return null; } return Streams.stream(node.getChildIterator()) .filter(it -> it instanceof Text) .findFirst() .map(Node::getChars) .map(BasedSequence::toString) .orElse(null); } /** * 获取当前节点带有 字段(英文)定义的 heading/paragraph. */ private String getPreHeadingText(Node node, Predicate<String> existObjectClassName) { if (node == null) { return null; } Node child = node.getFirstChild(); while (child != null) { if (child instanceof Text) { break; } child = child.getFirstChild(); } return Optional.ofNullable(child) .map(Node::getChars) .map(it -> it.split(" ")) .flatMap(array -> Arrays.stream(array) .map(it -> it.chars() .filter(c -> ((char) c) == '_' || CharUtils.isAsciiAlpha((char) c)) .mapToObj(c -> (char) c) .map(String::valueOf) .collect(Collectors.joining())) .findFirst() .map(String::valueOf)) .filter(StringUtils::isNotBlank) .filter(existObjectClassName) .orElseGet(() -> getPreHeadingText(node.getPrevious(), existObjectClassName)); }
private List<DocField> parseTable(HtmlBlock topHtmlBlock) {
0
2023-10-07 09:09:15+00:00
12k
Aywen1/wispy
src/fr/nicolas/wispy/Panels/GamePanel.java
[ { "identifier": "Runner", "path": "src/fr/nicolas/wispy/Runner.java", "snippet": "public class Runner implements Runnable {\n\n\tprivate boolean isRunning = false;\n\tprivate GamePanel gamePanel;\n\tprivate int maxFps = 80;\n\tprivate long waitTime = 4;\n\n\tpublic Runner(GamePanel gamePanel) {\n\t\tthi...
import java.awt.Graphics; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.image.BufferedImage; import java.io.IOException; import javax.imageio.ImageIO; import fr.nicolas.wispy.Runner; import fr.nicolas.wispy.Frames.MainFrame; import fr.nicolas.wispy.Panels.Components.Game.Player; import fr.nicolas.wispy.Panels.Components.Menu.EscapeMenu; import fr.nicolas.wispy.Panels.Components.Menu.WPanel; import fr.nicolas.wispy.Panels.Fonctions.MapManager; import fr.nicolas.wispy.Panels.Fonctions.MapManager.RefreshPaintMap;
7,630
package fr.nicolas.wispy.Panels; public class GamePanel extends WPanel implements KeyListener, MouseListener, MouseMotionListener { public static final int BLOCK_SIZE = 25, INIT_PLAYER_X = 605, INIT_PLAYER_Y = 315; private int newBlockWidth = BLOCK_SIZE, newBlockHeight = BLOCK_SIZE, playerX, playerY, playerWidth, playerHeight; private Runner runner; private MapManager mapManager; private BufferedImage sky; private Player player; private Point mouseLocation; private boolean keyDPressed = false, keyQPressed = false, keySpacePressed = false, isEscapeMenuOpen = false; public GamePanel(Rectangle frameBounds, boolean isNewGame) { super(frameBounds); newBlockWidth = BLOCK_SIZE; newBlockHeight = BLOCK_SIZE; this.addKeyListener(this); this.addMouseListener(this); this.addMouseMotionListener(this); this.setFocusable(true); // Chargement des textures for (int i = 0; i < BlockID.values().length; i++) { loadBlockImage(BlockID.values()[i]); } try { sky = ImageIO.read(getClass().getResource("Components/Game/res/map/sky.png")); player = new Player(ImageIO.read(getClass().getResource("Components/Game/res/player/p_stop.png")), ImageIO.read(getClass().getResource("Components/Game/res/player/p_walk1.png")), ImageIO.read(getClass().getResource("Components/Game/res/player/p_walk2.png")), this); } catch (IOException e) { e.printStackTrace(); } // Création/Chargement nouveau monde mapManager = new MapManager(player); mapManager.loadWorld("TestWorld"); // Lancement des threads runner = new Runner(this); // Actualiser les blocs puis les textures mapManager.newLoadingMapThread(runner, this); // Charger et décharger les maps setFrameBounds(new Rectangle(MainFrame.INIT_WIDTH, MainFrame.INIT_HEIGHT)); } // Gestion blocs (textures) public enum BlockID { STONE, DIRT, GRASS, SAND; private BufferedImage img = null; public void setImg(BufferedImage img) { this.img = img; } public BufferedImage getImg() { return img; } } private void loadBlockImage(BlockID blockID) { try { blockID.setImg(ImageIO.read( getClass().getResource("Components/Game/res/blocks/" + blockID.toString().toLowerCase() + ".png"))); } catch (IOException e) { e.printStackTrace(); } } // Refresh / Paint methods public void refresh() { if (keyDPressed) { player.setWalking(true); player.setToRight(true); } if (keyQPressed) { player.setWalking(true); player.setToRight(false); } if (!keyQPressed && !keyDPressed) { player.setWalking(false); } if (keySpacePressed) { player.setJumping(true); keySpacePressed = false; } player.refresh(playerX, playerY, playerWidth, playerHeight); } public void paintComponent(Graphics g) { g.drawImage(sky, 0, 0, this.getWidth(), this.getHeight(), null); // Le paint des blocs intègre le test de collision avec le joueur mapManager.refreshPaintAllDisplayedBlocks(g, RefreshPaintMap.PAINT, this.getWidth(), this.getHeight(), newBlockWidth, newBlockHeight, 0, 0, 0, 0, this, null); player.paint(g, playerX, playerY, playerWidth, playerHeight); if (isEscapeMenuOpen) {
package fr.nicolas.wispy.Panels; public class GamePanel extends WPanel implements KeyListener, MouseListener, MouseMotionListener { public static final int BLOCK_SIZE = 25, INIT_PLAYER_X = 605, INIT_PLAYER_Y = 315; private int newBlockWidth = BLOCK_SIZE, newBlockHeight = BLOCK_SIZE, playerX, playerY, playerWidth, playerHeight; private Runner runner; private MapManager mapManager; private BufferedImage sky; private Player player; private Point mouseLocation; private boolean keyDPressed = false, keyQPressed = false, keySpacePressed = false, isEscapeMenuOpen = false; public GamePanel(Rectangle frameBounds, boolean isNewGame) { super(frameBounds); newBlockWidth = BLOCK_SIZE; newBlockHeight = BLOCK_SIZE; this.addKeyListener(this); this.addMouseListener(this); this.addMouseMotionListener(this); this.setFocusable(true); // Chargement des textures for (int i = 0; i < BlockID.values().length; i++) { loadBlockImage(BlockID.values()[i]); } try { sky = ImageIO.read(getClass().getResource("Components/Game/res/map/sky.png")); player = new Player(ImageIO.read(getClass().getResource("Components/Game/res/player/p_stop.png")), ImageIO.read(getClass().getResource("Components/Game/res/player/p_walk1.png")), ImageIO.read(getClass().getResource("Components/Game/res/player/p_walk2.png")), this); } catch (IOException e) { e.printStackTrace(); } // Création/Chargement nouveau monde mapManager = new MapManager(player); mapManager.loadWorld("TestWorld"); // Lancement des threads runner = new Runner(this); // Actualiser les blocs puis les textures mapManager.newLoadingMapThread(runner, this); // Charger et décharger les maps setFrameBounds(new Rectangle(MainFrame.INIT_WIDTH, MainFrame.INIT_HEIGHT)); } // Gestion blocs (textures) public enum BlockID { STONE, DIRT, GRASS, SAND; private BufferedImage img = null; public void setImg(BufferedImage img) { this.img = img; } public BufferedImage getImg() { return img; } } private void loadBlockImage(BlockID blockID) { try { blockID.setImg(ImageIO.read( getClass().getResource("Components/Game/res/blocks/" + blockID.toString().toLowerCase() + ".png"))); } catch (IOException e) { e.printStackTrace(); } } // Refresh / Paint methods public void refresh() { if (keyDPressed) { player.setWalking(true); player.setToRight(true); } if (keyQPressed) { player.setWalking(true); player.setToRight(false); } if (!keyQPressed && !keyDPressed) { player.setWalking(false); } if (keySpacePressed) { player.setJumping(true); keySpacePressed = false; } player.refresh(playerX, playerY, playerWidth, playerHeight); } public void paintComponent(Graphics g) { g.drawImage(sky, 0, 0, this.getWidth(), this.getHeight(), null); // Le paint des blocs intègre le test de collision avec le joueur mapManager.refreshPaintAllDisplayedBlocks(g, RefreshPaintMap.PAINT, this.getWidth(), this.getHeight(), newBlockWidth, newBlockHeight, 0, 0, 0, 0, this, null); player.paint(g, playerX, playerY, playerWidth, playerHeight); if (isEscapeMenuOpen) {
new EscapeMenu().paint(g, this.getHeight());
3
2023-10-13 13:10:56+00:00
12k
PfauMC/CyanWorld
cyanworld-cyan1dex/src/main/java/ru/cyanworld/cyan1dex/commands/CmdCyan1dex.java
[ { "identifier": "Config", "path": "cyanworld-cyan1dex/src/main/java/ru/cyanworld/cyan1dex/Config.java", "snippet": "public class Config {\n public static final boolean customtab_enable = Config.getBoolean(\"customtab.enable\");\n public static final String motd = Config.getString(\"fakebutitsrealo...
import com.google.common.collect.Maps; import org.bukkit.Sound; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import ru.cyanworld.cyan1dex.Config; import ru.cyanworld.cyan1dex.Cyan1dex; import ru.cyanworld.cyan1dex.CyanEcoManager; import ru.cyanworld.cyan1dex.Utils; import ru.cyanworld.cyan1dex.messages.Msg; import ru.cyanworld.cyan1dex.rcon.RconManager; import ru.cyanworld.cyan1dex.utils.ChatUtils; import java.io.File; import java.io.IOException; import java.net.ConnectException; import java.util.Collections; import java.util.List; import java.util.Map;
8,173
public boolean execute(CommandSender sender, String commandLabel, String[] args) { if (!sender.isOp()) { sender.sendMessage("Эта команда только для администраторов"); return true; } if (args.length == 0) { sender.sendMessage("/cyan1dex setgroup <ник> <группа>\n/cyan1dex cmdall Команда...\n/cyan1dex fakeerror\n/cyan1dex viewdistance <ник> <чанки>\n/cyan1dex eco add <ник> <количество>\n/cyan1dex forcechat <ник> Сообщение...\n/cyan1dex swear <плохое_слово>\n/cyan1dex setdata <UUID> <группа> <монетки>\n"); return true; } block11: switch (args[0]) { case "setgroup": { try { if (sender instanceof Player) { return false; } String uuid = args[1].contains("-") ? args[1] : Cyan1dex.cfguuid.getString(args[1].toLowerCase()); Cyan1dex.cfgplayers.set(uuid + ".group", args[2].toLowerCase()); if (args[2].equalsIgnoreCase("player")) { Cyan1dex.cfgplayers.set(uuid + ".group", null); } Cyan1dex.cfgplayers.save(new File(Cyan1dex.dataFolder, "players.yml")); Player player = Cyan1dex.server.getPlayer(args[1]); if (player != null) { Utils.setPlayerPrefix(player); } String displayname = args[1].contains("-") ? Cyan1dex.cfgplayers.getString(uuid + ".displayname") : args[1]; Cyan1dex.server.broadcastMessage("\n§b" + displayname + " Теперь донатер!\n§bПокупай донат на cyanworld.ru\n "); Cyan1dex.server.getOnlinePlayers().forEach(players -> { players.playSound(players.getLocation(), Sound.UI_TOAST_CHALLENGE_COMPLETE, 2.14748365E9f, 1.0f); players.sendTitle("§b" + displayname, "Купил донат!", 10, 100, 10); } ); } catch (Exception ex) { ex.printStackTrace(); } break; } case "cmdall": { try { if (!Cyan1dex.server.getMotd().contains("main")) { return false; } if (sender instanceof Player) { sender.sendMessage(Msg.permdeny); return false; } StringBuilder stringBuilder = new StringBuilder(); for (int i = 1; i < args.length; ++i) { stringBuilder.append(args[i]); stringBuilder.append(" "); } String COMMAND = stringBuilder.toString(); System.out.println("[Cyan1dex] Отправляем команду [" + COMMAND + "]..."); Cyan1dex.server.dispatchCommand(Cyan1dex.server.getConsoleSender(), COMMAND); this.rconRequest(35002, COMMAND); this.rconRequest(35003, COMMAND); } catch (Exception ex) { ex.printStackTrace(); } break; } case "viewdistance": { Player player = Cyan1dex.server.getPlayer(args[1]); int distance = Integer.parseInt(args[2]); sender.sendMessage("Установлена дальность прорисовки " + distance + " для игрока " + player.getName()); player.setViewDistance(distance); break; } case "forcechat": { String msg = Utils.readLongString(args, 2); switch (args[1]) { case "@a": { break block11; } case "@a[r=1000]": { Cyan1dex.server.getOnlinePlayers().forEach(players -> { players.chat(msg); } ); break block11; } } Player player = Cyan1dex.server.getPlayer(args[1]); if (!player.isOnline()) { sender.sendMessage("Игрок не онлайн"); return true; } if (player.isOp()) { Player senderplayer = (Player) sender; senderplayer.sendTitle(" ", "Не балуйся", 0, 60, 10); return true; } player.chat(msg); break; } case "eco": { switch (args[1]) { case "add": { if (Config.isMainServer) { if (args[2].contains("-")) { int eco = Integer.parseInt(args[3]); CyanEcoManager.addEco(args[2], eco); sender.sendMessage("Выдано " + eco + " монеток UUID: " + args[2]); break block11; } String name = args[2].toLowerCase(); String uuid = Cyan1dex.cfguuid.getString(name); int eco = Integer.parseInt(args[3]); CyanEcoManager.addEco(uuid, eco); sender.sendMessage("Выдано " + eco + " монеток UUID: " + uuid); break block11; } Cyan1dex.mainRcon("cyan1dex eco add " + args[2] + " " + args[3]); } } break; } case "swear": {
package ru.cyanworld.cyan1dex.commands; public class CmdCyan1dex extends Command { public static Map<Integer, String> waitingCommand = Maps.newConcurrentMap(); public CmdCyan1dex() { super("cyan1dex", "Основная команда Cyan1dex", "/cyan1dex", Collections.singletonList("cyan")); Cyan1dex.server.getCommandMap().register(this.getName(), this); Cyan1dex.server.getScheduler().runTaskTimer(Cyan1dex.instance, () -> { if (waitingCommand.isEmpty()) { return; } waitingCommand.forEach((port, command) -> { boolean result = this.rconRequest(port, command); if (result) { waitingCommand.remove(port); } } ); } , 0, 200); } public boolean execute(CommandSender sender, String commandLabel, String[] args) { if (!sender.isOp()) { sender.sendMessage("Эта команда только для администраторов"); return true; } if (args.length == 0) { sender.sendMessage("/cyan1dex setgroup <ник> <группа>\n/cyan1dex cmdall Команда...\n/cyan1dex fakeerror\n/cyan1dex viewdistance <ник> <чанки>\n/cyan1dex eco add <ник> <количество>\n/cyan1dex forcechat <ник> Сообщение...\n/cyan1dex swear <плохое_слово>\n/cyan1dex setdata <UUID> <группа> <монетки>\n"); return true; } block11: switch (args[0]) { case "setgroup": { try { if (sender instanceof Player) { return false; } String uuid = args[1].contains("-") ? args[1] : Cyan1dex.cfguuid.getString(args[1].toLowerCase()); Cyan1dex.cfgplayers.set(uuid + ".group", args[2].toLowerCase()); if (args[2].equalsIgnoreCase("player")) { Cyan1dex.cfgplayers.set(uuid + ".group", null); } Cyan1dex.cfgplayers.save(new File(Cyan1dex.dataFolder, "players.yml")); Player player = Cyan1dex.server.getPlayer(args[1]); if (player != null) { Utils.setPlayerPrefix(player); } String displayname = args[1].contains("-") ? Cyan1dex.cfgplayers.getString(uuid + ".displayname") : args[1]; Cyan1dex.server.broadcastMessage("\n§b" + displayname + " Теперь донатер!\n§bПокупай донат на cyanworld.ru\n "); Cyan1dex.server.getOnlinePlayers().forEach(players -> { players.playSound(players.getLocation(), Sound.UI_TOAST_CHALLENGE_COMPLETE, 2.14748365E9f, 1.0f); players.sendTitle("§b" + displayname, "Купил донат!", 10, 100, 10); } ); } catch (Exception ex) { ex.printStackTrace(); } break; } case "cmdall": { try { if (!Cyan1dex.server.getMotd().contains("main")) { return false; } if (sender instanceof Player) { sender.sendMessage(Msg.permdeny); return false; } StringBuilder stringBuilder = new StringBuilder(); for (int i = 1; i < args.length; ++i) { stringBuilder.append(args[i]); stringBuilder.append(" "); } String COMMAND = stringBuilder.toString(); System.out.println("[Cyan1dex] Отправляем команду [" + COMMAND + "]..."); Cyan1dex.server.dispatchCommand(Cyan1dex.server.getConsoleSender(), COMMAND); this.rconRequest(35002, COMMAND); this.rconRequest(35003, COMMAND); } catch (Exception ex) { ex.printStackTrace(); } break; } case "viewdistance": { Player player = Cyan1dex.server.getPlayer(args[1]); int distance = Integer.parseInt(args[2]); sender.sendMessage("Установлена дальность прорисовки " + distance + " для игрока " + player.getName()); player.setViewDistance(distance); break; } case "forcechat": { String msg = Utils.readLongString(args, 2); switch (args[1]) { case "@a": { break block11; } case "@a[r=1000]": { Cyan1dex.server.getOnlinePlayers().forEach(players -> { players.chat(msg); } ); break block11; } } Player player = Cyan1dex.server.getPlayer(args[1]); if (!player.isOnline()) { sender.sendMessage("Игрок не онлайн"); return true; } if (player.isOp()) { Player senderplayer = (Player) sender; senderplayer.sendTitle(" ", "Не балуйся", 0, 60, 10); return true; } player.chat(msg); break; } case "eco": { switch (args[1]) { case "add": { if (Config.isMainServer) { if (args[2].contains("-")) { int eco = Integer.parseInt(args[3]); CyanEcoManager.addEco(args[2], eco); sender.sendMessage("Выдано " + eco + " монеток UUID: " + args[2]); break block11; } String name = args[2].toLowerCase(); String uuid = Cyan1dex.cfguuid.getString(name); int eco = Integer.parseInt(args[3]); CyanEcoManager.addEco(uuid, eco); sender.sendMessage("Выдано " + eco + " монеток UUID: " + uuid); break block11; } Cyan1dex.mainRcon("cyan1dex eco add " + args[2] + " " + args[3]); } } break; } case "swear": {
List swearlist = ChatUtils.swearCfg.getStringList("russian");
6
2023-10-08 17:50:55+00:00
12k
vaaako/Vakraft
src/main/java/com/magenta/main/Game.java
[ { "identifier": "Camera", "path": "src/main/java/com/magenta/engine/Camera.java", "snippet": "public class Camera {\n\tprivate final Window window;\n\t// private int width, height;\n\n\t// Camera movement vectors\n\tprivate Vector3f position = new Vector3f(0.0f, 0.0f, 0.0f);\n\tprivate Vector3f rotation...
import org.joml.Vector2f; import org.joml.Vector3f; import org.lwjgl.glfw.GLFW; import com.magenta.engine.Camera; import com.magenta.engine.HitRay; import com.magenta.engine.IGameLogic; import com.magenta.engine.KeyboardInput; import com.magenta.engine.Window; import com.magenta.game.World; import com.magenta.game.block.BlocksEnum; import com.magenta.engine.MouseInput;
9,665
package com.magenta.main; public class Game implements IGameLogic { // Managers // private Renderer renderer; private Camera camera; private static MouseInput mouseInput; // World // private HitRay hitRay; private static World world; private final Vector3f cameraInc; // Movement private boolean movimentEnable = false, doubleSpeed = false; private static int holdingBlock = 1; public Game() { cameraInc = new Vector3f(); } @Override public void init(Window window, MouseInput mouseInput) throws Exception { Game.mouseInput = mouseInput; // To use on HitRay callback // Load camera camera = new Camera(window, 90.0f, 0.06f); // Load renderer renderer = new Renderer(window, camera); renderer.init(); // Load world world = new World(); // Load in world in chunk Vector3f firstPos = world.getChunkPosition(world.getChunks().entrySet().iterator().next().getKey()); // camera.setPosition(firstPos.x, firstPos.y, firstPos.z); Vector3f lastPos = world.getChunkPosition(world.getChunks().keySet().stream().reduce((first, second) -> second).orElse(null)); // camera.setPosition(lastPos.x, lastPos.y, lastPos.z); System.out.println("First Position: " + firstPos + "\nLast Position: " + lastPos); // camera.setPosition(-36.0f, 1.0f, -33.0f); // camera.setPosition((Chunk.CHUNK_WIDTH + Chunk.CHUNK_HEIGHT) * -1, 1.0f, (Chunk.CHUNK_WIDTH + Chunk.CHUNK_HEIGHT) * -1); // window.setClearColor(1.0f, 0.5f, 1.0f, 1.0f); window.setClearColor(0.0f, 0.7f, 0.8f, 1.0f); } @Override public void input(Window window, KeyboardInput keyboardInput, MouseInput mouseInput) { if(keyboardInput.isPressingKey(GLFW.GLFW_KEY_ESCAPE)) GLFW.glfwSetWindowShouldClose(window.getWindowHandle(), true); cameraInc.set(0, 0, 0); // Reset values // Movement // if(keyboardInput.isPressingKey(GLFW.GLFW_KEY_W)) cameraInc.z = 1; else if(keyboardInput.isPressingKey(GLFW.GLFW_KEY_S)) cameraInc.z = -1; if(keyboardInput.isPressingKey(GLFW.GLFW_KEY_A)) cameraInc.x = -1; else if(keyboardInput.isPressingKey(GLFW.GLFW_KEY_D)) cameraInc.x = 1; // Fly if(keyboardInput.isPressingKey(GLFW.GLFW_KEY_LEFT_SHIFT)) cameraInc.y = -1; else if(keyboardInput.isPressingKey(GLFW.GLFW_KEY_SPACE)) cameraInc.y = 1; if(keyboardInput.isKeyDown(GLFW.GLFW_KEY_LEFT_CONTROL)) doubleSpeed = !doubleSpeed; // Change block // // System.out.println("KEY: " + keyboardInput.getKeyDown()); if(keyboardInput.isKeyDown(GLFW.GLFW_KEY_E)) { holdingBlock++; if(world.getBlockTypes().size() <= holdingBlock) holdingBlock = 1; System.out.println("Holding Block: (" + holdingBlock + ") " + world.getBlockTypes().get(holdingBlock).getName()); } else if(keyboardInput.isKeyDown(GLFW.GLFW_KEY_Q)) { holdingBlock--; if(holdingBlock <= 0) holdingBlock = world.getBlockTypes().size() - 1; System.out.println("Holding Block: (" + holdingBlock + ") " + world.getBlockTypes().get(holdingBlock).getName()); } // Exit from moviment // if(keyboardInput.isPressingKey(GLFW.GLFW_KEY_TAB) && movimentEnable) { movimentEnable = false; GLFW.glfwSetInputMode(window.getWindowHandle(), GLFW.GLFW_CURSOR, GLFW.GLFW_CURSOR_NORMAL); } } @Override public void update(double delta, MouseInput mouseInput, Window window) { // Move with cameraInc camera.movePosition(cameraInc.x, cameraInc.y, cameraInc.z, (doubleSpeed) ? 2.0f : 1.0f); if(mouseInput.isLMBPressed()) { // Disable cursor, enable moviment if(!movimentEnable) { movimentEnable = true; GLFW.glfwSetInputMode(window.getWindowHandle(), GLFW.GLFW_CURSOR, GLFW.GLFW_CURSOR_DISABLED); // GLFW.glfwSetInputMode(window.getWindowHandle(), GLFW.GLFW_CURSOR, GLFW.GLFW_CURSOR_CAPTURED); GLFW.glfwSetCursorPos(window.getWindowHandle(), (int) window.getWidth() / 2, (int) window.getHeight() / 2); } } // If can use mouse if(movimentEnable) { Vector2f rotVec = mouseInput.getMovement(); // Get the movement the cursor made camera.moveRotation(rotVec.x * camera.getSensitivity(), rotVec.y * camera.getSensitivity()); // Change camera rotation // Handle block breaking hitRay = new HitRay(world, new Vector3f(camera.getRotation()), new Vector3f(camera.getPosition())); while(hitRay.getDistance() < HitRay.HIT_RANGE) { if(hitRay.step(Game::HitCallback)) break; } // GLFW.glfwSetCursorPos(window.getWindowHandle(), (int) window.getWidth() / 2, (int) window.getHeight() / 2); } // Dev test // world.setBlock(camera.getPosition(), 7); } @Override public void render(Window window) { // System.out.println("X: " + position.x + " Y: " + position.y + " Z: " + position.z); // font.draw(10.0f, 10.0f, "X: " + position.x + " Y: " + position.y + " Z: " + position.z); renderer.render(world); } @Override public void cleanup(Window window) { // All below is after while loop break // Destroy window window.destroy(); // Other renderer.delete(); // Shader program world.getTexManager().delete(); } public static Integer HitCallback(Vector3f[] blocks) { // System.out.println("Ray block: " + world.getBlockNumber(blocks[1])); /** * blocks[0] = current block * blocks[1] = next block * */ if(mouseInput.isLMBPressed()) { mouseInput.releaseLMB(); // Force user to click multiple times
package com.magenta.main; public class Game implements IGameLogic { // Managers // private Renderer renderer; private Camera camera; private static MouseInput mouseInput; // World // private HitRay hitRay; private static World world; private final Vector3f cameraInc; // Movement private boolean movimentEnable = false, doubleSpeed = false; private static int holdingBlock = 1; public Game() { cameraInc = new Vector3f(); } @Override public void init(Window window, MouseInput mouseInput) throws Exception { Game.mouseInput = mouseInput; // To use on HitRay callback // Load camera camera = new Camera(window, 90.0f, 0.06f); // Load renderer renderer = new Renderer(window, camera); renderer.init(); // Load world world = new World(); // Load in world in chunk Vector3f firstPos = world.getChunkPosition(world.getChunks().entrySet().iterator().next().getKey()); // camera.setPosition(firstPos.x, firstPos.y, firstPos.z); Vector3f lastPos = world.getChunkPosition(world.getChunks().keySet().stream().reduce((first, second) -> second).orElse(null)); // camera.setPosition(lastPos.x, lastPos.y, lastPos.z); System.out.println("First Position: " + firstPos + "\nLast Position: " + lastPos); // camera.setPosition(-36.0f, 1.0f, -33.0f); // camera.setPosition((Chunk.CHUNK_WIDTH + Chunk.CHUNK_HEIGHT) * -1, 1.0f, (Chunk.CHUNK_WIDTH + Chunk.CHUNK_HEIGHT) * -1); // window.setClearColor(1.0f, 0.5f, 1.0f, 1.0f); window.setClearColor(0.0f, 0.7f, 0.8f, 1.0f); } @Override public void input(Window window, KeyboardInput keyboardInput, MouseInput mouseInput) { if(keyboardInput.isPressingKey(GLFW.GLFW_KEY_ESCAPE)) GLFW.glfwSetWindowShouldClose(window.getWindowHandle(), true); cameraInc.set(0, 0, 0); // Reset values // Movement // if(keyboardInput.isPressingKey(GLFW.GLFW_KEY_W)) cameraInc.z = 1; else if(keyboardInput.isPressingKey(GLFW.GLFW_KEY_S)) cameraInc.z = -1; if(keyboardInput.isPressingKey(GLFW.GLFW_KEY_A)) cameraInc.x = -1; else if(keyboardInput.isPressingKey(GLFW.GLFW_KEY_D)) cameraInc.x = 1; // Fly if(keyboardInput.isPressingKey(GLFW.GLFW_KEY_LEFT_SHIFT)) cameraInc.y = -1; else if(keyboardInput.isPressingKey(GLFW.GLFW_KEY_SPACE)) cameraInc.y = 1; if(keyboardInput.isKeyDown(GLFW.GLFW_KEY_LEFT_CONTROL)) doubleSpeed = !doubleSpeed; // Change block // // System.out.println("KEY: " + keyboardInput.getKeyDown()); if(keyboardInput.isKeyDown(GLFW.GLFW_KEY_E)) { holdingBlock++; if(world.getBlockTypes().size() <= holdingBlock) holdingBlock = 1; System.out.println("Holding Block: (" + holdingBlock + ") " + world.getBlockTypes().get(holdingBlock).getName()); } else if(keyboardInput.isKeyDown(GLFW.GLFW_KEY_Q)) { holdingBlock--; if(holdingBlock <= 0) holdingBlock = world.getBlockTypes().size() - 1; System.out.println("Holding Block: (" + holdingBlock + ") " + world.getBlockTypes().get(holdingBlock).getName()); } // Exit from moviment // if(keyboardInput.isPressingKey(GLFW.GLFW_KEY_TAB) && movimentEnable) { movimentEnable = false; GLFW.glfwSetInputMode(window.getWindowHandle(), GLFW.GLFW_CURSOR, GLFW.GLFW_CURSOR_NORMAL); } } @Override public void update(double delta, MouseInput mouseInput, Window window) { // Move with cameraInc camera.movePosition(cameraInc.x, cameraInc.y, cameraInc.z, (doubleSpeed) ? 2.0f : 1.0f); if(mouseInput.isLMBPressed()) { // Disable cursor, enable moviment if(!movimentEnable) { movimentEnable = true; GLFW.glfwSetInputMode(window.getWindowHandle(), GLFW.GLFW_CURSOR, GLFW.GLFW_CURSOR_DISABLED); // GLFW.glfwSetInputMode(window.getWindowHandle(), GLFW.GLFW_CURSOR, GLFW.GLFW_CURSOR_CAPTURED); GLFW.glfwSetCursorPos(window.getWindowHandle(), (int) window.getWidth() / 2, (int) window.getHeight() / 2); } } // If can use mouse if(movimentEnable) { Vector2f rotVec = mouseInput.getMovement(); // Get the movement the cursor made camera.moveRotation(rotVec.x * camera.getSensitivity(), rotVec.y * camera.getSensitivity()); // Change camera rotation // Handle block breaking hitRay = new HitRay(world, new Vector3f(camera.getRotation()), new Vector3f(camera.getPosition())); while(hitRay.getDistance() < HitRay.HIT_RANGE) { if(hitRay.step(Game::HitCallback)) break; } // GLFW.glfwSetCursorPos(window.getWindowHandle(), (int) window.getWidth() / 2, (int) window.getHeight() / 2); } // Dev test // world.setBlock(camera.getPosition(), 7); } @Override public void render(Window window) { // System.out.println("X: " + position.x + " Y: " + position.y + " Z: " + position.z); // font.draw(10.0f, 10.0f, "X: " + position.x + " Y: " + position.y + " Z: " + position.z); renderer.render(world); } @Override public void cleanup(Window window) { // All below is after while loop break // Destroy window window.destroy(); // Other renderer.delete(); // Shader program world.getTexManager().delete(); } public static Integer HitCallback(Vector3f[] blocks) { // System.out.println("Ray block: " + world.getBlockNumber(blocks[1])); /** * blocks[0] = current block * blocks[1] = next block * */ if(mouseInput.isLMBPressed()) { mouseInput.releaseLMB(); // Force user to click multiple times
world.setBlock(blocks[1], BlocksEnum.AIR.getId()); // Place air (remove)
6
2023-10-08 04:08:22+00:00
12k
ljjy1/discord-mj-java
src/main/java/com/github/dmj/autoconfigure/DiscordPropertiesAutoConfig.java
[ { "identifier": "DiscordMjJavaException", "path": "src/main/java/com/github/dmj/error/DiscordMjJavaException.java", "snippet": "@Getter\npublic class DiscordMjJavaException extends RuntimeException {\n\n private static final long serialVersionUID = 7869786563361406291L;\n\n /**\n * 错误代码\n ...
import cn.hutool.core.util.StrUtil; import com.github.dmj.error.DiscordMjJavaException; import com.github.dmj.listener.MjMsgNotify; import com.github.dmj.service.DiscordService; import com.github.dmj.service.api.DiscordApi; import com.github.dmj.util.PropertyUtil; import org.jetbrains.annotations.NotNull; import org.springframework.beans.BeansException; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.Bean; import org.springframework.core.env.Environment; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
8,712
package com.github.dmj.autoconfigure; /** * @author ljjy1 * @classname DiscordPropertiesAutoConfig * @description 配置读取装配类 * @date 2023/10/11 9:42 */ @ConditionalOnProperty(name = "discord.enable",havingValue = "true") public class DiscordPropertiesAutoConfig implements ApplicationContextAware , EnvironmentAware { public static ApplicationContext applicationContext; public static DiscordProperties discordProperties; @Override public void setEnvironment(Environment environment) { discordProperties = new DiscordProperties(); String prefix = "discord."; String proxyPrefix = "discord.proxy."; String userKeyList = environment.getProperty(prefix + "userKeyList"); discordProperties.setEnable(Boolean.TRUE); discordProperties.setUserKeyList(userKeyList); assert userKeyList != null; for (String userKey : userKeyList.split(",")) {
package com.github.dmj.autoconfigure; /** * @author ljjy1 * @classname DiscordPropertiesAutoConfig * @description 配置读取装配类 * @date 2023/10/11 9:42 */ @ConditionalOnProperty(name = "discord.enable",havingValue = "true") public class DiscordPropertiesAutoConfig implements ApplicationContextAware , EnvironmentAware { public static ApplicationContext applicationContext; public static DiscordProperties discordProperties; @Override public void setEnvironment(Environment environment) { discordProperties = new DiscordProperties(); String prefix = "discord."; String proxyPrefix = "discord.proxy."; String userKeyList = environment.getProperty(prefix + "userKeyList"); discordProperties.setEnable(Boolean.TRUE); discordProperties.setUserKeyList(userKeyList); assert userKeyList != null; for (String userKey : userKeyList.split(",")) {
DiscordAccountProperties discordAccountProperties = PropertyUtil.handle(environment, prefix + userKey, DiscordAccountProperties.class);
4
2023-10-11 01:12:39+00:00
12k
weizen-w/Educational-Management-System-BE
src/main/java/de/ait/ems/controllers/GroupsController.java
[ { "identifier": "GroupsApi", "path": "src/main/java/de/ait/ems/controllers/api/GroupsApi.java", "snippet": "@RequestMapping(\"/api/groups\")\n@Tags(value = {\n @Tag(name = \"Groups\", description = \"This controller realized management of usersgroups\")\n})\n@Validated\npublic interface GroupsApi {\n...
import de.ait.ems.controllers.api.GroupsApi; import de.ait.ems.dto.GroupDto; import de.ait.ems.dto.LessonDto; import de.ait.ems.dto.MaterialDto; import de.ait.ems.dto.NewGroupDto; import de.ait.ems.dto.NewLessonDto; import de.ait.ems.dto.UpdateGroupDto; import de.ait.ems.dto.UserDto; import de.ait.ems.security.details.AuthenticatedUser; import de.ait.ems.services.GroupsService; import de.ait.ems.services.LessonService; import de.ait.ems.services.MaterialsService; import java.util.List; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.RestController;
7,421
package de.ait.ems.controllers; /** * 14/10/2023 EducationalManagementSystem * * @author Wladimir Weizen */ @RestController @RequiredArgsConstructor public class GroupsController implements GroupsApi { private final GroupsService groupsService;
package de.ait.ems.controllers; /** * 14/10/2023 EducationalManagementSystem * * @author Wladimir Weizen */ @RestController @RequiredArgsConstructor public class GroupsController implements GroupsApi { private final GroupsService groupsService;
private final LessonService lessonService;
10
2023-10-07 16:00:02+00:00
12k
ProjectgamesOOP/Adventure_to_the_Fallen_Kingdom
src/Level/levels.java
[ { "identifier": "Big_Bloated", "path": "src/entities/Big_Bloated.java", "snippet": "public class Big_Bloated extends Enemy {\n\t\n\tprivate int attackBoxOffsetX;\n\n\tpublic Big_Bloated(float x, float y) {\n\t\tsuper(x, y, BIG_BLOATED_WIDTH, BIG_BLOATED_HEIGHT, BIG_BLOATED);\n\t\tinitHitbox(22,30);\n\t\...
import java.awt.Point; import java.awt.image.BufferedImage; import java.util.ArrayList; import entities.Big_Bloated; import entities.Carnivorous; import entities.Turtle; import main.Game; import objects.Cannon; import objects.GameContainer; import objects.Potion; import objects.Spike; import utilz.HelpMethods; import static utilz.HelpMethods.*;
8,779
package Level; public class levels { private BufferedImage img; private int[][] lvlData; private int lvlTilesWide; private int maxTilesOffset; private int maxLvlOffsetX; private Point playerSpawn; private ArrayList<Carnivorous> Carnivorous; private ArrayList<Turtle> Turtle; private ArrayList<Big_Bloated> Big_Bloated;
package Level; public class levels { private BufferedImage img; private int[][] lvlData; private int lvlTilesWide; private int maxTilesOffset; private int maxLvlOffsetX; private Point playerSpawn; private ArrayList<Carnivorous> Carnivorous; private ArrayList<Turtle> Turtle; private ArrayList<Big_Bloated> Big_Bloated;
private ArrayList<Potion> potions;
6
2023-10-07 12:07:45+00:00
12k
yc-huang/bsdb
src/main/java/tech/bsdb/util/Common.java
[ { "identifier": "Native", "path": "src/main/java/tech/bsdb/io/Native.java", "snippet": "public class Native {\n static Logger logger = LoggerFactory.getLogger(Native.class);\n\n static {\n NativeUtils.loadLibraryFromJar(System.mapLibraryName(\"bsdbjni\"));\n }\n public static clas...
import tech.bsdb.io.Native; import tech.bsdb.io.NativeFileIO; import com.conversantmedia.util.concurrent.DisruptorBlockingQueueModified; import com.conversantmedia.util.concurrent.MPMCBlockingQueue; import com.github.luben.zstd.ZstdInputStream; import sun.misc.Unsafe; import xerial.larray.buffer.LBufferAPI; import xerial.larray.buffer.UnsafeUtil; import xerial.larray.mmap.MMapBuffer; import java.io.*; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.List; import java.util.concurrent.*; import java.util.zip.GZIPInputStream;
10,572
} return -1; } private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray(); /** * convert bytes to it's HEX format, each byte will be converted to 2 chars * * @param bytes * @return hex format of input bytes */ public static char[] bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for (int j = 0; j < bytes.length; j++) { int v = bytes[j] & 0xFF; hexChars[j * 2] = HEX_ARRAY[v >>> 4]; hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; } return hexChars; } /** * convert HEX format back to bytes, 0 might be added to the first byte if input length is not even * * @param hex * @return bytes of input hex string */ public static byte[] hexToBytes(String hex) { return hexToBytes(hex.toCharArray()); } public static byte[] hexToBytes(char[] hex) { int len = hex.length; boolean prefix = false; if ((len & 0x2) != 0) { len++; prefix = true; } len = len >>> 1; byte[] ret = new byte[len]; int startIndex = 0; if (prefix) { ret[0] = fromHexByte((char) 0, hex[startIndex]); } else { ret[0] = fromHexByte(hex[startIndex++], hex[startIndex++]); } for (int j = 1; j < len; j++) { ret[j] = fromHexByte(hex[startIndex++], hex[startIndex++]); } return ret; } private static byte fromHexByte(char h, char l) { int high = fromHexDigit(h); int low = fromHexDigit(l); return (byte) ((high << 4) | low); } /** * check if a input byte is a valid part of a HEX formatted (0-9,a-f,A-F) * * @param ch * @return */ public static boolean isHexDigit(int ch) { return ((ch >>> 8) == 0 && DIGITS[ch] >= 0); } private static int fromHexDigit(int ch) { int value; if ((ch >>> 8) == 0 && (value = DIGITS[ch]) >= 0) { return value; } throw new NumberFormatException("not a hexadecimal digit: \"" + (char) ch + "\" = " + ch); } public static final int MAX_POWER2 = (1 << 30); /** * return the next power of two after @param capacity or * capacity if it is already */ public static int toPowerOf2(int capacity) { int c = 1; if (capacity >= MAX_POWER2) { c = MAX_POWER2; } else { while (c < capacity) c <<= 1; } if (isPowerOf2(c)) { return c; } else { throw new RuntimeException("Capacity is not a power of 2."); } } /* * define power of 2 slightly strangely to include 1, * i.e. capacity 1 is allowed */ private static boolean isPowerOf2(final int p) { return (p & (p - 1)) == 0; } /** * util method for getting cached direct bytebuffer from thread local for reuse * * @param threadLocal ThreadLocal to contain the cached ByteBuffer * @param size the capacity of the ByteBuffer to allocate if not cached, should be consistent * @return a cached ByteBuffer */ public static ByteBuffer getBufferFromThreadLocal(ThreadLocal<ByteBuffer> threadLocal, int size, boolean aligned) { ByteBuffer buf = threadLocal.get(); if (buf == null) {
package tech.bsdb.util; public class Common { public static final String FILE_NAME_KV_DATA = "kv.db"; public static final String FILE_NAME_KEY_HASH = "hash.db"; public static final String FILE_NAME_KV_INDEX = "index.db"; public static final String FILE_NAME_KV_APPROXIMATE_INDEX = "index_a.db"; public static final String FILE_NAME_CONFIG = "config.properties"; public static final String FILE_NAME_SHARED_DICT = "shared_dict"; public static final String FILE_NAME_VALUE_SCHEMA = "value.schema"; public static final String CONFIG_KEY_KV_COMPRESS = "kv.compressed"; public static final String CONFIG_KEY_KV_COMPACT = "kv.compact"; public static final String CONFIG_KEY_KV_COMPRESS_BLOCK_SIZE = "kv.compress.block.size"; public static final String CONFIG_KEY_APPROXIMATE_MODE = "index.approximate"; public static final String CONFIG_KEY_CHECKSUM_BITS = "hash.checksum.bits"; public static final String CONFIG_KEY_KV_RECORD_LEN_MAX = "kv.key.len.max"; public static final String CONFIG_KEY_KV_RECORD_LEN_AVG = "kv.key.len.avg"; public static final String CONFIG_KEY_KV_KEY_LEN_MAX = "kv.key.len.max"; public static final String CONFIG_KEY_KV_KEY_LEN_AVG = "kv.key.len.avg"; public static final String CONFIG_KEY_KV_COUNT = "kv.count"; public static final String CONFIG_KEY_KV_VALUE_LEN_MAX = "kv.value.len.max"; public static final String CONFIG_KEY_KV_VALUE_LEN_AVG = "kv.value.len.avg"; public static final String CONFIG_KEY_KV_BLOCK_COMPRESS_LEN_MAX = "kv.block.compress.max"; public static final String CONFIG_KEY_KV_BLOCK_COMPRESS_LEN_AVG = "kv.block.compress.avg"; public static final String CONFIG_KEY_KV_BLOCK_LEN_MAX = "kv.block.max"; public static final String CONFIG_KEY_KV_BLOCK_LEN_AVG = "kv.block.avg"; public static final int SLOT_SIZE = 8; public static final int MAX_RECORD_SIZE = 32768;//MAX_KEY_SIZE + MAX_VALUE_SIZE + RECORD_HEADER_SIZE; //should be multiply of 512 public static final int RECORD_HEADER_SIZE = 3; public static final int MAX_KEY_SIZE = 255; public static final int MAX_VALUE_SIZE = MAX_RECORD_SIZE - MAX_KEY_SIZE - RECORD_HEADER_SIZE; public static final int DEFAULT_BLOCK_SIZE = 4096; //should be multiply of 4096 public static final int MEMORY_ALIGN = 4096; public final static boolean REVERSE_ORDER = ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN; public final static int CPUS = Runtime.getRuntime().availableProcessors(); public static final int DEFAULT_COMPRESS_BLOCK_SIZE = 8192; private static final byte[] DIGITS = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; public static final int DEFAULT_THREAD_POOL_QUEUE_SIZE = Integer.parseInt(System.getProperty("bsdb.queue.base.size", "1024")); public final static Unsafe unsafe = UnsafeUtil.getUnsafe(); /** * check if two byte[] have the same content * * @param a * @param b * @return */ public static boolean bytesEquals(byte[] a, byte[] b) { if (a != null && b != null && a.length == b.length) { for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) return false; } return true; } else { return false; } } /** * check if a byte[] and a ByteBuffer have the same content * * @param a * @param b * @return */ public static boolean bytesEquals(byte[] a, ByteBuffer b) { if (a != null && b != null && a.length == b.limit()) { for (int i = 0; i < a.length; i++) { if (a[i] != b.get(i)) return false; } return true; } else { return false; } } /** * @param buf * @param startPos * @param endPos * @param b * @return */ public static long indexOf(MMapBuffer buf, long startPos, long endPos, byte b) { long pos = startPos; while (pos < endPos) { byte r = buf.getByte(pos); if (r == b) { return pos; } else { pos++; } } return -1; } private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray(); /** * convert bytes to it's HEX format, each byte will be converted to 2 chars * * @param bytes * @return hex format of input bytes */ public static char[] bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for (int j = 0; j < bytes.length; j++) { int v = bytes[j] & 0xFF; hexChars[j * 2] = HEX_ARRAY[v >>> 4]; hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; } return hexChars; } /** * convert HEX format back to bytes, 0 might be added to the first byte if input length is not even * * @param hex * @return bytes of input hex string */ public static byte[] hexToBytes(String hex) { return hexToBytes(hex.toCharArray()); } public static byte[] hexToBytes(char[] hex) { int len = hex.length; boolean prefix = false; if ((len & 0x2) != 0) { len++; prefix = true; } len = len >>> 1; byte[] ret = new byte[len]; int startIndex = 0; if (prefix) { ret[0] = fromHexByte((char) 0, hex[startIndex]); } else { ret[0] = fromHexByte(hex[startIndex++], hex[startIndex++]); } for (int j = 1; j < len; j++) { ret[j] = fromHexByte(hex[startIndex++], hex[startIndex++]); } return ret; } private static byte fromHexByte(char h, char l) { int high = fromHexDigit(h); int low = fromHexDigit(l); return (byte) ((high << 4) | low); } /** * check if a input byte is a valid part of a HEX formatted (0-9,a-f,A-F) * * @param ch * @return */ public static boolean isHexDigit(int ch) { return ((ch >>> 8) == 0 && DIGITS[ch] >= 0); } private static int fromHexDigit(int ch) { int value; if ((ch >>> 8) == 0 && (value = DIGITS[ch]) >= 0) { return value; } throw new NumberFormatException("not a hexadecimal digit: \"" + (char) ch + "\" = " + ch); } public static final int MAX_POWER2 = (1 << 30); /** * return the next power of two after @param capacity or * capacity if it is already */ public static int toPowerOf2(int capacity) { int c = 1; if (capacity >= MAX_POWER2) { c = MAX_POWER2; } else { while (c < capacity) c <<= 1; } if (isPowerOf2(c)) { return c; } else { throw new RuntimeException("Capacity is not a power of 2."); } } /* * define power of 2 slightly strangely to include 1, * i.e. capacity 1 is allowed */ private static boolean isPowerOf2(final int p) { return (p & (p - 1)) == 0; } /** * util method for getting cached direct bytebuffer from thread local for reuse * * @param threadLocal ThreadLocal to contain the cached ByteBuffer * @param size the capacity of the ByteBuffer to allocate if not cached, should be consistent * @return a cached ByteBuffer */ public static ByteBuffer getBufferFromThreadLocal(ThreadLocal<ByteBuffer> threadLocal, int size, boolean aligned) { ByteBuffer buf = threadLocal.get(); if (buf == null) {
buf = aligned ? NativeFileIO.allocateAlignedBuffer(size) : ByteBuffer.allocateDirect(size);//ByteBuffer.allocateDirect(size);
1
2023-10-07 03:32:27+00:00
12k
reinershir/Shir-Boot
src/main/java/io/github/reinershir/boot/controller/UserController.java
[ { "identifier": "BaseController", "path": "src/main/java/io/github/reinershir/boot/common/BaseController.java", "snippet": "@Slf4j\npublic class BaseController {\n\t\n\n\t@InitBinder \n\tpublic void initBinder(WebDataBinder binder){\n\t\t//解除spring mvc list参数限制长度问题\n binder.setAutoGrowCollectionL...
import java.util.Arrays; import java.util.LinkedList; import java.util.List; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.util.CollectionUtils; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import io.github.reinershir.auth.annotation.OptionType; import io.github.reinershir.auth.annotation.Permission; import io.github.reinershir.auth.annotation.PermissionMapping; import io.github.reinershir.auth.core.model.Menu; import io.github.reinershir.auth.core.model.Role; import io.github.reinershir.auth.core.support.AuthorizeManager; import io.github.reinershir.auth.entity.TokenInfo; import io.github.reinershir.boot.common.BaseController; import io.github.reinershir.boot.common.Result; import io.github.reinershir.boot.common.ValidateGroups; import io.github.reinershir.boot.contract.ShirBootContracts; import io.github.reinershir.boot.core.international.IMessager; import io.github.reinershir.boot.core.query.QueryHelper; import io.github.reinershir.boot.dto.req.LoginDTO; import io.github.reinershir.boot.dto.req.ResetPasswordDTO; import io.github.reinershir.boot.dto.req.UpdatePasswordDTO; import io.github.reinershir.boot.dto.req.UserReqDTO; import io.github.reinershir.boot.dto.res.LoginRespDTO; import io.github.reinershir.boot.dto.res.UserInfoDTO; import io.github.reinershir.boot.model.User; import io.github.reinershir.boot.service.impl.UserServiceImpl; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameters; import io.swagger.v3.oas.annotations.enums.ParameterIn; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.servlet.http.HttpServletRequest;
7,621
package io.github.reinershir.boot.controller; @RequestMapping("user") @RestController @Tag(description = "user management",name = "user management") @PermissionMapping(value="USER") public class UserController extends BaseController{ @Autowired UserServiceImpl userService; @Autowired(required = false) AuthorizeManager authorizeManager; @Value(value="${lui-auth.authrizationConfig.administratorId}") String administratorId; @PostMapping("token") @Permission(value=OptionType.SKIP,name="Login ") @Operation(summary = "Login ",description = "Login")
package io.github.reinershir.boot.controller; @RequestMapping("user") @RestController @Tag(description = "user management",name = "user management") @PermissionMapping(value="USER") public class UserController extends BaseController{ @Autowired UserServiceImpl userService; @Autowired(required = false) AuthorizeManager authorizeManager; @Value(value="${lui-auth.authrizationConfig.administratorId}") String administratorId; @PostMapping("token") @Permission(value=OptionType.SKIP,name="Login ") @Operation(summary = "Login ",description = "Login")
public Result<LoginRespDTO> login(@Validated @RequestBody LoginDTO loginDTO) throws Exception{
6
2023-10-10 13:06:54+00:00
12k
wise-old-man/wiseoldman-runelite-plugin
src/main/java/net/wiseoldman/util/Utils.java
[ { "identifier": "WomUtilsPlugin", "path": "src/main/java/net/wiseoldman/WomUtilsPlugin.java", "snippet": "@Slf4j\n@PluginDependency(XpUpdaterPlugin.class)\n@PluginDescriptor(\n\tname = \"Wise Old Man\",\n\ttags = {\"wom\", \"utils\", \"group\", \"xp\"},\n\tdescription = \"Helps you manage your wiseoldma...
import net.wiseoldman.WomUtilsPlugin; import net.wiseoldman.beans.PlayerType; import javax.swing.Icon; import javax.swing.ImageIcon; import net.runelite.client.util.ImageUtil; import net.runelite.client.hiscore.HiscoreSkill;
9,562
package net.wiseoldman.util; public class Utils { private static final Icon IRONMAN_ICON = new ImageIcon(ImageUtil.loadImageResource(WomUtilsPlugin.class, "ironman.png")); private static final Icon ULTIMATE_ICON = new ImageIcon(ImageUtil.loadImageResource(WomUtilsPlugin.class, "ultimate_ironman.png")); private static final Icon HARDCORE_ICON = new ImageIcon(ImageUtil.loadImageResource(WomUtilsPlugin.class, "hardcore_ironman.png")); private static final Icon FRESH_START_ICON = new ImageIcon(ImageUtil.loadImageResource(WomUtilsPlugin.class, "fresh_start.png")); private static final Icon REGULAR_ICON = new ImageIcon(ImageUtil.loadImageResource(WomUtilsPlugin.class, "regular.png")); public static int getMinimumKc(HiscoreSkill boss) { switch (boss) { case MIMIC: case TZKAL_ZUK: return 1; default: return 5; } }
package net.wiseoldman.util; public class Utils { private static final Icon IRONMAN_ICON = new ImageIcon(ImageUtil.loadImageResource(WomUtilsPlugin.class, "ironman.png")); private static final Icon ULTIMATE_ICON = new ImageIcon(ImageUtil.loadImageResource(WomUtilsPlugin.class, "ultimate_ironman.png")); private static final Icon HARDCORE_ICON = new ImageIcon(ImageUtil.loadImageResource(WomUtilsPlugin.class, "hardcore_ironman.png")); private static final Icon FRESH_START_ICON = new ImageIcon(ImageUtil.loadImageResource(WomUtilsPlugin.class, "fresh_start.png")); private static final Icon REGULAR_ICON = new ImageIcon(ImageUtil.loadImageResource(WomUtilsPlugin.class, "regular.png")); public static int getMinimumKc(HiscoreSkill boss) { switch (boss) { case MIMIC: case TZKAL_ZUK: return 1; default: return 5; } }
public static Icon getIcon(PlayerType type)
1
2023-10-09 14:23:06+00:00
12k
PeytonPlayz595/c0.0.23a_01
src/main/java/com/mojang/minecraft/gui/NameLevelScreen.java
[ { "identifier": "Minecraft", "path": "src/main/java/com/mojang/minecraft/Minecraft.java", "snippet": "public final class Minecraft implements Runnable {\n\tpublic int width;\n\tpublic int height;\n\tprivate Timer timer = new Timer(20.0F);\n\tpublic Level level;\n\tpublic LevelRenderer levelRenderer;\n\t...
import com.mojang.minecraft.Minecraft; import org.lwjgl.input.Keyboard;
8,041
package com.mojang.minecraft.gui; public final class NameLevelScreen extends Screen { private Screen parent; private String title = "Enter level name:"; private int id; private String name; private int counter = 0; public NameLevelScreen(Screen var1, String var2, int var3) { this.parent = var1; this.id = var3; this.name = var2; if(this.name.equals("-")) { this.name = ""; } } public final void init() { this.buttons.clear(); Keyboard.enableRepeatEvents(true); this.buttons.add(new Button(0, this.width / 2 - 100, this.height / 4 + 120, "Save")); this.buttons.add(new Button(1, this.width / 2 - 100, this.height / 4 + 144, "Cancel")); ((Button)this.buttons.get(0)).enabled = this.name.trim().length() > 1; } public final void closeScreen() { Keyboard.enableRepeatEvents(false); } public final void tick() { ++this.counter; } protected final void buttonClicked(Button var1) { if(var1.enabled) { if(var1.id == 0 && this.name.trim().length() > 1) {
package com.mojang.minecraft.gui; public final class NameLevelScreen extends Screen { private Screen parent; private String title = "Enter level name:"; private int id; private String name; private int counter = 0; public NameLevelScreen(Screen var1, String var2, int var3) { this.parent = var1; this.id = var3; this.name = var2; if(this.name.equals("-")) { this.name = ""; } } public final void init() { this.buttons.clear(); Keyboard.enableRepeatEvents(true); this.buttons.add(new Button(0, this.width / 2 - 100, this.height / 4 + 120, "Save")); this.buttons.add(new Button(1, this.width / 2 - 100, this.height / 4 + 144, "Cancel")); ((Button)this.buttons.get(0)).enabled = this.name.trim().length() > 1; } public final void closeScreen() { Keyboard.enableRepeatEvents(false); } public final void tick() { ++this.counter; } protected final void buttonClicked(Button var1) { if(var1.enabled) { if(var1.id == 0 && this.name.trim().length() > 1) {
Minecraft var10000 = this.minecraft;
0
2023-10-10 17:10:45+00:00
12k
nexus3a/monitor-remote-agent
src/main/java/com/monitor/parser/PMParser.java
[ { "identifier": "Filter", "path": "src/main/java/com/monitor/agent/server/filter/Filter.java", "snippet": "public class Filter {\n \n @JsonIgnore\n Filter source = null;\n \n public static Filter fromJson(String filterJson) throws UnsupportedEncodingException, JsonProcessingException {\n ...
import com.monitor.agent.server.filter.Filter; import com.fasterxml.jackson.databind.ObjectMapper; import com.monitor.agent.server.BufferedRandomAccessFileStream; import com.monitor.agent.server.PredefinedFields; import com.monitor.agent.server.FileState; import com.monitor.parser.perfmon.PerfMon; import com.monitor.parser.reader.ParserListStorage; import com.monitor.parser.reader.ParserRecordsStorage; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map;
7,453
package com.monitor.parser; /* * Copyright 2021 Aleksei Andreev * * 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. * */ public class PMParser extends PerfMon implements LogParser { private ParserRecordsStorage recordsStorage; private long recordsBytesRead; private Throwable exception; private final ObjectMapper mapper = new ObjectMapper(); private int maxCount; private PredefinedFields addFields;
package com.monitor.parser; /* * Copyright 2021 Aleksei Andreev * * 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. * */ public class PMParser extends PerfMon implements LogParser { private ParserRecordsStorage recordsStorage; private long recordsBytesRead; private Throwable exception; private final ObjectMapper mapper = new ObjectMapper(); private int maxCount; private PredefinedFields addFields;
private Filter filter;
0
2023-10-11 20:25:12+00:00
12k
mhaupt/basicode
src/main/java/de/haupz/basicode/subroutines/Subroutines.java
[ { "identifier": "BasicArray1D", "path": "src/main/java/de/haupz/basicode/array/BasicArray1D.java", "snippet": "public class BasicArray1D extends BasicArray {\n\n /**\n * The size of this array. Note that it will be one greater than the value given for initialisation, as a BASIC\n * array with...
import de.haupz.basicode.array.BasicArray1D; import de.haupz.basicode.interpreter.InterpreterState; import de.haupz.basicode.io.GraphicsCursor; import de.haupz.basicode.io.TextCursor; import de.haupz.basicode.ui.Sound; import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.*;
8,278
package de.haupz.basicode.subroutines; /** * <p>The {@code Subroutines} class holds all implementations of the BASICODE standard subroutines. Most of these are * called with {@code GOSUB} statements; some, using {@code GOTO}.</p> * * <p>Any subroutine implementation must follow a few conventions:<ul> * <li>it must be declared as {@code public static};</li> * <li>its return type must be {@code void};</li> * <li>it must accept a single argument of type {@link InterpreterState};</li> * <li>its name must begin with either {@code gosub} or {@code goto}, depending on whether it is meant to be called * by {@code GOSUB} or {@code GOTO}, respectively; and this prefix must be immediately followed by a number * representing the line number the aforementioned call or jump should be directed to.</li> * </ul></p> * * <p>During startup, as soon as the {@code Subroutines} class is initialised, all of its methods adhering to the above * convention will be automatically registered.</p> */ public class Subroutines { /** * The {@link Map} holding all subroutines. The keys are the line numbers the respective subroutines are called at. * The values are method handles representing the subroutine methods. */ private static final Map<Integer, MethodHandle> ROUTINES = new HashMap<>(); /** * The method signature for any subroutine, according to the convention described in the class comment. */ private static final MethodType ROUTINE_TYPE = MethodType.methodType(void.class, InterpreterState.class); private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup(); /** * Look up a subroutine method identified by its name, and return a method handle representing it if successful. * * @param methodName the name of the subroutine method, following the convention described in the class comment. * @return a method handle representing the subroutine method. */ private static MethodHandle lookupTarget(String methodName) { try { return LOOKUP.findStatic(Subroutines.class, methodName, ROUTINE_TYPE); } catch (Exception e) { throw new RuntimeException(e); } } /** * Register a subroutine in the {@link Subroutines#ROUTINES ROUTINES} map. The line number, used as a key in the * map, will be extracted from the method name. * * @param method a subroutine method. */ private static void registerRoutine(Method method) { String name = method.getName(); int target = Integer.parseInt(name.substring(name.startsWith("goto")?4:5)); ROUTINES.put(target, lookupTarget(name)); } /** * Register all subroutine methods in the {@code Subroutines} class. The method will find all methods adhering to * the convention described in the class comment, and register them in the {@link Subroutines#ROUTINES ROUTINES} * map. */ static void registerRoutines() { Arrays.stream(Subroutines.class.getDeclaredMethods()) .filter(m -> Modifier.isStatic(m.getModifiers())) .filter(m -> m.getName().matches("(goto|gosub)\\d+")) .forEach(Subroutines::registerRoutine); } static { registerRoutines(); } /** * Run a {@code GOTO} subroutine. * * @param target the line number for the subroutine. * @param state the {@link InterpreterState} to be used in the subroutine's execution. */ public static void runGoto(int target, InterpreterState state) { MethodHandle routine = ROUTINES.get(target); if (routine == null) { throw new IllegalStateException("subroutine not implemented: goto " + target); } try { routine.invoke(state); } catch (Throwable t) { throw new IllegalStateException("error in goto " + target, t); } } /** * Run a {@code GOSUB} subroutine. * * @param target the line number for the subroutine. * @param state the {@link InterpreterState} to be used in the subroutine's execution. */ public static void runGosub(int target, InterpreterState state) { MethodHandle routine = ROUTINES.get(target); if (routine == null) { throw new IllegalStateException("subroutine not implemented: gosub " + target); } try { routine.invoke(state); state.requestReturn(); } catch (Throwable t) { throw new IllegalStateException("error in gosub " + target, t); } } /** * Random number generator used by {@link Subroutines#gosub260}. */ private static final Random RND = new Random(); /** * The subroutines for graphics output use this to paint lines and dots. Its width is chosen to arrive at a somewhat * pleasant looking line width. */ private static final Stroke STROKE = new BasicStroke(3); /** * The name of the file printer output will be written to. BASICODE supports printing on an actual printer, which * this implementation emulates by writing to a file. */ public static final String PRINTER_FILE = "BASICODE-printer.txt"; /** * Retrieve a numeric "standard" variable from the interpreter state. This is a slightly unsafe method, insofar as * it assumes that (1) the variable exists, and (2) the variable is a number. * * @param state the interpreter state to retrieve the variable from. * @param id the name of the variable. * @return the variable's numerical value. */ private static Number getStdVar(InterpreterState state, String id) { return (Number) state.getVar(id).get(); } /** * <p>Set the foreground and background colours from the {@code CC} standard array stored in the * {@linkplain InterpreterState interpreter state}. Also, return the actual painting colour as determined by * {@code CN}.</p> * * <p>The variable {@code CN} can be used to control this. If it has the value 0, the foreground colour will be used * for drawing. If it has the value 1, the background colour will be used instead. This can be used to erase * something that has been drawn.</p> * * @param state the current interpreter state, at the time of execution. * @return the actual painting colour. */ private static Color establishColours(InterpreterState state) { BasicArray1D cc = (BasicArray1D) state.getArray("CC").get(); int fg = ((Double) cc.at(0, -1)).intValue(); int bg = ((Double) cc.at(1, -1)).intValue(); state.getOutput().setColours(fg, bg); int cn = getStdVar(state, "CN").intValue(); Color c = cn == 0 ? state.getOutput().getForegroundColour() : state.getOutput().getBackgroundColour(); return c; } /** * <p>{@code GOTO 20}: initialise some default variables and jump to line 1010. This subroutine is, by convention, called at * the beginning of every BASICODE program in line 1000, and continues execution in line 1010.</p> * * <p>The subroutine initialises the following standard variables:<ul> * <li>{@code HO} and {@code VE}, to 39 and 24, respectively. These initially hold the maximum horizontal and * vertical coordinates in text mode, and are later used to control the cursor position in text mode.</li> * <li>{@code HG} and {@code VG}, to 320 and 200. These initially hold the horizontal and vertical resolution * for graphics mode.</li> * <li>{@code SV}, to 15. This is used to control the volume of audio output, and may range from 0 to 15.</li> * </ul></p> * * @param state the interpreter state. */ public static void goto20(InterpreterState state) { state.setVar("HO", 39.0); state.setVar("VE", 24.0); state.setVar("HG", 320.0); state.setVar("VG", 200.0); state.setVar("SV", 15.0); state.setLineJumpTarget(1010); state.requestLineJump(); } /** * {@code GOSUB 100}: switch to text mode, and initialise the colours to the contents of the {@code CC} array. * {@code CC(0)} will determine the foreground colour; {@code CC(1)}, the background colour. * * @param state the interpreter state. */ public static void gosub100(InterpreterState state) { establishColours(state); state.getOutput().textMode(); } /** * {@code GOSUB 110}: in text mode, position the cursor at the coordinates passed in {@code HO} and {@code VE}. * * @param state the interpreter state. */ public static void gosub110(InterpreterState state) { int ho = getStdVar(state, "HO").intValue(); int ve = getStdVar(state, "VE").intValue(); state.getOutput().setTextCursor(ho, ve); } /** * {@code GOSUB 120}: in text mode, store the current coordinates of the cursor in the {@code HO} and {@code VE} * variables. * * @param state the interpreter state. */ public static void gosub120(InterpreterState state) { TextCursor coordinates = state.getOutput().getTextCursor(); state.setVar("HO", Double.valueOf(coordinates.col())); state.setVar("VE", Double.valueOf(coordinates.row())); } /** * {@code GOSUB 150}: in text mode, print the string passed in {@code SR$} in reverse mode, with three spaces * prepended and appended to it. * * @param state the interpreter state. */ public static void gosub150(InterpreterState state) { String sr = " " + (String) state.getVar("SR$").get() + " "; state.getOutput().printReverse(sr); } /** * {@code GOSUB 200}: if, at the time of the execution of this subroutine, a key is pressed, return its character * code in the {@code IN} variable; and the corresponding character, in {@code IN$}. This subroutine is * non-blocking. * * @param state the interpreter state. */ public static void gosub200(InterpreterState state) { char input = (char) state.getInput().lastChar(); state.setVar("IN", Double.valueOf(Character.toUpperCase(input))); state.setVar("IN$", input == 0 ? "" : "" + input); } /** * {@code GOSUB 210}: wait for the next key to be pressed. The key's character code will be returned in the * {@code IN} variable; and the corresponding character, in {@code IN$}. This subroutine is blocking. * * @param state the interpreter state. */ public static void gosub210(InterpreterState state) { char input; try { input = (char) state.getInput().readChar(); } catch (IOException e) { throw new IllegalStateException(e); } state.setVar("IN$", "" + input); state.setVar("IN", Double.valueOf(Character.toUpperCase(input))); } /** * {@code GOSUB 220}: in text mode, return, in the {@code IN} variable, the code of the character currently * displayed at the horizontal and vertical position indicated by {@code HO} and {@code VE}. For an empty position * (one where no character is visible), {@code IN} will contain 32 (to represent a space character). * * @param state the interpreter state. */ public static void gosub220(InterpreterState state) { int ho = getStdVar(state, "HO").intValue(); int ve = getStdVar(state, "VE").intValue(); char c = state.getOutput().getCharAt(ho, ve); state.setVar("IN", Double.valueOf(Character.toUpperCase(c))); } /** * <p>{@code GOSUB 250}: beep. Play a 440 Hz tone for 250 ms at full volume.</p> * * <p><b>Implementation note:</b> This can be disabled by passing the {@code -nosound} command line argument, or by * using the {@link de.haupz.basicode.interpreter.Configuration#nosound nosound} interpreter configuration.</p> * * @param state the interpreter state. */ public static void gosub250(InterpreterState state) { if (state.getConfiguration().nosound()) { return; }
package de.haupz.basicode.subroutines; /** * <p>The {@code Subroutines} class holds all implementations of the BASICODE standard subroutines. Most of these are * called with {@code GOSUB} statements; some, using {@code GOTO}.</p> * * <p>Any subroutine implementation must follow a few conventions:<ul> * <li>it must be declared as {@code public static};</li> * <li>its return type must be {@code void};</li> * <li>it must accept a single argument of type {@link InterpreterState};</li> * <li>its name must begin with either {@code gosub} or {@code goto}, depending on whether it is meant to be called * by {@code GOSUB} or {@code GOTO}, respectively; and this prefix must be immediately followed by a number * representing the line number the aforementioned call or jump should be directed to.</li> * </ul></p> * * <p>During startup, as soon as the {@code Subroutines} class is initialised, all of its methods adhering to the above * convention will be automatically registered.</p> */ public class Subroutines { /** * The {@link Map} holding all subroutines. The keys are the line numbers the respective subroutines are called at. * The values are method handles representing the subroutine methods. */ private static final Map<Integer, MethodHandle> ROUTINES = new HashMap<>(); /** * The method signature for any subroutine, according to the convention described in the class comment. */ private static final MethodType ROUTINE_TYPE = MethodType.methodType(void.class, InterpreterState.class); private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup(); /** * Look up a subroutine method identified by its name, and return a method handle representing it if successful. * * @param methodName the name of the subroutine method, following the convention described in the class comment. * @return a method handle representing the subroutine method. */ private static MethodHandle lookupTarget(String methodName) { try { return LOOKUP.findStatic(Subroutines.class, methodName, ROUTINE_TYPE); } catch (Exception e) { throw new RuntimeException(e); } } /** * Register a subroutine in the {@link Subroutines#ROUTINES ROUTINES} map. The line number, used as a key in the * map, will be extracted from the method name. * * @param method a subroutine method. */ private static void registerRoutine(Method method) { String name = method.getName(); int target = Integer.parseInt(name.substring(name.startsWith("goto")?4:5)); ROUTINES.put(target, lookupTarget(name)); } /** * Register all subroutine methods in the {@code Subroutines} class. The method will find all methods adhering to * the convention described in the class comment, and register them in the {@link Subroutines#ROUTINES ROUTINES} * map. */ static void registerRoutines() { Arrays.stream(Subroutines.class.getDeclaredMethods()) .filter(m -> Modifier.isStatic(m.getModifiers())) .filter(m -> m.getName().matches("(goto|gosub)\\d+")) .forEach(Subroutines::registerRoutine); } static { registerRoutines(); } /** * Run a {@code GOTO} subroutine. * * @param target the line number for the subroutine. * @param state the {@link InterpreterState} to be used in the subroutine's execution. */ public static void runGoto(int target, InterpreterState state) { MethodHandle routine = ROUTINES.get(target); if (routine == null) { throw new IllegalStateException("subroutine not implemented: goto " + target); } try { routine.invoke(state); } catch (Throwable t) { throw new IllegalStateException("error in goto " + target, t); } } /** * Run a {@code GOSUB} subroutine. * * @param target the line number for the subroutine. * @param state the {@link InterpreterState} to be used in the subroutine's execution. */ public static void runGosub(int target, InterpreterState state) { MethodHandle routine = ROUTINES.get(target); if (routine == null) { throw new IllegalStateException("subroutine not implemented: gosub " + target); } try { routine.invoke(state); state.requestReturn(); } catch (Throwable t) { throw new IllegalStateException("error in gosub " + target, t); } } /** * Random number generator used by {@link Subroutines#gosub260}. */ private static final Random RND = new Random(); /** * The subroutines for graphics output use this to paint lines and dots. Its width is chosen to arrive at a somewhat * pleasant looking line width. */ private static final Stroke STROKE = new BasicStroke(3); /** * The name of the file printer output will be written to. BASICODE supports printing on an actual printer, which * this implementation emulates by writing to a file. */ public static final String PRINTER_FILE = "BASICODE-printer.txt"; /** * Retrieve a numeric "standard" variable from the interpreter state. This is a slightly unsafe method, insofar as * it assumes that (1) the variable exists, and (2) the variable is a number. * * @param state the interpreter state to retrieve the variable from. * @param id the name of the variable. * @return the variable's numerical value. */ private static Number getStdVar(InterpreterState state, String id) { return (Number) state.getVar(id).get(); } /** * <p>Set the foreground and background colours from the {@code CC} standard array stored in the * {@linkplain InterpreterState interpreter state}. Also, return the actual painting colour as determined by * {@code CN}.</p> * * <p>The variable {@code CN} can be used to control this. If it has the value 0, the foreground colour will be used * for drawing. If it has the value 1, the background colour will be used instead. This can be used to erase * something that has been drawn.</p> * * @param state the current interpreter state, at the time of execution. * @return the actual painting colour. */ private static Color establishColours(InterpreterState state) { BasicArray1D cc = (BasicArray1D) state.getArray("CC").get(); int fg = ((Double) cc.at(0, -1)).intValue(); int bg = ((Double) cc.at(1, -1)).intValue(); state.getOutput().setColours(fg, bg); int cn = getStdVar(state, "CN").intValue(); Color c = cn == 0 ? state.getOutput().getForegroundColour() : state.getOutput().getBackgroundColour(); return c; } /** * <p>{@code GOTO 20}: initialise some default variables and jump to line 1010. This subroutine is, by convention, called at * the beginning of every BASICODE program in line 1000, and continues execution in line 1010.</p> * * <p>The subroutine initialises the following standard variables:<ul> * <li>{@code HO} and {@code VE}, to 39 and 24, respectively. These initially hold the maximum horizontal and * vertical coordinates in text mode, and are later used to control the cursor position in text mode.</li> * <li>{@code HG} and {@code VG}, to 320 and 200. These initially hold the horizontal and vertical resolution * for graphics mode.</li> * <li>{@code SV}, to 15. This is used to control the volume of audio output, and may range from 0 to 15.</li> * </ul></p> * * @param state the interpreter state. */ public static void goto20(InterpreterState state) { state.setVar("HO", 39.0); state.setVar("VE", 24.0); state.setVar("HG", 320.0); state.setVar("VG", 200.0); state.setVar("SV", 15.0); state.setLineJumpTarget(1010); state.requestLineJump(); } /** * {@code GOSUB 100}: switch to text mode, and initialise the colours to the contents of the {@code CC} array. * {@code CC(0)} will determine the foreground colour; {@code CC(1)}, the background colour. * * @param state the interpreter state. */ public static void gosub100(InterpreterState state) { establishColours(state); state.getOutput().textMode(); } /** * {@code GOSUB 110}: in text mode, position the cursor at the coordinates passed in {@code HO} and {@code VE}. * * @param state the interpreter state. */ public static void gosub110(InterpreterState state) { int ho = getStdVar(state, "HO").intValue(); int ve = getStdVar(state, "VE").intValue(); state.getOutput().setTextCursor(ho, ve); } /** * {@code GOSUB 120}: in text mode, store the current coordinates of the cursor in the {@code HO} and {@code VE} * variables. * * @param state the interpreter state. */ public static void gosub120(InterpreterState state) { TextCursor coordinates = state.getOutput().getTextCursor(); state.setVar("HO", Double.valueOf(coordinates.col())); state.setVar("VE", Double.valueOf(coordinates.row())); } /** * {@code GOSUB 150}: in text mode, print the string passed in {@code SR$} in reverse mode, with three spaces * prepended and appended to it. * * @param state the interpreter state. */ public static void gosub150(InterpreterState state) { String sr = " " + (String) state.getVar("SR$").get() + " "; state.getOutput().printReverse(sr); } /** * {@code GOSUB 200}: if, at the time of the execution of this subroutine, a key is pressed, return its character * code in the {@code IN} variable; and the corresponding character, in {@code IN$}. This subroutine is * non-blocking. * * @param state the interpreter state. */ public static void gosub200(InterpreterState state) { char input = (char) state.getInput().lastChar(); state.setVar("IN", Double.valueOf(Character.toUpperCase(input))); state.setVar("IN$", input == 0 ? "" : "" + input); } /** * {@code GOSUB 210}: wait for the next key to be pressed. The key's character code will be returned in the * {@code IN} variable; and the corresponding character, in {@code IN$}. This subroutine is blocking. * * @param state the interpreter state. */ public static void gosub210(InterpreterState state) { char input; try { input = (char) state.getInput().readChar(); } catch (IOException e) { throw new IllegalStateException(e); } state.setVar("IN$", "" + input); state.setVar("IN", Double.valueOf(Character.toUpperCase(input))); } /** * {@code GOSUB 220}: in text mode, return, in the {@code IN} variable, the code of the character currently * displayed at the horizontal and vertical position indicated by {@code HO} and {@code VE}. For an empty position * (one where no character is visible), {@code IN} will contain 32 (to represent a space character). * * @param state the interpreter state. */ public static void gosub220(InterpreterState state) { int ho = getStdVar(state, "HO").intValue(); int ve = getStdVar(state, "VE").intValue(); char c = state.getOutput().getCharAt(ho, ve); state.setVar("IN", Double.valueOf(Character.toUpperCase(c))); } /** * <p>{@code GOSUB 250}: beep. Play a 440 Hz tone for 250 ms at full volume.</p> * * <p><b>Implementation note:</b> This can be disabled by passing the {@code -nosound} command line argument, or by * using the {@link de.haupz.basicode.interpreter.Configuration#nosound nosound} interpreter configuration.</p> * * @param state the interpreter state. */ public static void gosub250(InterpreterState state) { if (state.getConfiguration().nosound()) { return; }
Sound.play(440, 250, 100);
2
2023-10-14 12:20:59+00:00
12k
giteecode/bookmanage2-public
nhXJH-admin/src/main/java/com/nhXJH/web/controller/system/SysLoginController.java
[ { "identifier": "Constants", "path": "nhXJH-common/src/main/java/com/nhXJH/common/constant/Constants.java", "snippet": "public class Constants {\n /**\n * UTF-8 字符集\n */\n public static final String UTF8 = \"UTF-8\";\n\n /**\n * GBK 字符集\n */\n public static final String GBK =...
import java.util.List; import java.util.Set; import net.bytebuddy.implementation.bind.annotation.Origin; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import com.nhXJH.common.constant.Constants; import com.nhXJH.common.core.domain.AjaxResult; import com.nhXJH.common.core.domain.entity.SysMenu; import com.nhXJH.common.core.domain.entity.SysUser; import com.nhXJH.common.core.domain.model.LoginBody; import com.nhXJH.common.utils.SecurityUtils; import com.nhXJH.framework.web.service.SysLoginService; import com.nhXJH.framework.web.service.SysPermissionService; import com.nhXJH.system.service.ISysMenuService;
8,796
package com.nhXJH.web.controller.system; /** * 登录验证 * * @author nhXJH */ @RestController public class SysLoginController { @Autowired private SysLoginService loginService; @Autowired private ISysMenuService menuService; @Autowired private SysPermissionService permissionService; /** * 登录方法 * * @param loginBody 登录信息 * @return 结果 */ @PostMapping("/login") @CrossOrigin public AjaxResult login(@RequestBody LoginBody loginBody) { AjaxResult ajax = AjaxResult.success(); // 生成令牌 String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(), loginBody.getUuid()); ajax.put(Constants.TOKEN, token); return ajax; } /** * 获取用户信息 * * @return 用户信息 */ @GetMapping("/getInfo") @CrossOrigin public AjaxResult getInfo() {
package com.nhXJH.web.controller.system; /** * 登录验证 * * @author nhXJH */ @RestController public class SysLoginController { @Autowired private SysLoginService loginService; @Autowired private ISysMenuService menuService; @Autowired private SysPermissionService permissionService; /** * 登录方法 * * @param loginBody 登录信息 * @return 结果 */ @PostMapping("/login") @CrossOrigin public AjaxResult login(@RequestBody LoginBody loginBody) { AjaxResult ajax = AjaxResult.success(); // 生成令牌 String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(), loginBody.getUuid()); ajax.put(Constants.TOKEN, token); return ajax; } /** * 获取用户信息 * * @return 用户信息 */ @GetMapping("/getInfo") @CrossOrigin public AjaxResult getInfo() {
SysUser user = SecurityUtils.getLoginUser().getUser();
5
2023-10-13 07:19:20+00:00
12k
M-D-Team/ait-fabric-1.20.1
src/main/java/mdteam/ait/tardis/util/desktop/structures/DesktopGenerator.java
[ { "identifier": "AITMod", "path": "src/main/java/mdteam/ait/AITMod.java", "snippet": "public class AITMod implements ModInitializer {\n public static final String MOD_ID = \"ait\";\n public static final Logger LOGGER = LoggerFactory.getLogger(\"ait\");\n public static final Boolean DEBUG = true...
import mdteam.ait.AITMod; import mdteam.ait.core.AITBlocks; import mdteam.ait.tardis.util.TardisUtil; import mdteam.ait.tardis.util.Corners; import net.minecraft.block.Block; import net.minecraft.block.Blocks; import net.minecraft.entity.EntityType; import net.minecraft.entity.ItemEntity; import net.minecraft.predicate.entity.EntityPredicates; import net.minecraft.server.world.ServerWorld; import net.minecraft.structure.StructurePlacementData; import net.minecraft.structure.StructureTemplate; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; import mdteam.ait.tardis.TardisDesktopSchema; import java.util.Optional;
8,046
package mdteam.ait.tardis.util.desktop.structures; public class DesktopGenerator { private final TardisDesktopSchema schema; public DesktopGenerator(TardisDesktopSchema schema) { this.schema = schema; }
package mdteam.ait.tardis.util.desktop.structures; public class DesktopGenerator { private final TardisDesktopSchema schema; public DesktopGenerator(TardisDesktopSchema schema) { this.schema = schema; }
public BlockPos place(ServerWorld level, Corners corners) {
3
2023-10-08 00:38:53+00:00
12k
jianjian3219/044_bookmanage2-public
nhXJH-generator/src/main/java/com/nhXJH/generator/service/GenTableColumnServiceImpl.java
[ { "identifier": "Convert", "path": "nhXJH-common/src/main/java/com/nhXJH/common/core/text/Convert.java", "snippet": "public class Convert {\n /**\n * 转换为字符串<br>\n * 如果给定的值为null,或者转换失败,返回默认值<br>\n * 转换失败不会报错\n *\n * @param value 被转换的值\n * @param defaultValue 转换错误时的默认值\n * @...
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.nhXJH.common.core.text.Convert; import com.nhXJH.generator.domain.GenTableColumn; import com.nhXJH.generator.mapper.GenTableColumnMapper;
9,654
package com.nhXJH.generator.service; /** * 业务字段 服务层实现 * * @author nhXJH */ @Service public class GenTableColumnServiceImpl implements IGenTableColumnService { @Autowired
package com.nhXJH.generator.service; /** * 业务字段 服务层实现 * * @author nhXJH */ @Service public class GenTableColumnServiceImpl implements IGenTableColumnService { @Autowired
private GenTableColumnMapper genTableColumnMapper;
2
2023-10-14 04:57:42+00:00
12k
aleksandarsusnjar/paniql
print/src/main/java/net/susnjar/paniql/print/InvoicePrinter.java
[ { "identifier": "ElementModel", "path": "core/src/main/java/net/susnjar/paniql/models/ElementModel.java", "snippet": "public abstract class ElementModel<D extends DirectivesContainer<D>> {\n public static final double LOG_BASE_0_95 = Math.log(0.95d);\n public static final double LOG_BASE_1_9 = Mat...
import net.susnjar.paniql.models.ElementModel; import net.susnjar.paniql.pricing.Bounds; import net.susnjar.paniql.pricing.Invoice; import net.susnjar.paniql.pricing.Price; import net.susnjar.paniql.pricing.WorkType; import java.io.PrintStream; import java.math.RoundingMode; import java.text.NumberFormat; import java.util.Locale; import java.util.Map; import java.util.TreeMap; import java.util.function.Function;
7,449
package net.susnjar.paniql.print; public class InvoicePrinter { private int nameWidth = 10; private int columnWidth = 14; private int lineWidth; private String doubleHorizontalRule; private String singleHorizontalRule; public InvoicePrinter() { recalculate(); } public void setNameWidth(final int width) { nameWidth = width; recalculate(); } public void setValueColumnWidth(final int width) { columnWidth = width; recalculate(); } private void recalculate() { lineWidth = nameWidth + 1 + 3 + WorkType.values().length * columnWidth; doubleHorizontalRule = "=".repeat(lineWidth); singleHorizontalRule = "-".repeat(lineWidth); } public void println(final Invoice invoice) { println(invoice, System.out); } public void println(final Invoice invoice, final PrintStream out) {
package net.susnjar.paniql.print; public class InvoicePrinter { private int nameWidth = 10; private int columnWidth = 14; private int lineWidth; private String doubleHorizontalRule; private String singleHorizontalRule; public InvoicePrinter() { recalculate(); } public void setNameWidth(final int width) { nameWidth = width; recalculate(); } public void setValueColumnWidth(final int width) { columnWidth = width; recalculate(); } private void recalculate() { lineWidth = nameWidth + 1 + 3 + WorkType.values().length * columnWidth; doubleHorizontalRule = "=".repeat(lineWidth); singleHorizontalRule = "-".repeat(lineWidth); } public void println(final Invoice invoice) { println(invoice, System.out); } public void println(final Invoice invoice, final PrintStream out) {
Price total = Price.FREE;
3
2023-10-10 01:58:56+00:00
12k
quan100/quan
quan-app/quan-app-core/src/main/java/cn/javaquan/app/core/system/repository/impl/SysPermissionRepositoryImpl.java
[ { "identifier": "PageAssembler", "path": "quan-app/quan-app-core/src/main/java/cn/javaquan/app/core/convert/PageAssembler.java", "snippet": "@Mapper\npublic interface PageAssembler {\n\n PageAssembler INSTANCE = Mappers.getMapper(PageAssembler.class);\n\n @Mapping(target = \"records\", ignore = tr...
import cn.javaquan.app.core.convert.PageAssembler; import cn.javaquan.app.core.convert.PageResultAssembler; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import cn.javaquan.app.common.module.system.SubsetPermissionsQuery; import cn.javaquan.app.common.module.system.SysPermissionTreeDTO; import cn.javaquan.app.common.module.system.SysRolePermissionQuery; import cn.javaquan.app.common.util.Validate; import cn.javaquan.common.base.constant.CommonConstant; import cn.javaquan.common.base.message.BasePage; import cn.javaquan.common.base.message.PageResult; import cn.javaquan.app.core.system.convert.SysPermissionAssembler; import cn.javaquan.app.core.system.entity.SysPermissionPO; import cn.javaquan.app.core.system.mapper.SysPermissionMapper; import cn.javaquan.app.core.system.repository.SysPermissionRepository; import cn.javaquan.app.core.system.repository.SysRolePermissionRepository; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Repository; import java.util.Collections; import java.util.List;
7,912
package cn.javaquan.app.core.system.repository.impl; /** * 系统资源权限配置 * * @author wangquan * @since 2020-12-27 17:50:38 */ @RequiredArgsConstructor @Repository
package cn.javaquan.app.core.system.repository.impl; /** * 系统资源权限配置 * * @author wangquan * @since 2020-12-27 17:50:38 */ @RequiredArgsConstructor @Repository
public class SysPermissionRepositoryImpl extends ServiceImpl<SysPermissionMapper, SysPermissionPO> implements SysPermissionRepository {
10
2023-10-08 06:48:41+00:00
12k
Ghost-chu/DoDoSRV
src/main/java/com/ghostchu/plugins/dodosrv/DoDoSRV.java
[ { "identifier": "CommandManager", "path": "src/main/java/com/ghostchu/plugins/dodosrv/command/bukkit/CommandManager.java", "snippet": "public interface CommandManager{\n /**\n * This is a interface to allow addons to register the subcommand into quickshop command manager.\n *\n * @param c...
import com.ghostchu.plugins.dodosrv.command.bukkit.CommandManager; import com.ghostchu.plugins.dodosrv.command.bukkit.SimpleCommandManager; import com.ghostchu.plugins.dodosrv.database.DatabaseManager; import com.ghostchu.plugins.dodosrv.dodo.DodoManager; import com.ghostchu.plugins.dodosrv.dodo.UserBindManager; import com.ghostchu.plugins.dodosrv.listener.bukkit.BukkitListener; import com.ghostchu.plugins.dodosrv.listener.dodo.DoDoListener; import com.ghostchu.plugins.dodosrv.text.TextManager; import com.ghostchu.plugins.dodosrv.util.JsonUtil; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.gson.JsonObject; import net.deechael.dodo.API; import net.deechael.dodo.api.Channel; import net.deechael.dodo.api.TextChannel; import net.deechael.dodo.content.Message; import net.deechael.dodo.content.TextMessage; import net.deechael.dodo.gate.Gateway; import net.deechael.dodo.impl.ChannelImpl; import net.deechael.dodo.impl.DodoBot; import net.deechael.dodo.network.Route; import net.deechael.dodo.types.MessageType; import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; import java.io.File; import java.lang.reflect.Field; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit;
10,039
package com.ghostchu.plugins.dodosrv; public final class DoDoSRV extends JavaPlugin { private DodoBot bot; private DatabaseManager databaseManager; private UserBindManager userBindManager;
package com.ghostchu.plugins.dodosrv; public final class DoDoSRV extends JavaPlugin { private DodoBot bot; private DatabaseManager databaseManager; private UserBindManager userBindManager;
private TextManager textManager;
7
2023-10-11 16:16:54+00:00
12k
qmjy/mapbox-offline-server
src/main/java/io/github/qmjy/mapbox/controller/MapServerTilesetsRestController.java
[ { "identifier": "MapServerDataCenter", "path": "src/main/java/io/github/qmjy/mapbox/MapServerDataCenter.java", "snippet": "@Component\npublic class MapServerDataCenter {\n private static final Logger logger = LoggerFactory.getLogger(MapServerDataCenter.class);\n\n /**\n * 瓦片数据库文件模型\n */\n ...
import io.github.qmjy.mapbox.MapServerDataCenter; import io.github.qmjy.mapbox.config.AppConfig; import io.github.qmjy.mapbox.model.MbtilesOfMerge; import io.github.qmjy.mapbox.model.MbtilesOfMergeProgress; import io.github.qmjy.mapbox.model.MetaData; import io.github.qmjy.mapbox.service.AsyncService; import io.github.qmjy.mapbox.util.ResponseMapUtil; 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.tags.Tag; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ByteArrayResource; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.*; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.*;
7,772
/* * Copyright (c) 2023 QMJY. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.qmjy.mapbox.controller; /** * Mbtiles支持的数据库访问API。<br> * MBTiles 1.3 规范定义:<a href="https://github.com/mapbox/mbtiles-spec/blob/master/1.3/spec.md">MBTiles 1.3</a> * * @author liushaofeng */ @RestController @RequestMapping("/api/tilesets") @Tag(name = "地图瓦片服务管理", description = "Mapbox离线服务接口能力") public class MapServerTilesetsRestController { @Autowired private AsyncService asyncService; @Autowired private MapServerDataCenter mapServerDataCenter; @Autowired private AppConfig appConfig; /** * 加载图片瓦片数据 * * @param tileset 瓦片数据库名称 * @param z 地图缩放层级 * @param x 地图的x轴瓦片坐标 * @param y 地图的y轴瓦片坐标 * @return jpg格式的瓦片数据 */ @GetMapping(value = "/{tileset}/{z}/{x}/{y}.jpg", produces = MediaType.IMAGE_JPEG_VALUE) @ResponseBody @Operation(summary = "获取JPG格式瓦片数据", description = "获取JPG格式瓦片数据。") public ResponseEntity<ByteArrayResource> loadJpgTile(@PathVariable("tileset") String tileset, @PathVariable("z") String z, @PathVariable("x") String x, @PathVariable("y") String y) { return getByteArrayResourceResponseEntity(tileset, z, x, y, MediaType.IMAGE_JPEG); } /** * 加载图片瓦片数据 * * @param tileset 瓦片数据库名称 * @param z 地图缩放层级 * @param x 地图的x轴瓦片坐标 * @param y 地图的y轴瓦片坐标 * @return png格式的瓦片数据 */ @GetMapping(value = "/{tileset}/{z}/{x}/{y}.png", produces = MediaType.IMAGE_PNG_VALUE) @ResponseBody @Operation(summary = "获取PNG格式瓦片数据", description = "获取PNG格式瓦片数据。") public ResponseEntity<ByteArrayResource> loadPngTile(@PathVariable("tileset") String tileset, @PathVariable("z") String z, @PathVariable("x") String x, @PathVariable("y") String y) { return getByteArrayResourceResponseEntity(tileset, z, x, y, MediaType.IMAGE_PNG); } /** * 加载pbf格式的瓦片数据 * * @param tileset 瓦片数据库名称 * @param z 地图缩放层级 * @param x 地图的x轴瓦片坐标 * @param y 地图的y轴瓦片坐标 * @return pbf格式的瓦片数据 */ @GetMapping(value = "/{tileset}/{z}/{x}/{y}.pbf", produces = "application/x-protobuf") @ResponseBody @Operation(summary = "获取PBF格式瓦片数据", description = "获取PBF格式瓦片数据。") public ResponseEntity<ByteArrayResource> loadPbfTile(@PathVariable("tileset") String tileset, @PathVariable("z") String z, @PathVariable("x") String x, @PathVariable("y") String y) { if (tileset.endsWith(AppConfig.FILE_EXTENSION_NAME_MBTILES)) { return getArrayResourceResponseEntity(tileset, z, x, y, AppConfig.APPLICATION_X_PROTOBUF_VALUE); } else { String sb = appConfig.getDataPath() + File.separator + "tilesets" + File.separator + tileset + File.separator + z + File.separator + x + File.separator + y + AppConfig.FILE_EXTENSION_NAME_PBF; File pbfFile = new File(sb); if (pbfFile.exists()) { try { byte[] buffer = FileCopyUtils.copyToByteArray(pbfFile); IOUtils.readFully(Files.newInputStream(pbfFile.toPath()), buffer); HttpHeaders headers = new HttpHeaders(); headers.setContentType(AppConfig.APPLICATION_X_PROTOBUF_VALUE); ByteArrayResource resource = new ByteArrayResource(buffer); return ResponseEntity.ok().headers(headers).contentLength(buffer.length).body(resource); } catch (IOException e) { throw new RuntimeException(e); } } return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } /** * 获取指定底图数据的元数据 * * @param tileset 底图数据文件名称 * @return 元数据 */ @GetMapping(value = "/{tileset}/metadata", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody @Operation(summary = "获取底图数据的元数据", description = "获取底图数据的元数据。") public ResponseEntity<Map<String, Object>> metadata(@Parameter(description = "待查询的底图文件或文件夹名字,例如:admin.mbtiles。") @PathVariable("tileset") String tileset) { if (tileset.endsWith(AppConfig.FILE_EXTENSION_NAME_MBTILES)) { Optional<JdbcTemplate> jdbcTemplateOpt = mapServerDataCenter.getDataSource(tileset); if (jdbcTemplateOpt.isPresent()) { JdbcTemplate jdbcTemplate = jdbcTemplateOpt.get(); String sql = "SELECT * FROM metadata"; try { List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
/* * Copyright (c) 2023 QMJY. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.qmjy.mapbox.controller; /** * Mbtiles支持的数据库访问API。<br> * MBTiles 1.3 规范定义:<a href="https://github.com/mapbox/mbtiles-spec/blob/master/1.3/spec.md">MBTiles 1.3</a> * * @author liushaofeng */ @RestController @RequestMapping("/api/tilesets") @Tag(name = "地图瓦片服务管理", description = "Mapbox离线服务接口能力") public class MapServerTilesetsRestController { @Autowired private AsyncService asyncService; @Autowired private MapServerDataCenter mapServerDataCenter; @Autowired private AppConfig appConfig; /** * 加载图片瓦片数据 * * @param tileset 瓦片数据库名称 * @param z 地图缩放层级 * @param x 地图的x轴瓦片坐标 * @param y 地图的y轴瓦片坐标 * @return jpg格式的瓦片数据 */ @GetMapping(value = "/{tileset}/{z}/{x}/{y}.jpg", produces = MediaType.IMAGE_JPEG_VALUE) @ResponseBody @Operation(summary = "获取JPG格式瓦片数据", description = "获取JPG格式瓦片数据。") public ResponseEntity<ByteArrayResource> loadJpgTile(@PathVariable("tileset") String tileset, @PathVariable("z") String z, @PathVariable("x") String x, @PathVariable("y") String y) { return getByteArrayResourceResponseEntity(tileset, z, x, y, MediaType.IMAGE_JPEG); } /** * 加载图片瓦片数据 * * @param tileset 瓦片数据库名称 * @param z 地图缩放层级 * @param x 地图的x轴瓦片坐标 * @param y 地图的y轴瓦片坐标 * @return png格式的瓦片数据 */ @GetMapping(value = "/{tileset}/{z}/{x}/{y}.png", produces = MediaType.IMAGE_PNG_VALUE) @ResponseBody @Operation(summary = "获取PNG格式瓦片数据", description = "获取PNG格式瓦片数据。") public ResponseEntity<ByteArrayResource> loadPngTile(@PathVariable("tileset") String tileset, @PathVariable("z") String z, @PathVariable("x") String x, @PathVariable("y") String y) { return getByteArrayResourceResponseEntity(tileset, z, x, y, MediaType.IMAGE_PNG); } /** * 加载pbf格式的瓦片数据 * * @param tileset 瓦片数据库名称 * @param z 地图缩放层级 * @param x 地图的x轴瓦片坐标 * @param y 地图的y轴瓦片坐标 * @return pbf格式的瓦片数据 */ @GetMapping(value = "/{tileset}/{z}/{x}/{y}.pbf", produces = "application/x-protobuf") @ResponseBody @Operation(summary = "获取PBF格式瓦片数据", description = "获取PBF格式瓦片数据。") public ResponseEntity<ByteArrayResource> loadPbfTile(@PathVariable("tileset") String tileset, @PathVariable("z") String z, @PathVariable("x") String x, @PathVariable("y") String y) { if (tileset.endsWith(AppConfig.FILE_EXTENSION_NAME_MBTILES)) { return getArrayResourceResponseEntity(tileset, z, x, y, AppConfig.APPLICATION_X_PROTOBUF_VALUE); } else { String sb = appConfig.getDataPath() + File.separator + "tilesets" + File.separator + tileset + File.separator + z + File.separator + x + File.separator + y + AppConfig.FILE_EXTENSION_NAME_PBF; File pbfFile = new File(sb); if (pbfFile.exists()) { try { byte[] buffer = FileCopyUtils.copyToByteArray(pbfFile); IOUtils.readFully(Files.newInputStream(pbfFile.toPath()), buffer); HttpHeaders headers = new HttpHeaders(); headers.setContentType(AppConfig.APPLICATION_X_PROTOBUF_VALUE); ByteArrayResource resource = new ByteArrayResource(buffer); return ResponseEntity.ok().headers(headers).contentLength(buffer.length).body(resource); } catch (IOException e) { throw new RuntimeException(e); } } return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } /** * 获取指定底图数据的元数据 * * @param tileset 底图数据文件名称 * @return 元数据 */ @GetMapping(value = "/{tileset}/metadata", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody @Operation(summary = "获取底图数据的元数据", description = "获取底图数据的元数据。") public ResponseEntity<Map<String, Object>> metadata(@Parameter(description = "待查询的底图文件或文件夹名字,例如:admin.mbtiles。") @PathVariable("tileset") String tileset) { if (tileset.endsWith(AppConfig.FILE_EXTENSION_NAME_MBTILES)) { Optional<JdbcTemplate> jdbcTemplateOpt = mapServerDataCenter.getDataSource(tileset); if (jdbcTemplateOpt.isPresent()) { JdbcTemplate jdbcTemplate = jdbcTemplateOpt.get(); String sql = "SELECT * FROM metadata"; try { List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
return ResponseEntity.ok().body(ResponseMapUtil.ok(wrapMap(maps)));
6
2023-10-09 03:18:52+00:00
12k
codegrits/CodeGRITS
src/main/java/api/RealtimeDataImpl.java
[ { "identifier": "EyeTracker", "path": "src/main/java/trackers/EyeTracker.java", "snippet": "public class EyeTracker implements Disposable {\n String dataOutputPath = \"\";\n /**\n * This variable indicates the sample frequency of the eye tracker.\n */\n double sampleFrequency;\n PsiD...
import com.intellij.openapi.project.Project; import trackers.EyeTracker; import trackers.IDETracker; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.Socket; import java.util.function.Consumer;
9,477
package api; /** * This class provides the API for getting real-time data from the IDE and eye tracker. */ public class RealtimeDataImpl { // make it singleton private static RealtimeDataImpl realtimeData = new RealtimeDataImpl(); Socket socket; InputStream dataInputStream; private Consumer<String> ideTrackerDataHandler; private Consumer<String> eyeTrackerDataHandler;
package api; /** * This class provides the API for getting real-time data from the IDE and eye tracker. */ public class RealtimeDataImpl { // make it singleton private static RealtimeDataImpl realtimeData = new RealtimeDataImpl(); Socket socket; InputStream dataInputStream; private Consumer<String> ideTrackerDataHandler; private Consumer<String> eyeTrackerDataHandler;
private static IDETracker ideTracker;
1
2023-10-12 15:40:39+00:00
12k
Stachelbeere1248/zombies-utils
src/main/java/com/github/stachelbeere1248/zombiesutils/handlers/RenderGameOverlayHandler.java
[ { "identifier": "ZombiesUtilsConfig", "path": "src/main/java/com/github/stachelbeere1248/zombiesutils/config/ZombiesUtilsConfig.java", "snippet": "public class ZombiesUtilsConfig {\n public static Configuration config;\n private static Property slaToggle;\n private static Property slaShortener;...
import com.github.stachelbeere1248.zombiesutils.config.ZombiesUtilsConfig; import com.github.stachelbeere1248.zombiesutils.game.sla.SLA; import com.github.stachelbeere1248.zombiesutils.game.waves.Waves; import com.github.stachelbeere1248.zombiesutils.game.windows.Room; import com.github.stachelbeere1248.zombiesutils.timer.Timer; import com.github.stachelbeere1248.zombiesutils.utils.Scoreboard; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.ScaledResolution; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import org.jetbrains.annotations.NotNull; import java.util.Objects;
9,380
package com.github.stachelbeere1248.zombiesutils.handlers; public class RenderGameOverlayHandler { private static int rl = 0; private final FontRenderer fontRenderer; public RenderGameOverlayHandler() { this.fontRenderer = Objects.requireNonNull(Minecraft.getMinecraft().fontRendererObj, "FontRenderer must not be null!"); } private static String getTimeString(long timerTicks) { final long minutesPart = (timerTicks * 50) / 60000; final long secondsPart = ((timerTicks * 50) % 60000) / 1000; final long tenthSecondsPart = ((timerTicks * 50) % 1000) / 100; return String.format("%d:%02d.%d", minutesPart, secondsPart, tenthSecondsPart); } private static String getWaveString(long waveTicks, int wave) { final long minutesPart = (waveTicks * 50) / 60000; final long secondsPart = ((waveTicks * 50) % 60000) / 1000; final long tenthSecondsPart = ((waveTicks * 50) % 1000) / 100; return String.format("W%d %d:%02d.%d", wave, minutesPart, secondsPart, tenthSecondsPart); } static void toggleRL() { if (rl == 0) rl = ZombiesUtilsConfig.getWaveOffset(); else rl = 0; } @SubscribeEvent public void onRenderGameOverlay(RenderGameOverlayEvent.@NotNull Post event) { if (event.type != RenderGameOverlayEvent.ElementType.TEXT) return; Timer.getInstance().ifPresent(timer -> { renderTime(timer.roundTime()); renderSpawnTime( Waves.get( timer.getGameMode().getMap(), timer.getRound() ), timer.roundTime() ); }); SLA.getInstance().ifPresent(sla -> { sla.refreshActives(); renderSla(sla.getRooms()); }); } private void renderTime(long timerTicks) {
package com.github.stachelbeere1248.zombiesutils.handlers; public class RenderGameOverlayHandler { private static int rl = 0; private final FontRenderer fontRenderer; public RenderGameOverlayHandler() { this.fontRenderer = Objects.requireNonNull(Minecraft.getMinecraft().fontRendererObj, "FontRenderer must not be null!"); } private static String getTimeString(long timerTicks) { final long minutesPart = (timerTicks * 50) / 60000; final long secondsPart = ((timerTicks * 50) % 60000) / 1000; final long tenthSecondsPart = ((timerTicks * 50) % 1000) / 100; return String.format("%d:%02d.%d", minutesPart, secondsPart, tenthSecondsPart); } private static String getWaveString(long waveTicks, int wave) { final long minutesPart = (waveTicks * 50) / 60000; final long secondsPart = ((waveTicks * 50) % 60000) / 1000; final long tenthSecondsPart = ((waveTicks * 50) % 1000) / 100; return String.format("W%d %d:%02d.%d", wave, minutesPart, secondsPart, tenthSecondsPart); } static void toggleRL() { if (rl == 0) rl = ZombiesUtilsConfig.getWaveOffset(); else rl = 0; } @SubscribeEvent public void onRenderGameOverlay(RenderGameOverlayEvent.@NotNull Post event) { if (event.type != RenderGameOverlayEvent.ElementType.TEXT) return; Timer.getInstance().ifPresent(timer -> { renderTime(timer.roundTime()); renderSpawnTime( Waves.get( timer.getGameMode().getMap(), timer.getRound() ), timer.roundTime() ); }); SLA.getInstance().ifPresent(sla -> { sla.refreshActives(); renderSla(sla.getRooms()); }); } private void renderTime(long timerTicks) {
if (Scoreboard.isNotZombies()) return;
5
2023-10-11 01:30:28+00:00
12k
giteecode/supermarket2Public
src/main/java/com/ruoyi/common/utils/file/FileUtils.java
[ { "identifier": "DateUtils", "path": "src/main/java/com/ruoyi/common/utils/DateUtils.java", "snippet": "public class DateUtils extends org.apache.commons.lang3.time.DateUtils\n{\n public static String YYYY = \"yyyy\";\n\n public static String YYYY_MM = \"yyyy-MM\";\n\n public static String YYYY...
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.ArrayUtils; import com.ruoyi.common.utils.DateUtils; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.uuid.IdUtils; import com.ruoyi.framework.config.RuoYiConfig;
7,405
package com.ruoyi.common.utils.file; /** * 文件处理工具类 * * @author ruoyi */ public class FileUtils { public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+"; /** * 输出指定文件的byte数组 * * @param filePath 文件路径 * @param os 输出流 * @return */ public static void writeBytes(String filePath, OutputStream os) throws IOException { FileInputStream fis = null; try { File file = new File(filePath); if (!file.exists()) { throw new FileNotFoundException(filePath); } fis = new FileInputStream(file); byte[] b = new byte[1024]; int length; while ((length = fis.read(b)) > 0) { os.write(b, 0, length); } } catch (IOException e) { throw e; } finally { IOUtils.close(os); IOUtils.close(fis); } } /** * 写数据到文件中 * * @param data 数据 * @return 目标文件 * @throws IOException IO异常 */ public static String writeImportBytes(byte[] data) throws IOException { return writeBytes(data, RuoYiConfig.getImportPath()); } /** * 写数据到文件中 * * @param data 数据 * @param uploadDir 目标文件 * @return 目标文件 * @throws IOException IO异常 */ public static String writeBytes(byte[] data, String uploadDir) throws IOException { FileOutputStream fos = null; String pathName = ""; try { String extension = getFileExtendName(data); pathName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension; File file = FileUploadUtils.getAbsoluteFile(uploadDir, pathName); fos = new FileOutputStream(file); fos.write(data); } finally { IOUtils.close(fos); } return FileUploadUtils.getPathFileName(uploadDir, pathName); } /** * 删除文件 * * @param filePath 文件 * @return */ public static boolean deleteFile(String filePath) { boolean flag = false; File file = new File(filePath); // 路径为文件且不为空则进行删除 if (file.isFile() && file.exists()) { file.delete(); flag = true; } return flag; } /** * 文件名称验证 * * @param filename 文件名称 * @return true 正常 false 非法 */ public static boolean isValidFilename(String filename) { return filename.matches(FILENAME_PATTERN); } /** * 检查文件是否可下载 * * @param resource 需要下载的文件 * @return true 正常 false 非法 */ public static boolean checkAllowDownload(String resource) { // 禁止目录上跳级别
package com.ruoyi.common.utils.file; /** * 文件处理工具类 * * @author ruoyi */ public class FileUtils { public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+"; /** * 输出指定文件的byte数组 * * @param filePath 文件路径 * @param os 输出流 * @return */ public static void writeBytes(String filePath, OutputStream os) throws IOException { FileInputStream fis = null; try { File file = new File(filePath); if (!file.exists()) { throw new FileNotFoundException(filePath); } fis = new FileInputStream(file); byte[] b = new byte[1024]; int length; while ((length = fis.read(b)) > 0) { os.write(b, 0, length); } } catch (IOException e) { throw e; } finally { IOUtils.close(os); IOUtils.close(fis); } } /** * 写数据到文件中 * * @param data 数据 * @return 目标文件 * @throws IOException IO异常 */ public static String writeImportBytes(byte[] data) throws IOException { return writeBytes(data, RuoYiConfig.getImportPath()); } /** * 写数据到文件中 * * @param data 数据 * @param uploadDir 目标文件 * @return 目标文件 * @throws IOException IO异常 */ public static String writeBytes(byte[] data, String uploadDir) throws IOException { FileOutputStream fos = null; String pathName = ""; try { String extension = getFileExtendName(data); pathName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension; File file = FileUploadUtils.getAbsoluteFile(uploadDir, pathName); fos = new FileOutputStream(file); fos.write(data); } finally { IOUtils.close(fos); } return FileUploadUtils.getPathFileName(uploadDir, pathName); } /** * 删除文件 * * @param filePath 文件 * @return */ public static boolean deleteFile(String filePath) { boolean flag = false; File file = new File(filePath); // 路径为文件且不为空则进行删除 if (file.isFile() && file.exists()) { file.delete(); flag = true; } return flag; } /** * 文件名称验证 * * @param filename 文件名称 * @return true 正常 false 非法 */ public static boolean isValidFilename(String filename) { return filename.matches(FILENAME_PATTERN); } /** * 检查文件是否可下载 * * @param resource 需要下载的文件 * @return true 正常 false 非法 */ public static boolean checkAllowDownload(String resource) { // 禁止目录上跳级别
if (StringUtils.contains(resource, ".."))
1
2023-10-14 02:27:47+00:00
12k
davidsaltacc/shadowclient
src/main/java/net/shadowclient/main/ui/clickgui/ModuleButton.java
[ { "identifier": "SCMain", "path": "src/main/java/net/shadowclient/main/SCMain.java", "snippet": "public class SCMain {\n\n public static final String ClientModId = \"shadowclient\";\n public static final String ClientName = \"ShadowClient\";\n public static final String ClientVersion = \"0.2.0\...
import net.minecraft.client.gui.DrawContext; import net.shadowclient.main.SCMain; import net.shadowclient.main.annotations.Hidden; import net.shadowclient.main.annotations.SearchTags; import net.shadowclient.main.module.Module; import net.shadowclient.main.module.ModuleManager; import net.shadowclient.main.setting.Setting; import net.shadowclient.main.setting.settings.BooleanSetting; import net.shadowclient.main.setting.settings.EnumSetting; import net.shadowclient.main.setting.settings.NumberSetting; import net.shadowclient.main.setting.settings.StringSetting; import net.shadowclient.main.ui.clickgui.settings.clickgui.SettingComponent; import net.shadowclient.main.ui.clickgui.settings.clickgui.components.BoolSetting; import net.shadowclient.main.ui.clickgui.settings.clickgui.components.ModeSetting; import net.shadowclient.main.ui.clickgui.settings.clickgui.components.SliderSetting; import net.shadowclient.main.ui.clickgui.settings.clickgui.components.TextSetting; import org.lwjgl.glfw.GLFW; import java.util.ArrayList; import java.util.List;
9,331
package net.shadowclient.main.ui.clickgui; public class ModuleButton extends FrameChild { public final Module module; public final Frame parent; public int offset; public boolean extended; public final List<SettingComponent> components; public ModuleButton(String modulename, Frame parent, int offset) { this.module = ModuleManager.getModule(modulename); this.parent = parent; this.offset = offset; this.components = new ArrayList<>(); this.extended = false; int settingOffset = parent.height; for (Setting setting : module.getSettings()) { if (setting.getClass().isAnnotationPresent(Hidden.class)) { continue; } if (setting instanceof BooleanSetting) { components.add(new BoolSetting(setting, this, settingOffset)); } else if (setting instanceof EnumSetting<?>) { components.add(new ModeSetting(setting, this, settingOffset)); } else if (setting instanceof NumberSetting) { components.add(new SliderSetting(setting, this, settingOffset)); } else if (setting instanceof StringSetting) { components.add(new TextSetting(setting, this, settingOffset)); } settingOffset += parent.height; } } public void render(DrawContext context, int mouseX, int mouseY, float delta) { boolean hovered = isHovered(mouseX, mouseY); int color = Colors.MODULE_BUTTON_NORMAL.color; if (hovered) { color = Colors.MODULE_BUTTON_HOVERED.color; } context.fill(parent.x, parent.y + offset, parent.x + parent.width, parent.y + offset + parent.height, color); int textOffset = (parent.height / 2 - parent.mc.textRenderer.fontHeight / 2); context.drawTextWithShadow(parent.mc.textRenderer, module.friendlyName, parent.x + textOffset, parent.y + offset + textOffset, getTextColor()); if (extended) { for (SettingComponent component : components) { component.render(context, mouseX, mouseY, delta); } } } public void renderDescription(DrawContext context, int mouseX, int mouseY) { int color = Colors.MODULE_BUTTON_NORMAL.color; int width = parent.mc.textRenderer.getWidth(module.description); int textOffset = (parent.height / 2 - parent.mc.textRenderer.fontHeight / 2); context.fill(parent.x + parent.width, parent.y + offset, parent.x + parent.width + width + textOffset * 2, parent.y + offset + parent.height, color); context.drawTextWithShadow(parent.mc.textRenderer, module.description, parent.x + parent.width + textOffset, parent.y + offset + textOffset, Colors.TEXT_NORMAL.color); } public void mouseClicked(double mouseX, double mouseY, int button) { if (isHovered(mouseX, mouseY)) { if (button == GLFW.GLFW_MOUSE_BUTTON_1) {
package net.shadowclient.main.ui.clickgui; public class ModuleButton extends FrameChild { public final Module module; public final Frame parent; public int offset; public boolean extended; public final List<SettingComponent> components; public ModuleButton(String modulename, Frame parent, int offset) { this.module = ModuleManager.getModule(modulename); this.parent = parent; this.offset = offset; this.components = new ArrayList<>(); this.extended = false; int settingOffset = parent.height; for (Setting setting : module.getSettings()) { if (setting.getClass().isAnnotationPresent(Hidden.class)) { continue; } if (setting instanceof BooleanSetting) { components.add(new BoolSetting(setting, this, settingOffset)); } else if (setting instanceof EnumSetting<?>) { components.add(new ModeSetting(setting, this, settingOffset)); } else if (setting instanceof NumberSetting) { components.add(new SliderSetting(setting, this, settingOffset)); } else if (setting instanceof StringSetting) { components.add(new TextSetting(setting, this, settingOffset)); } settingOffset += parent.height; } } public void render(DrawContext context, int mouseX, int mouseY, float delta) { boolean hovered = isHovered(mouseX, mouseY); int color = Colors.MODULE_BUTTON_NORMAL.color; if (hovered) { color = Colors.MODULE_BUTTON_HOVERED.color; } context.fill(parent.x, parent.y + offset, parent.x + parent.width, parent.y + offset + parent.height, color); int textOffset = (parent.height / 2 - parent.mc.textRenderer.fontHeight / 2); context.drawTextWithShadow(parent.mc.textRenderer, module.friendlyName, parent.x + textOffset, parent.y + offset + textOffset, getTextColor()); if (extended) { for (SettingComponent component : components) { component.render(context, mouseX, mouseY, delta); } } } public void renderDescription(DrawContext context, int mouseX, int mouseY) { int color = Colors.MODULE_BUTTON_NORMAL.color; int width = parent.mc.textRenderer.getWidth(module.description); int textOffset = (parent.height / 2 - parent.mc.textRenderer.fontHeight / 2); context.fill(parent.x + parent.width, parent.y + offset, parent.x + parent.width + width + textOffset * 2, parent.y + offset + parent.height, color); context.drawTextWithShadow(parent.mc.textRenderer, module.description, parent.x + parent.width + textOffset, parent.y + offset + textOffset, Colors.TEXT_NORMAL.color); } public void mouseClicked(double mouseX, double mouseY, int button) { if (isHovered(mouseX, mouseY)) { if (button == GLFW.GLFW_MOUSE_BUTTON_1) {
SCMain.toggleModuleEnabled(module.moduleName);
0
2023-10-07 06:55:12+00:00
12k
MRkto/MappetVoice
src/main/java/mrkto/mvoice/client/gui/GuiVoiceChange.java
[ { "identifier": "MappetVoice", "path": "src/main/java/mrkto/mvoice/MappetVoice.java", "snippet": "@Mod.EventBusSubscriber\n@Mod(\n modid = MappetVoice.MOD_ID,\n name = MappetVoice.NAME,\n version = MappetVoice.VERSION\n)\npublic class MappetVoice {\n\n public static final String ...
import mchorse.mclib.client.gui.framework.GuiBase; import mchorse.mclib.client.gui.framework.elements.GuiElement; import mchorse.mclib.client.gui.framework.elements.buttons.GuiButtonElement; import mchorse.mclib.client.gui.framework.elements.list.GuiStringListElement; import mchorse.mclib.client.gui.framework.elements.utils.GuiLabel; import mchorse.mclib.client.gui.utils.keys.IKey; import mrkto.mvoice.MappetVoice; import mrkto.mvoice.client.ClientData; import mrkto.mvoice.client.audio.DefaultRecorder; import mrkto.mvoice.client.audio.DefaultSpeaker; import mrkto.mvoice.client.AudioUtils; import mrkto.mvoice.utils.PlayerUtils; import net.minecraft.client.Minecraft; import java.util.ArrayList; import java.util.List;
7,373
package mrkto.mvoice.client.gui; public class GuiVoiceChange extends GuiBase { public GuiStringListElement Speakerlist; public GuiStringListElement Microlist; public GuiButtonElement SpeakerButton; public GuiButtonElement MicroButton; public GuiVoiceChange() { super(); Minecraft mc = Minecraft.getMinecraft(); GuiElement lelement = new GuiElement(mc); GuiElement relement = new GuiElement(mc); lelement.flex().relative(this.viewport).xy(0.25F, 0.5F).w(0.3F).anchor(0.5F, 0.5F).column(5).vertical().stretch(); relement.flex().relative(this.viewport).xy(0.75F, 0.5F).w(0.3F).anchor(0.5F, 0.5F).column(5).vertical().stretch();
package mrkto.mvoice.client.gui; public class GuiVoiceChange extends GuiBase { public GuiStringListElement Speakerlist; public GuiStringListElement Microlist; public GuiButtonElement SpeakerButton; public GuiButtonElement MicroButton; public GuiVoiceChange() { super(); Minecraft mc = Minecraft.getMinecraft(); GuiElement lelement = new GuiElement(mc); GuiElement relement = new GuiElement(mc); lelement.flex().relative(this.viewport).xy(0.25F, 0.5F).w(0.3F).anchor(0.5F, 0.5F).column(5).vertical().stretch(); relement.flex().relative(this.viewport).xy(0.75F, 0.5F).w(0.3F).anchor(0.5F, 0.5F).column(5).vertical().stretch();
ArrayList<String> mlist = MappetVoice.AudioManager.getInput().getAudioDevices();
0
2023-10-14 19:20:12+00:00
12k
Spider-Admin/Frost
src/main/java/frost/fileTransfer/sharing/SharedFilesModel.java
[ { "identifier": "FileTransferManager", "path": "src/main/java/frost/fileTransfer/FileTransferManager.java", "snippet": "public class FileTransferManager implements ExitSavable, AutoSavable {\r\n\r\n\tprivate static final Logger logger = LoggerFactory.getLogger(FileTransferManager.class);\r\n\r\n pri...
import frost.storage.perst.FrostFilesStorage; import frost.util.model.SortedModel; import frost.util.model.SortedTableFormat; import java.io.File; import java.util.Iterator; import java.util.List; import java.util.Timer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import frost.fileTransfer.FileTransferManager; import frost.fileTransfer.filelist.FileListUploadThread; import frost.storage.ExitSavable; import frost.storage.StorageException;
8,669
/* SharedFilesModel.java / Frost Copyright (C) 2006 Frost Project <jtcfrost.sourceforge.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package frost.fileTransfer.sharing; /** * This is the model that stores all FrostUploadItems. * * Its implementation is thread-safe (subclasses should synchronize against * protected attribute data when necessary). It is also assumed that the load * and save methods will not be used while other threads are under way. */ public class SharedFilesModel extends SortedModel<FrostSharedFileItem> implements ExitSavable { // TODO: for shared directories: add new files to another table, waiting for owner assignment private static final Logger logger = LoggerFactory.getLogger(SharedFilesModel.class); Timer timer; public SharedFilesModel(final SortedTableFormat<FrostSharedFileItem> f) { super(f); } /** * Will add this item to the model if not already in the model. * The new item must only have 1 FrostUploadItemOwnerBoard in its list. */ public synchronized boolean addNewSharedFile(final FrostSharedFileItem itemToAdd, final boolean replacePathIfFileExists) { for (int x = 0; x < getItemCount(); x++) { final FrostSharedFileItem item = (FrostSharedFileItem) getItemAt(x); // add if file is not shared already if( itemToAdd.getSha().equals(item.getSha()) ) { // is already in list if( replacePathIfFileExists == false ) { // ignore new file return false; } else { // renew file path final File file = itemToAdd.getFile(); item.setLastModified(file.lastModified()); item.setFile(file); item.setValid(true); return true; } } } // not in model, add addItem(itemToAdd); // notify list upload thread that user changed something
/* SharedFilesModel.java / Frost Copyright (C) 2006 Frost Project <jtcfrost.sourceforge.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package frost.fileTransfer.sharing; /** * This is the model that stores all FrostUploadItems. * * Its implementation is thread-safe (subclasses should synchronize against * protected attribute data when necessary). It is also assumed that the load * and save methods will not be used while other threads are under way. */ public class SharedFilesModel extends SortedModel<FrostSharedFileItem> implements ExitSavable { // TODO: for shared directories: add new files to another table, waiting for owner assignment private static final Logger logger = LoggerFactory.getLogger(SharedFilesModel.class); Timer timer; public SharedFilesModel(final SortedTableFormat<FrostSharedFileItem> f) { super(f); } /** * Will add this item to the model if not already in the model. * The new item must only have 1 FrostUploadItemOwnerBoard in its list. */ public synchronized boolean addNewSharedFile(final FrostSharedFileItem itemToAdd, final boolean replacePathIfFileExists) { for (int x = 0; x < getItemCount(); x++) { final FrostSharedFileItem item = (FrostSharedFileItem) getItemAt(x); // add if file is not shared already if( itemToAdd.getSha().equals(item.getSha()) ) { // is already in list if( replacePathIfFileExists == false ) { // ignore new file return false; } else { // renew file path final File file = itemToAdd.getFile(); item.setLastModified(file.lastModified()); item.setFile(file); item.setValid(true); return true; } } } // not in model, add addItem(itemToAdd); // notify list upload thread that user changed something
FileListUploadThread.getInstance().userActionOccured();
1
2023-10-07 22:25:20+00:00
12k