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
daominh-studio/quick-mem
app/src/main/java/com/daominh/quickmem/ui/fragments/home/HomeFragment.java
[ { "identifier": "ClassAdapter", "path": "app/src/main/java/com/daominh/quickmem/adapter/group/ClassAdapter.java", "snippet": "public class ClassAdapter extends RecyclerView.Adapter<ClassAdapter.ClassViewHolder> {\n private final Context context;\n private final ArrayList<Group> classes;\n\n pub...
import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.daominh.quickmem.adapter.group.ClassAdapter; import com.daominh.quickmem.adapter.folder.FolderAdapter; import com.daominh.quickmem.adapter.flashcard.SetsAdapter; import com.daominh.quickmem.data.dao.FlashCardDAO; import com.daominh.quickmem.data.dao.FolderDAO; import com.daominh.quickmem.data.dao.GroupDAO; import com.daominh.quickmem.data.model.FlashCard; import com.daominh.quickmem.data.model.Folder; import com.daominh.quickmem.data.model.Group; import com.daominh.quickmem.databinding.FragmentHomeBinding; import com.daominh.quickmem.preferen.UserSharePreferences; import com.daominh.quickmem.ui.activities.create.CreateSetActivity; import com.daominh.quickmem.ui.activities.search.ViewSearchActivity; import org.jetbrains.annotations.NotNull; import java.util.ArrayList;
13,998
package com.daominh.quickmem.ui.fragments.home; public class HomeFragment extends Fragment { private FragmentHomeBinding binding; private UserSharePreferences userSharePreferences; private SetsAdapter setsAdapter; private FolderAdapter folderAdapter; private ClassAdapter classAdapter;
package com.daominh.quickmem.ui.fragments.home; public class HomeFragment extends Fragment { private FragmentHomeBinding binding; private UserSharePreferences userSharePreferences; private SetsAdapter setsAdapter; private FolderAdapter folderAdapter; private ClassAdapter classAdapter;
private ArrayList<FlashCard> flashCards;
6
2023-11-07 16:56:39+00:00
16k
FRCTeam2910/2023CompetitionRobot-Public
src/main/java/org/frcteam2910/c2023/util/PathChooser.java
[ { "identifier": "RobotContainer", "path": "src/main/java/org/frcteam2910/c2023/RobotContainer.java", "snippet": "public class RobotContainer {\n private final PathChooser pathChooser;\n\n private final DrivetrainSubsystem drivetrainSubsystem;\n\n private final LEDSubsystem ledSubsystem;\n\n ...
import com.pathplanner.lib.PathPlannerTrajectory; import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj2.command.*; import org.frcteam2910.c2023.RobotContainer; import org.frcteam2910.c2023.commands.*; import org.frcteam2910.c2023.subsystems.drivetrain.DrivetrainSubsystem; import org.frcteam2910.c2023.subsystems.intake.IntakeSubsystem; import org.frcteam2910.c2023.util.constants.ArmPoseConstants; import org.littletonrobotics.junction.Logger;
13,920
package org.frcteam2910.c2023.util; public class PathChooser { public static final double EJECTION_DISTANCE = 0.4; // Enum for auto modes private enum AutonomousMode { DRIVE_STRAIGHT, BLUE_NO_BUMP_THREE_CUBE, RED_NO_BUMP_THREE_CUBE, NO_BUMP_TWO_CUBE_BALANCE, BLUE_NO_BUMP_TWO_AND_A_HALF_CUBE_BALANCE, RED_NO_BUMP_TWO_AND_A_HALF_CUBE_BALANCE, BLUE_LONG_INTAKE_NO_BUMP_THREE_CUBE_BALANCE, RED_LONG_INTAKE_NO_BUMP_THREE_CUBE_BALANCE, BLUE_LONG_INTAKE_NO_BUMP_THREE_CUBE_SUBSTATION, RED_LONG_INTAKE_NO_BUMP_THREE_CUBE_SUBSTATION, RED_BUMP_THREE_CUBE, BLUE_BUMP_THREE_CUBE, RED_CHEZYBUMP_THREE_CUBE, BLUE_CHEZYBUMP_THREE_CUBE, RED_CHEZYBUMP_TWO_CUBE, BLUE_CHEZYBUMP_TWO_CUBE, BUMP_TWO_AND_A_HALF_CUBE, BLUE_BUMP_TWO_CUBE, RED_BUMP_TWO_CUBE, MIDDLE_BALANCE, MIDDLE_UP_CUBE_BALANCE, MIDDLE_DOWN_CUBE_BALANCE, NO_BUMP_EXIT_COMMUNITY, BUMP_EXIT_COMMUNITY, } // Trajectories object private final PathTrajectories trajectories; // Chooser for autonomous mode private static final SendableChooser<AutonomousMode> autonomousModeChooser = new SendableChooser<>(); // Add options to chooser public PathChooser(PathTrajectories trajectories) { this.trajectories = trajectories; // autonomousModeChooser.addOption("Drive Straight", AutonomousMode.DRIVE_STRAIGHT); autonomousModeChooser.setDefaultOption( "Blue Yoshi No Bump 3 Cube Balance", AutonomousMode.BLUE_LONG_INTAKE_NO_BUMP_THREE_CUBE_BALANCE); autonomousModeChooser.setDefaultOption( "Red Yoshi No Bump 3 Cube Balance", AutonomousMode.RED_LONG_INTAKE_NO_BUMP_THREE_CUBE_BALANCE); autonomousModeChooser.addOption( "Blue Yoshi No Bump 3 Cube Substation", AutonomousMode.BLUE_LONG_INTAKE_NO_BUMP_THREE_CUBE_SUBSTATION); autonomousModeChooser.addOption( "Red Yoshi No Bump 3 Cube Substation", AutonomousMode.RED_LONG_INTAKE_NO_BUMP_THREE_CUBE_SUBSTATION); autonomousModeChooser.addOption("Blue No Bump 3 Cube", AutonomousMode.BLUE_NO_BUMP_THREE_CUBE); autonomousModeChooser.addOption("Red No Bump 3 Cube", AutonomousMode.RED_NO_BUMP_THREE_CUBE); // autonomousModeChooser.addOption("No Bump 1 Cube Balance", AutonomousMode.NO_BUMP_ONE_CUBE_BALANCE);; autonomousModeChooser.addOption( "Blue No Bump 2.5 Cube Balance", AutonomousMode.BLUE_NO_BUMP_TWO_AND_A_HALF_CUBE_BALANCE); autonomousModeChooser.addOption( "Red No Bump 2.5 Cube Balance", AutonomousMode.RED_NO_BUMP_TWO_AND_A_HALF_CUBE_BALANCE); // autonomousModeChooser.addOption("Bump 1.5 Cube", AutonomousMode.BUMP_ONE_AND_A_HALF_CUBE); // autonomousModeChooser.addOption("Chezy Blue Bump 3 Cube", AutonomousMode.BLUE_CHEZYBUMP_THREE_CUBE); // autonomousModeChooser.addOption("Chezy Red Bump 3 Cube", AutonomousMode.RED_CHEZYBUMP_THREE_CUBE); // autonomousModeChooser.addOption("Chezy Blue Bump 2 Cube", AutonomousMode.BLUE_CHEZYBUMP_TWO_CUBE); // autonomousModeChooser.addOption("Chezy Red Bump 2 Cube", AutonomousMode.RED_CHEZYBUMP_TWO_CUBE); autonomousModeChooser.addOption("Blue Bump 3 Cube", AutonomousMode.BLUE_BUMP_THREE_CUBE); autonomousModeChooser.addOption("Red Bump 3 Cube", AutonomousMode.RED_BUMP_THREE_CUBE); autonomousModeChooser.addOption("Red Bump 2 Cube", AutonomousMode.RED_BUMP_TWO_CUBE); autonomousModeChooser.addOption("Blue Bump 2 Cube", AutonomousMode.BLUE_BUMP_TWO_CUBE); // autonomousModeChooser.addOption("Middle No Bump Cube Balance", AutonomousMode.MIDDLE_UP_CUBE_BALANCE); // autonomousModeChooser.addOption("Middle Bump Cube Balance", AutonomousMode.MIDDLE_DOWN_CUBE_BALANCE); autonomousModeChooser.addOption("Middle Balance", AutonomousMode.MIDDLE_BALANCE); autonomousModeChooser.addOption("No Bump Exit Community", AutonomousMode.NO_BUMP_EXIT_COMMUNITY); autonomousModeChooser.addOption("Bump Exit Community", AutonomousMode.BUMP_EXIT_COMMUNITY); } public Command getDriveStraight(RobotContainer container) { return resetDrivetrainPose(container, trajectories.getDriveStraightPath()) .andThen(follow(container, trajectories.getDriveStraightPath())); } // Method for the preload score which happens before every sequence public Command getResetPoseAndPreloadScore(RobotContainer container, PathPlannerTrajectory trajectory) { return resetDrivetrainPose(container, trajectory)
package org.frcteam2910.c2023.util; public class PathChooser { public static final double EJECTION_DISTANCE = 0.4; // Enum for auto modes private enum AutonomousMode { DRIVE_STRAIGHT, BLUE_NO_BUMP_THREE_CUBE, RED_NO_BUMP_THREE_CUBE, NO_BUMP_TWO_CUBE_BALANCE, BLUE_NO_BUMP_TWO_AND_A_HALF_CUBE_BALANCE, RED_NO_BUMP_TWO_AND_A_HALF_CUBE_BALANCE, BLUE_LONG_INTAKE_NO_BUMP_THREE_CUBE_BALANCE, RED_LONG_INTAKE_NO_BUMP_THREE_CUBE_BALANCE, BLUE_LONG_INTAKE_NO_BUMP_THREE_CUBE_SUBSTATION, RED_LONG_INTAKE_NO_BUMP_THREE_CUBE_SUBSTATION, RED_BUMP_THREE_CUBE, BLUE_BUMP_THREE_CUBE, RED_CHEZYBUMP_THREE_CUBE, BLUE_CHEZYBUMP_THREE_CUBE, RED_CHEZYBUMP_TWO_CUBE, BLUE_CHEZYBUMP_TWO_CUBE, BUMP_TWO_AND_A_HALF_CUBE, BLUE_BUMP_TWO_CUBE, RED_BUMP_TWO_CUBE, MIDDLE_BALANCE, MIDDLE_UP_CUBE_BALANCE, MIDDLE_DOWN_CUBE_BALANCE, NO_BUMP_EXIT_COMMUNITY, BUMP_EXIT_COMMUNITY, } // Trajectories object private final PathTrajectories trajectories; // Chooser for autonomous mode private static final SendableChooser<AutonomousMode> autonomousModeChooser = new SendableChooser<>(); // Add options to chooser public PathChooser(PathTrajectories trajectories) { this.trajectories = trajectories; // autonomousModeChooser.addOption("Drive Straight", AutonomousMode.DRIVE_STRAIGHT); autonomousModeChooser.setDefaultOption( "Blue Yoshi No Bump 3 Cube Balance", AutonomousMode.BLUE_LONG_INTAKE_NO_BUMP_THREE_CUBE_BALANCE); autonomousModeChooser.setDefaultOption( "Red Yoshi No Bump 3 Cube Balance", AutonomousMode.RED_LONG_INTAKE_NO_BUMP_THREE_CUBE_BALANCE); autonomousModeChooser.addOption( "Blue Yoshi No Bump 3 Cube Substation", AutonomousMode.BLUE_LONG_INTAKE_NO_BUMP_THREE_CUBE_SUBSTATION); autonomousModeChooser.addOption( "Red Yoshi No Bump 3 Cube Substation", AutonomousMode.RED_LONG_INTAKE_NO_BUMP_THREE_CUBE_SUBSTATION); autonomousModeChooser.addOption("Blue No Bump 3 Cube", AutonomousMode.BLUE_NO_BUMP_THREE_CUBE); autonomousModeChooser.addOption("Red No Bump 3 Cube", AutonomousMode.RED_NO_BUMP_THREE_CUBE); // autonomousModeChooser.addOption("No Bump 1 Cube Balance", AutonomousMode.NO_BUMP_ONE_CUBE_BALANCE);; autonomousModeChooser.addOption( "Blue No Bump 2.5 Cube Balance", AutonomousMode.BLUE_NO_BUMP_TWO_AND_A_HALF_CUBE_BALANCE); autonomousModeChooser.addOption( "Red No Bump 2.5 Cube Balance", AutonomousMode.RED_NO_BUMP_TWO_AND_A_HALF_CUBE_BALANCE); // autonomousModeChooser.addOption("Bump 1.5 Cube", AutonomousMode.BUMP_ONE_AND_A_HALF_CUBE); // autonomousModeChooser.addOption("Chezy Blue Bump 3 Cube", AutonomousMode.BLUE_CHEZYBUMP_THREE_CUBE); // autonomousModeChooser.addOption("Chezy Red Bump 3 Cube", AutonomousMode.RED_CHEZYBUMP_THREE_CUBE); // autonomousModeChooser.addOption("Chezy Blue Bump 2 Cube", AutonomousMode.BLUE_CHEZYBUMP_TWO_CUBE); // autonomousModeChooser.addOption("Chezy Red Bump 2 Cube", AutonomousMode.RED_CHEZYBUMP_TWO_CUBE); autonomousModeChooser.addOption("Blue Bump 3 Cube", AutonomousMode.BLUE_BUMP_THREE_CUBE); autonomousModeChooser.addOption("Red Bump 3 Cube", AutonomousMode.RED_BUMP_THREE_CUBE); autonomousModeChooser.addOption("Red Bump 2 Cube", AutonomousMode.RED_BUMP_TWO_CUBE); autonomousModeChooser.addOption("Blue Bump 2 Cube", AutonomousMode.BLUE_BUMP_TWO_CUBE); // autonomousModeChooser.addOption("Middle No Bump Cube Balance", AutonomousMode.MIDDLE_UP_CUBE_BALANCE); // autonomousModeChooser.addOption("Middle Bump Cube Balance", AutonomousMode.MIDDLE_DOWN_CUBE_BALANCE); autonomousModeChooser.addOption("Middle Balance", AutonomousMode.MIDDLE_BALANCE); autonomousModeChooser.addOption("No Bump Exit Community", AutonomousMode.NO_BUMP_EXIT_COMMUNITY); autonomousModeChooser.addOption("Bump Exit Community", AutonomousMode.BUMP_EXIT_COMMUNITY); } public Command getDriveStraight(RobotContainer container) { return resetDrivetrainPose(container, trajectories.getDriveStraightPath()) .andThen(follow(container, trajectories.getDriveStraightPath())); } // Method for the preload score which happens before every sequence public Command getResetPoseAndPreloadScore(RobotContainer container, PathPlannerTrajectory trajectory) { return resetDrivetrainPose(container, trajectory)
.alongWith(score(container, ArmPoseConstants.SECONDARY_L3_CONE, GamePiece.CONE));
3
2023-11-03 02:12:12+00:00
16k
YunaBraska/type-map
src/main/java/berlin/yuna/typemap/model/TypeMap.java
[ { "identifier": "ArgsDecoder", "path": "src/main/java/berlin/yuna/typemap/logic/ArgsDecoder.java", "snippet": "public class ArgsDecoder {\n\n public static Map<String, TypeSet> argsOf(final String input) {\n final Map<String, TypeSet> result = new HashMap<>();\n final List<Integer[]> ke...
import berlin.yuna.typemap.logic.ArgsDecoder; import berlin.yuna.typemap.logic.JsonDecoder; import berlin.yuna.typemap.logic.JsonEncoder; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.IntFunction; import java.util.function.Supplier; import static berlin.yuna.typemap.logic.TypeConverter.*; import static java.util.Optional.ofNullable;
11,859
package berlin.yuna.typemap.model; /** * {@link TypeMap} is a specialized implementation of {@link HashMap} that offers enhanced * functionality for type-safe data retrieval and manipulation. It is designed for * high-performance type conversion while being native-ready for GraalVM. The {@link TypeMap} * class provides methods to retrieve data in various forms (single objects, collections, * arrays, or maps) while ensuring type safety without the need for reflection. */ public class TypeMap extends HashMap<Object, Object> implements TypeMapI<TypeMap> { /** * Default constructor for creating an empty {@link TypeMap}. */ public TypeMap() { this((Map<?, ?>) null); } /** * Constructs a new {@link TypeMap} of the specified json. */ public TypeMap(final String json) { this(JsonDecoder.jsonMapOf(json)); } /** * Constructs a new {@link TypeMap} of the specified command line arguments. */ public TypeMap(final String[] cliArgs) { this(ArgsDecoder.argsOf(String.join(" ", cliArgs))); } /** * Constructs a new {@link TypeMap} with the same mappings as the specified map. * * @param map The initial map to copy mappings from, can be null. */ public TypeMap(final Map<?, ?> map) { ofNullable(map).ifPresent(super::putAll); } /** * Retrieves the value to which the specified key is mapped, and attempts to * convert it to the specified type. * * @param <T> The target type for conversion. * @param path the key whose associated value is to be returned. * @param type the Class object of the type to convert to. * @return the value if present and convertible, else null. */ public <T> T get(final Class<T> type, final Object... path) { return gett(type, path).orElse(null); } /** * Associates the specified value with the specified key in this map. * * @param key the key with which the specified value is to be associated. * @param value the value to be associated with the specified key. * @return the updated {@link TypeMap} instance for chaining. */ public TypeMap putt(final Object key, final Object value) { super.put(key, value); return this; } /** * Associates the specified value with the specified key in this map. * * @param key the key with which the specified value is to be associated. * @param value the value to be associated with the specified key. * @return the updated {@link ConcurrentTypeMap} instance for chaining. */ public TypeMap addd(final Object key, final Object value) { super.put(key, value); return this; } /** * Retrieves the value to which the specified key is mapped, and attempts to * convert it to the specified type. * * @param <T> The target type for conversion. * @param path the key whose associated value is to be returned. * @param type the Class object of the type to convert to. * @return an Optional containing the value if present and convertible, else empty. */ public <T> Optional<T> gett(final Class<T> type, final Object... path) { return ofNullable(treeGet(this, path)).map(object -> convertObj(object, type)); } /** * Retrieves the value to which the specified key is mapped, and attempts to * convert it to the specified type. * * @param <T> The target type for conversion. * @param key the key whose associated value is to be returned. * @param type the Class object of the type to convert to. * @return an Optional containing the value if present and convertible, else empty. */ public <T> T get(final Object key, final Class<T> type) { return gett(key, type).orElse(null); } /** * Retrieves the value to which the specified key is mapped, and attempts to * convert it to the specified type. * * @param <T> The target type for conversion. * @param key the key whose associated value is to be returned. * @param type the Class object of the type to convert to. * @return an Optional containing the value if present and convertible, else empty. */ public <T> Optional<T> gett(final Object key, final Class<T> type) { return ofNullable(super.get(key)).map(object -> convertObj(object, type)); } /** * This method converts the retrieved map to a list of the specified key and value types. * * @param path The key whose associated value is to be returned. * @return a {@link LinkedTypeMap} of the specified key and value types. */ public TypeList getList(final Object... path) { return getList(TypeList::new, Object.class, path); } /** * Retrieves a collection associated at the specified index and converts it to * the specified element type. * * @param <E> The type of elements in the collection. * @param key The index whose associated value is to be returned. * @param itemType The class of the items in the collection. * @return a collection of the specified type and element type. */ public <E> List<E> getList(final Object key, final Class<E> itemType) { return getList(ArrayList::new, itemType, key); } /** * Retrieves a collection associated at the specified index and converts it to * the specified element type. * * @param <E> The type of elements in the collection. * @param path The index whose associated value is to be returned. * @param itemType The class of the items in the collection. * @return a collection of the specified type and element type. */ public <E> List<E> getList(final Class<E> itemType, final Object... path) { return getList(ArrayList::new, itemType, path); } /** * Retrieves a collection associated with the specified key and converts it to * the specified collection type and element type. * * @param <T> The type of the collection to be returned. * @param <E> The type of elements in the collection. * @param path The key whose associated value is to be returned. * @param output The supplier providing a new collection instance. * @param itemType The class of the items in the collection. * @return a collection of the specified type and element type. */ public <T extends Collection<E>, E> T getList(final Supplier<? extends T> output, final Class<E> itemType, final Object... path) { return collectionOf(treeGet(this, path), output, itemType); } /** * Retrieves a collection associated with the specified key and converts it to * the specified collection type and element type. * * @param <T> The type of the collection to be returned. * @param <E> The type of elements in the collection. * @param key The key whose associated value is to be returned. * @param output The supplier providing a new collection instance. * @param itemType The class of the items in the collection. * @return a collection of the specified type and element type. */ public <T extends Collection<E>, E> T getList(final Object key, final Supplier<? extends T> output, final Class<E> itemType) { return collectionOf(super.get(key), output, itemType); } /** * This method converts the retrieved map to a map of the specified key and value types. * * @param path The key whose associated value is to be returned. * @return a {@link LinkedTypeMap} of the specified key and value types. */ public LinkedTypeMap getMap(final Object... path) { return getMap(LinkedTypeMap::new, Object.class, Object.class, path); } /** * Retrieves a map of a specific type associated with the specified key. * This method converts the retrieved map to a map of the specified key and value types. * * @param <K> The type of keys in the returned map. * @param <V> The type of values in the returned map. * @param key The key whose associated value is to be returned. * @param keyType The class of the map's key type. * @param valueType The class of the map's value type. * @return a map of the specified key and value types. */ public <K, V> Map<K, V> getMap(final Object key, final Class<K> keyType, final Class<V> valueType) { return convertAndMap(treeGet(this, key), LinkedHashMap::new, keyType, valueType); } /** * Retrieves a map of a specific type associated with the specified key. * This method converts the retrieved map to a map of the specified key and value types. * * @param <K> The type of keys in the returned map. * @param <V> The type of values in the returned map. * @param path The key whose associated value is to be returned. * @param keyType The class of the map's key type. * @param valueType The class of the map's value type. * @return a map of the specified key and value types. */ public <K, V> Map<K, V> getMap(final Class<K> keyType, final Class<V> valueType, final Object... path) { return convertAndMap(treeGet(this, path), LinkedHashMap::new, keyType, valueType); } /** * Retrieves a map of a specific type associated with the specified key. * This method converts the retrieved map to a map of the specified key and value types. * * @param <K> The type of keys in the returned map. * @param <V> The type of values in the returned map. * @param <M> The type of the map to be returned. * @param path The key whose associated value is to be returned. * @param output A supplier providing a new map instance. * @param keyType The class of the map's key type. * @param valueType The class of the map's value type. * @return a map of the specified key and value types. */ public <K, V, M extends Map<K, V>> M getMap(final Supplier<M> output, final Class<K> keyType, final Class<V> valueType, final Object... path) { return convertAndMap(treeGet(this, path), output, keyType, valueType); } /** * Retrieves a map of a specific type associated with the specified key. * This method converts the retrieved map to a map of the specified key and value types. * * @param <K> The type of keys in the returned map. * @param <V> The type of values in the returned map. * @param <M> The type of the map to be returned. * @param key The key whose associated value is to be returned. * @param output A supplier providing a new map instance. * @param keyType The class of the map's key type. * @param valueType The class of the map's value type. * @return a map of the specified key and value types. */ public <K, V, M extends Map<K, V>> M getMap(final Object key, final Supplier<M> output, final Class<K> keyType, final Class<V> valueType) { return convertAndMap(super.get(key), output, keyType, valueType); } /** * Retrieves an array of a specific type associated with the specified key. * This method is useful for cases where the type indicator is an array instance. * * @param <E> The component type of the array. * @param path The key whose associated value is to be returned. * @param typeIndicator An array instance indicating the type of array to return. * @param componentType The class of the array's component type. * @return an array of the specified component type. */ public <E> E[] getArray(final E[] typeIndicator, final Class<E> componentType, final Object... path) { final ArrayList<E> result = getList(ArrayList::new, componentType, path); return result.toArray(Arrays.copyOf(typeIndicator, result.size())); } /** * Retrieves an array of a specific type associated with the specified key. * This method is useful for cases where the type indicator is an array instance. * * @param <E> The component type of the array. * @param key The key whose associated value is to be returned. * @param typeIndicator An array instance indicating the type of array to return. * @param componentType The class of the array's component type. * @return an array of the specified component type. */ public <E> E[] getArray(final Object key, final E[] typeIndicator, final Class<E> componentType) { final ArrayList<E> result = getList(key, ArrayList::new, componentType); return result.toArray(Arrays.copyOf(typeIndicator, result.size())); } /** * Retrieves an array of a specific type associated with the specified key. * This method allows for custom array generation using a generator function. * * @param <E> The component type of the array. * @param path The key whose associated value is to be returned. * @param generator A function to generate the array of the required size. * @param componentType The class of the array's component type. * @return an array of the specified component type. */ public <E> E[] getArray(final IntFunction<E[]> generator, final Class<E> componentType, final Object... path) { return getList(ArrayList::new, componentType, path).stream().toArray(generator); } /** * Retrieves an array of a specific type associated with the specified key. * This method allows for custom array generation using a generator function. * * @param <E> The component type of the array. * @param key The key whose associated value is to be returned. * @param generator A function to generate the array of the required size. * @param componentType The class of the array's component type. * @return an array of the specified component type. */ public <E> E[] getArray(final Object key, final IntFunction<E[]> generator, final Class<E> componentType) { return getList(key, ArrayList::new, componentType).stream().toArray(generator); } /** * Fluent typecheck if the current {@link TypeContainer} is a {@link TypeMapI} * * @return {@link Optional#empty()} if current object is not a {@link TypeMapI}, else returns self. */ public Optional<TypeMapI<?>> typeMap() { return Optional.of(this); } /** * Fluent typecheck if the current {@link TypeContainer} is a {@link TypeListI} * * @return {@link Optional#empty()} if current object is not a {@link TypeListI}, else returns self. */ public Optional<TypeListI<?>> typeList() { return Optional.empty(); } /** * Converts any object to its JSON representation. * This method intelligently dispatches the conversion task based on the type of the object, * handling Maps, Collections, Arrays (both primitive and object types), and other objects. * * @param path The key whose associated value is to be returned. * @return A JSON representation of the key value as a String. */ public String toJson(final Object... path) {
package berlin.yuna.typemap.model; /** * {@link TypeMap} is a specialized implementation of {@link HashMap} that offers enhanced * functionality for type-safe data retrieval and manipulation. It is designed for * high-performance type conversion while being native-ready for GraalVM. The {@link TypeMap} * class provides methods to retrieve data in various forms (single objects, collections, * arrays, or maps) while ensuring type safety without the need for reflection. */ public class TypeMap extends HashMap<Object, Object> implements TypeMapI<TypeMap> { /** * Default constructor for creating an empty {@link TypeMap}. */ public TypeMap() { this((Map<?, ?>) null); } /** * Constructs a new {@link TypeMap} of the specified json. */ public TypeMap(final String json) { this(JsonDecoder.jsonMapOf(json)); } /** * Constructs a new {@link TypeMap} of the specified command line arguments. */ public TypeMap(final String[] cliArgs) { this(ArgsDecoder.argsOf(String.join(" ", cliArgs))); } /** * Constructs a new {@link TypeMap} with the same mappings as the specified map. * * @param map The initial map to copy mappings from, can be null. */ public TypeMap(final Map<?, ?> map) { ofNullable(map).ifPresent(super::putAll); } /** * Retrieves the value to which the specified key is mapped, and attempts to * convert it to the specified type. * * @param <T> The target type for conversion. * @param path the key whose associated value is to be returned. * @param type the Class object of the type to convert to. * @return the value if present and convertible, else null. */ public <T> T get(final Class<T> type, final Object... path) { return gett(type, path).orElse(null); } /** * Associates the specified value with the specified key in this map. * * @param key the key with which the specified value is to be associated. * @param value the value to be associated with the specified key. * @return the updated {@link TypeMap} instance for chaining. */ public TypeMap putt(final Object key, final Object value) { super.put(key, value); return this; } /** * Associates the specified value with the specified key in this map. * * @param key the key with which the specified value is to be associated. * @param value the value to be associated with the specified key. * @return the updated {@link ConcurrentTypeMap} instance for chaining. */ public TypeMap addd(final Object key, final Object value) { super.put(key, value); return this; } /** * Retrieves the value to which the specified key is mapped, and attempts to * convert it to the specified type. * * @param <T> The target type for conversion. * @param path the key whose associated value is to be returned. * @param type the Class object of the type to convert to. * @return an Optional containing the value if present and convertible, else empty. */ public <T> Optional<T> gett(final Class<T> type, final Object... path) { return ofNullable(treeGet(this, path)).map(object -> convertObj(object, type)); } /** * Retrieves the value to which the specified key is mapped, and attempts to * convert it to the specified type. * * @param <T> The target type for conversion. * @param key the key whose associated value is to be returned. * @param type the Class object of the type to convert to. * @return an Optional containing the value if present and convertible, else empty. */ public <T> T get(final Object key, final Class<T> type) { return gett(key, type).orElse(null); } /** * Retrieves the value to which the specified key is mapped, and attempts to * convert it to the specified type. * * @param <T> The target type for conversion. * @param key the key whose associated value is to be returned. * @param type the Class object of the type to convert to. * @return an Optional containing the value if present and convertible, else empty. */ public <T> Optional<T> gett(final Object key, final Class<T> type) { return ofNullable(super.get(key)).map(object -> convertObj(object, type)); } /** * This method converts the retrieved map to a list of the specified key and value types. * * @param path The key whose associated value is to be returned. * @return a {@link LinkedTypeMap} of the specified key and value types. */ public TypeList getList(final Object... path) { return getList(TypeList::new, Object.class, path); } /** * Retrieves a collection associated at the specified index and converts it to * the specified element type. * * @param <E> The type of elements in the collection. * @param key The index whose associated value is to be returned. * @param itemType The class of the items in the collection. * @return a collection of the specified type and element type. */ public <E> List<E> getList(final Object key, final Class<E> itemType) { return getList(ArrayList::new, itemType, key); } /** * Retrieves a collection associated at the specified index and converts it to * the specified element type. * * @param <E> The type of elements in the collection. * @param path The index whose associated value is to be returned. * @param itemType The class of the items in the collection. * @return a collection of the specified type and element type. */ public <E> List<E> getList(final Class<E> itemType, final Object... path) { return getList(ArrayList::new, itemType, path); } /** * Retrieves a collection associated with the specified key and converts it to * the specified collection type and element type. * * @param <T> The type of the collection to be returned. * @param <E> The type of elements in the collection. * @param path The key whose associated value is to be returned. * @param output The supplier providing a new collection instance. * @param itemType The class of the items in the collection. * @return a collection of the specified type and element type. */ public <T extends Collection<E>, E> T getList(final Supplier<? extends T> output, final Class<E> itemType, final Object... path) { return collectionOf(treeGet(this, path), output, itemType); } /** * Retrieves a collection associated with the specified key and converts it to * the specified collection type and element type. * * @param <T> The type of the collection to be returned. * @param <E> The type of elements in the collection. * @param key The key whose associated value is to be returned. * @param output The supplier providing a new collection instance. * @param itemType The class of the items in the collection. * @return a collection of the specified type and element type. */ public <T extends Collection<E>, E> T getList(final Object key, final Supplier<? extends T> output, final Class<E> itemType) { return collectionOf(super.get(key), output, itemType); } /** * This method converts the retrieved map to a map of the specified key and value types. * * @param path The key whose associated value is to be returned. * @return a {@link LinkedTypeMap} of the specified key and value types. */ public LinkedTypeMap getMap(final Object... path) { return getMap(LinkedTypeMap::new, Object.class, Object.class, path); } /** * Retrieves a map of a specific type associated with the specified key. * This method converts the retrieved map to a map of the specified key and value types. * * @param <K> The type of keys in the returned map. * @param <V> The type of values in the returned map. * @param key The key whose associated value is to be returned. * @param keyType The class of the map's key type. * @param valueType The class of the map's value type. * @return a map of the specified key and value types. */ public <K, V> Map<K, V> getMap(final Object key, final Class<K> keyType, final Class<V> valueType) { return convertAndMap(treeGet(this, key), LinkedHashMap::new, keyType, valueType); } /** * Retrieves a map of a specific type associated with the specified key. * This method converts the retrieved map to a map of the specified key and value types. * * @param <K> The type of keys in the returned map. * @param <V> The type of values in the returned map. * @param path The key whose associated value is to be returned. * @param keyType The class of the map's key type. * @param valueType The class of the map's value type. * @return a map of the specified key and value types. */ public <K, V> Map<K, V> getMap(final Class<K> keyType, final Class<V> valueType, final Object... path) { return convertAndMap(treeGet(this, path), LinkedHashMap::new, keyType, valueType); } /** * Retrieves a map of a specific type associated with the specified key. * This method converts the retrieved map to a map of the specified key and value types. * * @param <K> The type of keys in the returned map. * @param <V> The type of values in the returned map. * @param <M> The type of the map to be returned. * @param path The key whose associated value is to be returned. * @param output A supplier providing a new map instance. * @param keyType The class of the map's key type. * @param valueType The class of the map's value type. * @return a map of the specified key and value types. */ public <K, V, M extends Map<K, V>> M getMap(final Supplier<M> output, final Class<K> keyType, final Class<V> valueType, final Object... path) { return convertAndMap(treeGet(this, path), output, keyType, valueType); } /** * Retrieves a map of a specific type associated with the specified key. * This method converts the retrieved map to a map of the specified key and value types. * * @param <K> The type of keys in the returned map. * @param <V> The type of values in the returned map. * @param <M> The type of the map to be returned. * @param key The key whose associated value is to be returned. * @param output A supplier providing a new map instance. * @param keyType The class of the map's key type. * @param valueType The class of the map's value type. * @return a map of the specified key and value types. */ public <K, V, M extends Map<K, V>> M getMap(final Object key, final Supplier<M> output, final Class<K> keyType, final Class<V> valueType) { return convertAndMap(super.get(key), output, keyType, valueType); } /** * Retrieves an array of a specific type associated with the specified key. * This method is useful for cases where the type indicator is an array instance. * * @param <E> The component type of the array. * @param path The key whose associated value is to be returned. * @param typeIndicator An array instance indicating the type of array to return. * @param componentType The class of the array's component type. * @return an array of the specified component type. */ public <E> E[] getArray(final E[] typeIndicator, final Class<E> componentType, final Object... path) { final ArrayList<E> result = getList(ArrayList::new, componentType, path); return result.toArray(Arrays.copyOf(typeIndicator, result.size())); } /** * Retrieves an array of a specific type associated with the specified key. * This method is useful for cases where the type indicator is an array instance. * * @param <E> The component type of the array. * @param key The key whose associated value is to be returned. * @param typeIndicator An array instance indicating the type of array to return. * @param componentType The class of the array's component type. * @return an array of the specified component type. */ public <E> E[] getArray(final Object key, final E[] typeIndicator, final Class<E> componentType) { final ArrayList<E> result = getList(key, ArrayList::new, componentType); return result.toArray(Arrays.copyOf(typeIndicator, result.size())); } /** * Retrieves an array of a specific type associated with the specified key. * This method allows for custom array generation using a generator function. * * @param <E> The component type of the array. * @param path The key whose associated value is to be returned. * @param generator A function to generate the array of the required size. * @param componentType The class of the array's component type. * @return an array of the specified component type. */ public <E> E[] getArray(final IntFunction<E[]> generator, final Class<E> componentType, final Object... path) { return getList(ArrayList::new, componentType, path).stream().toArray(generator); } /** * Retrieves an array of a specific type associated with the specified key. * This method allows for custom array generation using a generator function. * * @param <E> The component type of the array. * @param key The key whose associated value is to be returned. * @param generator A function to generate the array of the required size. * @param componentType The class of the array's component type. * @return an array of the specified component type. */ public <E> E[] getArray(final Object key, final IntFunction<E[]> generator, final Class<E> componentType) { return getList(key, ArrayList::new, componentType).stream().toArray(generator); } /** * Fluent typecheck if the current {@link TypeContainer} is a {@link TypeMapI} * * @return {@link Optional#empty()} if current object is not a {@link TypeMapI}, else returns self. */ public Optional<TypeMapI<?>> typeMap() { return Optional.of(this); } /** * Fluent typecheck if the current {@link TypeContainer} is a {@link TypeListI} * * @return {@link Optional#empty()} if current object is not a {@link TypeListI}, else returns self. */ public Optional<TypeListI<?>> typeList() { return Optional.empty(); } /** * Converts any object to its JSON representation. * This method intelligently dispatches the conversion task based on the type of the object, * handling Maps, Collections, Arrays (both primitive and object types), and other objects. * * @param path The key whose associated value is to be returned. * @return A JSON representation of the key value as a String. */ public String toJson(final Object... path) {
return JsonEncoder.toJson(treeGet(this, path));
2
2023-11-09 14:40:13+00:00
16k
estkme-group/InfiLPA
app/src/main/java/com/infineon/esim/lpa/data/DataModel.java
[ { "identifier": "ActivationCode", "path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/ActivationCode.java", "snippet": "public class ActivationCode implements Parcelable {\n private String activationCode;\n\n private final Boolean isValid;\n private String acFormat;\n private String ...
import android.content.Context; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.Observer; import com.infineon.esim.lpa.core.dtos.ActivationCode; import com.infineon.esim.lpa.core.dtos.EuiccInfo; import com.infineon.esim.lpa.core.dtos.profile.ProfileList; import com.infineon.esim.lpa.core.dtos.profile.ProfileMetadata; import com.infineon.esim.lpa.core.dtos.result.remote.AuthenticateResult; import com.infineon.esim.lpa.core.dtos.result.remote.CancelSessionResult; import com.infineon.esim.lpa.core.dtos.result.remote.DownloadResult; import com.infineon.esim.lpa.euicc.EuiccManager; import com.infineon.esim.lpa.lpa.LocalProfileAssistant; import com.infineon.esim.lpa.ui.generic.ActionStatus; import com.infineon.esim.lpa.ui.generic.AsyncActionStatus; import com.infineon.esim.lpa.ui.generic.Error; import com.infineon.esim.lpa.util.android.OneTimeEvent; import com.infineon.esim.util.Log; import java.util.List;
13,230
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.data; public class DataModel implements StatusAndEventHandler{ private static final String TAG = DataModel.class.getName(); private static DataModel instance; private final LocalProfileAssistant lpa; private final EuiccManager euiccManager; private final MutableLiveData<AsyncActionStatus> actionStatusLiveData; private final MutableLiveData<OneTimeEvent<Error>> errorEventLiveData; private DataModel(Context context) { this.euiccManager = new EuiccManager(context, this); this.lpa = new LocalProfileAssistant(euiccManager, this); this.actionStatusLiveData = new MutableLiveData<>(); this.errorEventLiveData = new MutableLiveData<>(); euiccManager.initializeInterfaces(); actionStatusLiveData.observeForever(actionStatusObserver); } public static void initializeInstance(Context context) { if(instance == null) { instance = new DataModel(context); } } public static DataModel getInstance() { return instance; } // observing action status final Observer<AsyncActionStatus> actionStatusObserver = actionStatus -> {
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.data; public class DataModel implements StatusAndEventHandler{ private static final String TAG = DataModel.class.getName(); private static DataModel instance; private final LocalProfileAssistant lpa; private final EuiccManager euiccManager; private final MutableLiveData<AsyncActionStatus> actionStatusLiveData; private final MutableLiveData<OneTimeEvent<Error>> errorEventLiveData; private DataModel(Context context) { this.euiccManager = new EuiccManager(context, this); this.lpa = new LocalProfileAssistant(euiccManager, this); this.actionStatusLiveData = new MutableLiveData<>(); this.errorEventLiveData = new MutableLiveData<>(); euiccManager.initializeInterfaces(); actionStatusLiveData.observeForever(actionStatusObserver); } public static void initializeInstance(Context context) { if(instance == null) { instance = new DataModel(context); } } public static DataModel getInstance() { return instance; } // observing action status final Observer<AsyncActionStatus> actionStatusObserver = actionStatus -> {
Log.debug(TAG, "Observed that action status changed: " + actionStatus.getActionStatus());
13
2023-11-06 02:41:13+00:00
16k
CxyJerry/pilipala
src/main/java/com/jerry/pilipala/domain/vod/service/impl/VodServiceImpl.java
[ { "identifier": "UserInfoBO", "path": "src/main/java/com/jerry/pilipala/application/bo/UserInfoBO.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class UserInfoBO {\n private String uid;\n private String roleId;\n private List<String> permissionIdList;\n}" }, { "identifier": ...
import cn.dev33.satoken.stp.StpUtil; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.lang.Snowflake; import cn.hutool.core.util.IdUtil; import com.fasterxml.jackson.core.JsonProcessingException; import com.jerry.pilipala.application.bo.UserInfoBO; import com.jerry.pilipala.application.dto.PreUploadDTO; import com.jerry.pilipala.application.dto.VideoPostDTO; import com.jerry.pilipala.application.vo.bvod.BVodVO; import com.jerry.pilipala.application.vo.bvod.PreviewBVodVO; import com.jerry.pilipala.application.vo.user.PreviewUserVO; import com.jerry.pilipala.application.vo.vod.*; import com.jerry.pilipala.domain.common.template.MessageTrigger; import com.jerry.pilipala.domain.message.service.MessageService; import com.jerry.pilipala.domain.user.entity.mongo.Permission; import com.jerry.pilipala.domain.user.entity.mongo.User; import com.jerry.pilipala.domain.user.entity.neo4j.UserEntity; import com.jerry.pilipala.domain.user.repository.UserEntityRepository; import com.jerry.pilipala.domain.vod.entity.mongo.distribute.Quality; import com.jerry.pilipala.domain.vod.entity.mongo.distribute.VodDistributeInfo; import com.jerry.pilipala.domain.vod.entity.mongo.event.VodHandleActionEvent; import com.jerry.pilipala.domain.vod.entity.mongo.event.VodHandleActionRecord; import com.jerry.pilipala.domain.vod.entity.mongo.statitics.VodStatistics; import com.jerry.pilipala.domain.vod.entity.mongo.thumbnails.Thumbnails; import com.jerry.pilipala.domain.vod.entity.mongo.thumbnails.VodThumbnails; import com.jerry.pilipala.domain.vod.entity.mongo.vod.BVod; import com.jerry.pilipala.domain.vod.entity.mongo.vod.Vod; import com.jerry.pilipala.domain.vod.entity.mongo.vod.VodInfo; import com.jerry.pilipala.domain.vod.entity.mongo.vod.VodProfiles; import com.jerry.pilipala.domain.vod.entity.neo4j.VodInfoEntity; import com.jerry.pilipala.domain.vod.repository.VodInfoRepository; import com.jerry.pilipala.domain.vod.service.FileService; import com.jerry.pilipala.domain.vod.service.VodService; import com.jerry.pilipala.domain.vod.service.media.UGCSchema; import com.jerry.pilipala.domain.vod.service.media.encoder.Encoder; import com.jerry.pilipala.domain.vod.service.media.profiles.Profile; import com.jerry.pilipala.infrastructure.common.errors.BusinessException; import com.jerry.pilipala.infrastructure.common.response.StandardResponse; import com.jerry.pilipala.infrastructure.enums.ActionStatusEnum; import com.jerry.pilipala.infrastructure.enums.Qn; import com.jerry.pilipala.infrastructure.enums.VodHandleActionEnum; import com.jerry.pilipala.infrastructure.enums.VodStatusEnum; import com.jerry.pilipala.infrastructure.enums.message.TemplateNameEnum; import com.jerry.pilipala.infrastructure.enums.redis.VodCacheKeyEnum; import com.jerry.pilipala.infrastructure.enums.video.Resolution; import com.jerry.pilipala.infrastructure.utils.JsonHelper; import com.jerry.pilipala.infrastructure.utils.Page; import com.jerry.pilipala.infrastructure.utils.SecurityTool; import lombok.extern.slf4j.Slf4j; import net.bramp.ffmpeg.FFmpeg; import net.bramp.ffmpeg.FFmpegExecutor; import net.bramp.ffmpeg.FFprobe; import net.bramp.ffmpeg.builder.FFmpegBuilder; import net.bramp.ffmpeg.builder.FFmpegOutputBuilder; import net.bramp.ffmpeg.probe.FFmpegFormat; import net.bramp.ffmpeg.probe.FFmpegProbeResult; import org.apache.commons.lang3.StringUtils; import org.bson.types.ObjectId; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationEventPublisher; import org.springframework.core.io.InputStreamResource; import org.springframework.core.task.TaskExecutor; import org.springframework.data.domain.Sort; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.IOException; import java.time.Instant; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors;
12,199
package com.jerry.pilipala.domain.vod.service.impl; @Slf4j @Service public class VodServiceImpl implements VodService { private final FFprobe fFprobe; private final FFmpeg fFmpeg; private final MongoTemplate mongoTemplate; private final RedisTemplate<String, Object> redisTemplate; private final Snowflake snowflake = IdUtil.getSnowflake(); private final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); private final ApplicationEventPublisher applicationEventPublisher; private final UGCSchema ugcSchema; private final TaskExecutor taskExecutor; private final VodInfoRepository vodInfoRepository; private final UserEntityRepository userEntityRepository;
package com.jerry.pilipala.domain.vod.service.impl; @Slf4j @Service public class VodServiceImpl implements VodService { private final FFprobe fFprobe; private final FFmpeg fFmpeg; private final MongoTemplate mongoTemplate; private final RedisTemplate<String, Object> redisTemplate; private final Snowflake snowflake = IdUtil.getSnowflake(); private final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); private final ApplicationEventPublisher applicationEventPublisher; private final UGCSchema ugcSchema; private final TaskExecutor taskExecutor; private final VodInfoRepository vodInfoRepository; private final UserEntityRepository userEntityRepository;
private final JsonHelper jsonHelper;
39
2023-11-03 10:05:02+00:00
16k
giteecode/oaSystemPublic
src/main/java/cn/gson/oasys/controller/inform/InformManageController.java
[ { "identifier": "BindingResultVOUtil", "path": "src/main/java/cn/gson/oasys/common/formValid/BindingResultVOUtil.java", "snippet": "public class BindingResultVOUtil {\n /**\n * 表单验证,返回形式ResultVO\n *\n * @param br\n * @return\n */\n public static ResultVO hasErrors(BindingResult...
import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.SessionAttribute; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import cn.gson.oasys.common.formValid.BindingResultVOUtil; import cn.gson.oasys.common.formValid.MapToList; import cn.gson.oasys.common.formValid.ResultEnum; import cn.gson.oasys.common.formValid.ResultVO; import cn.gson.oasys.mappers.NoticeMapper; import cn.gson.oasys.model.dao.informdao.InformDao; import cn.gson.oasys.model.dao.informdao.InformRelationDao; import cn.gson.oasys.model.dao.system.StatusDao; import cn.gson.oasys.model.dao.system.TypeDao; import cn.gson.oasys.model.dao.user.DeptDao; import cn.gson.oasys.model.dao.user.UserDao; import cn.gson.oasys.model.entity.notice.NoticeUserRelation; import cn.gson.oasys.model.entity.notice.NoticeVO; import cn.gson.oasys.model.entity.notice.NoticesList; import cn.gson.oasys.model.entity.system.SystemMenu; import cn.gson.oasys.model.entity.system.SystemStatusList; import cn.gson.oasys.model.entity.system.SystemTypeList; import cn.gson.oasys.model.entity.user.User; import cn.gson.oasys.services.inform.InformRelationService; import cn.gson.oasys.services.inform.InformService;
12,914
package cn.gson.oasys.controller.inform; @Controller @RequestMapping("/") public class InformManageController { Logger log = LoggerFactory.getLogger(getClass()); @Autowired private StatusDao statusDao; @Autowired private TypeDao typeDao; @Autowired private InformDao informDao; @Autowired private InformService informService; @Autowired private UserDao uDao; @Autowired private DeptDao deptDao; @Autowired private InformRelationDao informrelationDao; @Autowired private InformRelationService informrelationservice; @Autowired private NoticeMapper nm; /** * 通知管理面板 * * @return */ @RequestMapping("infrommanage") public String inform(@RequestParam(value = "page", defaultValue = "0") int page,@SessionAttribute("userId") Long userId,Model model) {
package cn.gson.oasys.controller.inform; @Controller @RequestMapping("/") public class InformManageController { Logger log = LoggerFactory.getLogger(getClass()); @Autowired private StatusDao statusDao; @Autowired private TypeDao typeDao; @Autowired private InformDao informDao; @Autowired private InformService informService; @Autowired private UserDao uDao; @Autowired private DeptDao deptDao; @Autowired private InformRelationDao informrelationDao; @Autowired private InformRelationService informrelationservice; @Autowired private NoticeMapper nm; /** * 通知管理面板 * * @return */ @RequestMapping("infrommanage") public String inform(@RequestParam(value = "page", defaultValue = "0") int page,@SessionAttribute("userId") Long userId,Model model) {
Page<NoticesList> page2 = informService.pageThis(page,userId);
13
2023-11-03 02:29:57+00:00
16k
ballerina-platform/module-ballerina-data-xmldata
native/src/main/java/io/ballerina/stdlib/data/xmldata/xml/XmlParser.java
[ { "identifier": "FromString", "path": "native/src/main/java/io/ballerina/stdlib/data/xmldata/FromString.java", "snippet": "public class FromString {\n\n public static Object fromStringWithType(BString string, BTypedesc typed) {\n Type expType = typed.getDescribingType();\n\n try {\n ...
import io.ballerina.runtime.api.PredefinedTypes; import io.ballerina.runtime.api.TypeTags; import io.ballerina.runtime.api.creators.TypeCreator; import io.ballerina.runtime.api.creators.ValueCreator; import io.ballerina.runtime.api.flags.SymbolFlags; import io.ballerina.runtime.api.types.ArrayType; import io.ballerina.runtime.api.types.Field; import io.ballerina.runtime.api.types.MapType; import io.ballerina.runtime.api.types.RecordType; import io.ballerina.runtime.api.types.Type; import io.ballerina.runtime.api.utils.StringUtils; import io.ballerina.runtime.api.utils.TypeUtils; import io.ballerina.runtime.api.values.BArray; import io.ballerina.runtime.api.values.BError; import io.ballerina.runtime.api.values.BMap; import io.ballerina.runtime.api.values.BString; import io.ballerina.stdlib.data.xmldata.FromString; import io.ballerina.stdlib.data.xmldata.utils.Constants; import io.ballerina.stdlib.data.xmldata.utils.DataUtils; import io.ballerina.stdlib.data.xmldata.utils.DiagnosticErrorCode; import io.ballerina.stdlib.data.xmldata.utils.DiagnosticLog; import java.io.Reader; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; import java.util.Stack; import javax.xml.namespace.QName; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import static javax.xml.stream.XMLStreamConstants.CDATA; import static javax.xml.stream.XMLStreamConstants.CHARACTERS; import static javax.xml.stream.XMLStreamConstants.COMMENT; import static javax.xml.stream.XMLStreamConstants.DTD; import static javax.xml.stream.XMLStreamConstants.END_DOCUMENT; import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; import static javax.xml.stream.XMLStreamConstants.PROCESSING_INSTRUCTION; import static javax.xml.stream.XMLStreamConstants.START_ELEMENT;
11,971
if (xmlStreamReader.hasNext()) { int next = xmlStreamReader.next(); if (next == COMMENT || next == PROCESSING_INSTRUCTION) { parseRootElement(xmlStreamReader, xmlParserData); return; } else if (next != START_ELEMENT) { throw DiagnosticLog.error(DiagnosticErrorCode.XML_ROOT_MISSING); } } RecordType rootRecord = xmlParserData.rootRecord; xmlParserData.currentNode = ValueCreator.createRecordValue(rootRecord); QualifiedName elementQName = getElementName(xmlStreamReader); xmlParserData.rootElement = DataUtils.validateAndGetXmlNameFromRecordAnnotation(rootRecord, rootRecord.getName(), elementQName); DataUtils.validateTypeNamespace(elementQName.getPrefix(), elementQName.getNamespaceURI(), rootRecord); // Keep track of fields and attributes updateExpectedTypeStacks(rootRecord, xmlParserData); handleAttributes(xmlStreamReader, xmlParserData); } private void readText(XMLStreamReader xmlStreamReader, boolean isCData, XmlParserData xmlParserData) throws XMLStreamException { Field currentField = xmlParserData.currentField; TextValue textValue = new TextValue(); String text; if (isCData) { text = xmlStreamReader.getText(); } else { handleTruncatedCharacters(xmlStreamReader, textValue); text = textValue.text; } if (text.strip().isBlank()) { return; } if (currentField == null) { Map<QualifiedName, Field> currentFieldMap = xmlParserData.fieldHierarchy.peek(); if (!currentFieldMap.containsKey(Constants.CONTENT_QNAME)) { return; } else { currentField = currentFieldMap.remove(Constants.CONTENT_QNAME); } } BString bText = StringUtils.fromString(text); String fieldName = currentField.getFieldName(); BString bFieldName = StringUtils.fromString(fieldName); Type fieldType = TypeUtils.getReferredType(currentField.getFieldType()); if (textValue.isCommentInTheMiddle && !DataUtils.isStringValueAssignable(fieldType.getTag())) { throw DiagnosticLog.error(DiagnosticErrorCode.INVALID_TYPE, fieldType, PredefinedTypes.TYPE_STRING); } if (xmlParserData.currentNode.containsKey(bFieldName)) { if (!DataUtils.isArrayValueAssignable(fieldType.getTag())) { throw DiagnosticLog.error(DiagnosticErrorCode.FOUND_ARRAY_FOR_NON_ARRAY_TYPE, fieldType, fieldName); } int arraySize = ((ArrayType) fieldType).getSize(); if (arraySize != -1 && arraySize <= ((BArray) xmlParserData.currentNode.get(bFieldName)).getLength()) { return; } ((BArray) xmlParserData.currentNode.get(bFieldName)).append(convertStringToRestExpType(bText, fieldType)); return; } if (fieldType.getTag() == TypeTags.RECORD_TYPE_TAG) { handleContentFieldInRecordType((RecordType) fieldType, bText, xmlParserData); } else if (fieldType.getTag() == TypeTags.ARRAY_TAG && ((ArrayType) fieldType).getElementType().getTag() == TypeTags.RECORD_TYPE_TAG) { handleContentFieldInRecordType((RecordType) ((ArrayType) fieldType).getElementType(), bText, xmlParserData); } else { xmlParserData.currentNode.put(bFieldName, convertStringToRestExpType(bText, fieldType)); } } private void handleTruncatedCharacters(XMLStreamReader xmlStreamReader, TextValue textValue) throws XMLStreamException { StringBuilder textBuilder = new StringBuilder(); while (xmlStreamReader.getEventType() == CHARACTERS) { textBuilder.append(xmlStreamReader.getText()); if (xmlStreamReader.next() == COMMENT) { textValue.isCommentInTheMiddle = true; xmlStreamReader.next(); } } textValue.text = textBuilder.toString(); } @SuppressWarnings("unchecked") private void handleContentFieldInRecordType(RecordType recordType, BString text, XmlParserData xmlParserData) { popStacks(xmlParserData); for (String key : recordType.getFields().keySet()) { if (key.contains(Constants.CONTENT)) { xmlParserData.currentNode.put(StringUtils.fromString(key), convertStringToExpType(text, recordType.getFields().get(key).getFieldType())); xmlParserData.currentNode = (BMap<BString, Object>) xmlParserData.nodesStack.pop(); return; } } Type restType = TypeUtils.getReferredType(recordType.getRestFieldType()); if (restType == null) { return; } xmlParserData.currentNode.put(StringUtils.fromString(Constants.CONTENT), convertStringToRestExpType(text, restType)); xmlParserData.currentNode = (BMap<BString, Object>) xmlParserData.nodesStack.pop(); } private Object convertStringToExpType(BString value, Type expType) { if (expType.getTag() == TypeTags.ARRAY_TAG) { expType = ((ArrayType) expType).getElementType(); }
/* * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). * * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.ballerina.stdlib.data.xmldata.xml; /** * Convert Xml string to a ballerina record. * * @since 0.1.0 */ public class XmlParser { // XMLInputFactory2 private static final XMLInputFactory xmlInputFactory; static { xmlInputFactory = XMLInputFactory.newInstance(); xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); } private XMLStreamReader xmlStreamReader; public static final String PARSE_ERROR = "failed to parse xml"; public static final String PARSE_ERROR_PREFIX = PARSE_ERROR + ": "; public XmlParser(Reader stringReader) { try { xmlStreamReader = xmlInputFactory.createXMLStreamReader(stringReader); } catch (XMLStreamException e) { handleXMLStreamException(e); } } public static Object parse(Reader reader, Type type) { try { XmlParserData xmlParserData = new XmlParserData(); XmlParser xmlParser = new XmlParser(reader); return xmlParser.parse(type, xmlParserData); } catch (BError e) { return e; } catch (Throwable e) { return DiagnosticLog.error(DiagnosticErrorCode.XML_PARSE_ERROR, e.getMessage()); } } private void handleXMLStreamException(Exception e) { String reason = e.getCause() == null ? e.getMessage() : e.getCause().getMessage(); if (reason == null) { throw DiagnosticLog.getXmlError(PARSE_ERROR); } throw DiagnosticLog.getXmlError(PARSE_ERROR_PREFIX + reason); } public Object parse(Type type, XmlParserData xmlParserData) { if (type.getTag() != TypeTags.RECORD_TYPE_TAG) { throw DiagnosticLog.error(DiagnosticErrorCode.INVALID_TYPE, Constants.RECORD, type.getName()); } xmlParserData.rootRecord = (RecordType) type; Object result = parse(xmlParserData); reset(xmlParserData); return result; } private void reset(XmlParserData xmlParserData) { xmlParserData.fieldHierarchy.clear(); xmlParserData.attributeHierarchy.clear(); xmlParserData.restTypes.clear(); xmlParserData.nodesStack.clear(); xmlParserData.parents.clear(); xmlParserData.siblings.clear(); xmlParserData.recordTypeStack.clear(); xmlParserData.restFieldsPoints.clear(); } public Object parse(XmlParserData xmlParserData) { try { parseRootElement(xmlStreamReader, xmlParserData); boolean readNext = false; int next; while (xmlStreamReader.hasNext()) { if (readNext) { next = xmlStreamReader.getEventType(); } else { next = xmlStreamReader.next(); } readNext = parseXmlElements(next, xmlParserData); } } catch (NumberFormatException e) { throw DiagnosticLog.getXmlError(PARSE_ERROR_PREFIX + e); } catch (BError e) { throw e; } catch (Exception e) { handleXMLStreamException(e); } return xmlParserData.currentNode; } private boolean parseXmlElements(int next, XmlParserData xmlParserData) throws XMLStreamException { switch (next) { case START_ELEMENT -> readElement(xmlStreamReader, xmlParserData); case END_ELEMENT -> endElement(xmlStreamReader, xmlParserData); case CDATA -> readText(xmlStreamReader, true, xmlParserData); case CHARACTERS -> { readText(xmlStreamReader, false, xmlParserData); return true; } case END_DOCUMENT -> buildDocument(xmlParserData); case PROCESSING_INSTRUCTION, COMMENT, DTD -> { } // Ignore default -> { assert false; } } return false; } public void parseRecordRest(String startElementName, XmlParserData xmlParserData) { try { boolean readNext = false; int next; while (xmlStreamReader.hasNext()) { if (readNext) { next = xmlStreamReader.getEventType(); } else { next = xmlStreamReader.next(); } // Terminate the record rest field parsing if the end element is reached. if (next == END_ELEMENT) { QName endElement = xmlStreamReader.getName(); if (endElement.getLocalPart().equals(startElementName)) { validateRequiredFields(xmlParserData); xmlParserData.fieldHierarchy.pop(); xmlParserData.restTypes.pop(); xmlParserData.attributeHierarchy.pop(); break; } } readNext = parseXmlElements(next, xmlParserData); } } catch (BError e) { throw e; } catch (Exception e) { handleXMLStreamException(e); } } private void parseRootElement(XMLStreamReader xmlStreamReader, XmlParserData xmlParserData) throws XMLStreamException { if (xmlStreamReader.hasNext()) { int next = xmlStreamReader.next(); if (next == COMMENT || next == PROCESSING_INSTRUCTION) { parseRootElement(xmlStreamReader, xmlParserData); return; } else if (next != START_ELEMENT) { throw DiagnosticLog.error(DiagnosticErrorCode.XML_ROOT_MISSING); } } RecordType rootRecord = xmlParserData.rootRecord; xmlParserData.currentNode = ValueCreator.createRecordValue(rootRecord); QualifiedName elementQName = getElementName(xmlStreamReader); xmlParserData.rootElement = DataUtils.validateAndGetXmlNameFromRecordAnnotation(rootRecord, rootRecord.getName(), elementQName); DataUtils.validateTypeNamespace(elementQName.getPrefix(), elementQName.getNamespaceURI(), rootRecord); // Keep track of fields and attributes updateExpectedTypeStacks(rootRecord, xmlParserData); handleAttributes(xmlStreamReader, xmlParserData); } private void readText(XMLStreamReader xmlStreamReader, boolean isCData, XmlParserData xmlParserData) throws XMLStreamException { Field currentField = xmlParserData.currentField; TextValue textValue = new TextValue(); String text; if (isCData) { text = xmlStreamReader.getText(); } else { handleTruncatedCharacters(xmlStreamReader, textValue); text = textValue.text; } if (text.strip().isBlank()) { return; } if (currentField == null) { Map<QualifiedName, Field> currentFieldMap = xmlParserData.fieldHierarchy.peek(); if (!currentFieldMap.containsKey(Constants.CONTENT_QNAME)) { return; } else { currentField = currentFieldMap.remove(Constants.CONTENT_QNAME); } } BString bText = StringUtils.fromString(text); String fieldName = currentField.getFieldName(); BString bFieldName = StringUtils.fromString(fieldName); Type fieldType = TypeUtils.getReferredType(currentField.getFieldType()); if (textValue.isCommentInTheMiddle && !DataUtils.isStringValueAssignable(fieldType.getTag())) { throw DiagnosticLog.error(DiagnosticErrorCode.INVALID_TYPE, fieldType, PredefinedTypes.TYPE_STRING); } if (xmlParserData.currentNode.containsKey(bFieldName)) { if (!DataUtils.isArrayValueAssignable(fieldType.getTag())) { throw DiagnosticLog.error(DiagnosticErrorCode.FOUND_ARRAY_FOR_NON_ARRAY_TYPE, fieldType, fieldName); } int arraySize = ((ArrayType) fieldType).getSize(); if (arraySize != -1 && arraySize <= ((BArray) xmlParserData.currentNode.get(bFieldName)).getLength()) { return; } ((BArray) xmlParserData.currentNode.get(bFieldName)).append(convertStringToRestExpType(bText, fieldType)); return; } if (fieldType.getTag() == TypeTags.RECORD_TYPE_TAG) { handleContentFieldInRecordType((RecordType) fieldType, bText, xmlParserData); } else if (fieldType.getTag() == TypeTags.ARRAY_TAG && ((ArrayType) fieldType).getElementType().getTag() == TypeTags.RECORD_TYPE_TAG) { handleContentFieldInRecordType((RecordType) ((ArrayType) fieldType).getElementType(), bText, xmlParserData); } else { xmlParserData.currentNode.put(bFieldName, convertStringToRestExpType(bText, fieldType)); } } private void handleTruncatedCharacters(XMLStreamReader xmlStreamReader, TextValue textValue) throws XMLStreamException { StringBuilder textBuilder = new StringBuilder(); while (xmlStreamReader.getEventType() == CHARACTERS) { textBuilder.append(xmlStreamReader.getText()); if (xmlStreamReader.next() == COMMENT) { textValue.isCommentInTheMiddle = true; xmlStreamReader.next(); } } textValue.text = textBuilder.toString(); } @SuppressWarnings("unchecked") private void handleContentFieldInRecordType(RecordType recordType, BString text, XmlParserData xmlParserData) { popStacks(xmlParserData); for (String key : recordType.getFields().keySet()) { if (key.contains(Constants.CONTENT)) { xmlParserData.currentNode.put(StringUtils.fromString(key), convertStringToExpType(text, recordType.getFields().get(key).getFieldType())); xmlParserData.currentNode = (BMap<BString, Object>) xmlParserData.nodesStack.pop(); return; } } Type restType = TypeUtils.getReferredType(recordType.getRestFieldType()); if (restType == null) { return; } xmlParserData.currentNode.put(StringUtils.fromString(Constants.CONTENT), convertStringToRestExpType(text, restType)); xmlParserData.currentNode = (BMap<BString, Object>) xmlParserData.nodesStack.pop(); } private Object convertStringToExpType(BString value, Type expType) { if (expType.getTag() == TypeTags.ARRAY_TAG) { expType = ((ArrayType) expType).getElementType(); }
Object result = FromString.fromStringWithTypeInternal(value, expType);
0
2023-11-08 04:13:52+00:00
16k
Mau38/SparePartsFTC
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/drive/SampleTankDrive.java
[ { "identifier": "MAX_ACCEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/drive/DriveConstants.java", "snippet": "public static double MAX_ACCEL = 30;" }, { "identifier": "MAX_ANG_ACCEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/d...
import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MAX_ACCEL; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MAX_ANG_ACCEL; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MAX_ANG_VEL; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MAX_VEL; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MOTOR_VELO_PID; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.RUN_USING_ENCODER; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.TRACK_WIDTH; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.encoderTicksToInches; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.kA; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.kStatic; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.kV; import androidx.annotation.NonNull; import com.acmerobotics.dashboard.config.Config; import com.acmerobotics.roadrunner.control.PIDCoefficients; import com.acmerobotics.roadrunner.drive.DriveSignal; import com.acmerobotics.roadrunner.drive.TankDrive; import com.acmerobotics.roadrunner.followers.TankPIDVAFollower; import com.acmerobotics.roadrunner.followers.TrajectoryFollower; import com.acmerobotics.roadrunner.geometry.Pose2d; import com.acmerobotics.roadrunner.trajectory.Trajectory; import com.acmerobotics.roadrunner.trajectory.TrajectoryBuilder; import com.acmerobotics.roadrunner.trajectory.constraints.AngularVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MinVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.ProfileAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TankVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryVelocityConstraint; import com.qualcomm.hardware.lynx.LynxModule; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorEx; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.IMU; import com.qualcomm.robotcore.hardware.PIDFCoefficients; import com.qualcomm.robotcore.hardware.VoltageSensor; import com.qualcomm.robotcore.hardware.configuration.typecontainers.MotorConfigurationType; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.teamcode.roadRunner.trajectorysequence.TrajectorySequence; import org.firstinspires.ftc.teamcode.roadRunner.trajectorysequence.TrajectorySequenceBuilder; import org.firstinspires.ftc.teamcode.roadRunner.trajectorysequence.TrajectorySequenceRunner; import org.firstinspires.ftc.teamcode.roadRunner.util.LynxModuleUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
10,873
package org.firstinspires.ftc.teamcode.roadRunner.drive; /* * Simple tank drive hardware implementation for REV hardware. */ @Config public class SampleTankDrive extends TankDrive { public static PIDCoefficients AXIAL_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients CROSS_TRACK_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(0, 0, 0); public static double VX_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner; private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(MAX_VEL, MAX_ANG_VEL, TRACK_WIDTH); private static final TrajectoryAccelerationConstraint accelConstraint = getAccelerationConstraint(MAX_ACCEL); private TrajectoryFollower follower; private List<DcMotorEx> motors, leftMotors, rightMotors; private IMU imu; private VoltageSensor batteryVoltageSensor; public SampleTankDrive(HardwareMap hardwareMap) {
package org.firstinspires.ftc.teamcode.roadRunner.drive; /* * Simple tank drive hardware implementation for REV hardware. */ @Config public class SampleTankDrive extends TankDrive { public static PIDCoefficients AXIAL_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients CROSS_TRACK_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(0, 0, 0); public static double VX_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner; private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(MAX_VEL, MAX_ANG_VEL, TRACK_WIDTH); private static final TrajectoryAccelerationConstraint accelConstraint = getAccelerationConstraint(MAX_ACCEL); private TrajectoryFollower follower; private List<DcMotorEx> motors, leftMotors, rightMotors; private IMU imu; private VoltageSensor batteryVoltageSensor; public SampleTankDrive(HardwareMap hardwareMap) {
super(kV, kA, kStatic, TRACK_WIDTH);
9
2023-11-06 21:25:54+00:00
16k
celedev97/asa-server-manager
src/main/java/dev/cele/asa_sm/ui/components/server_tab_accordions/RulesAccordion.java
[ { "identifier": "SpringApplicationContext", "path": "src/main/java/dev/cele/asa_sm/config/SpringApplicationContext.java", "snippet": "@Configuration\npublic class SpringApplicationContext implements ApplicationContextAware {\n private static ApplicationContext context;\n\n @Override\n public vo...
import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; import com.intellij.uiDesigner.core.Spacer; import dev.cele.asa_sm.config.SpringApplicationContext; import dev.cele.asa_sm.dto.AsaServerConfigDto; import dev.cele.asa_sm.ui.components.AccordionTopBar; import dev.cele.asa_sm.ui.components.forms.SliderWithText; import dev.cele.asa_sm.ui.components.forms.TimeField; import org.springframework.core.env.Environment; import javax.swing.*; import javax.swing.border.TitledBorder; import java.awt.*; import java.util.Arrays;
13,250
panel4.add(label15, new GridConstraints(1, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label16 = new JLabel(); label16.setText("items"); panel4.add(label16, new GridConstraints(2, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel5 = new JPanel(); panel5.setLayout(new GridLayoutManager(5, 3, new Insets(0, 0, 0, 0), -1, -1)); panel1.add(panel5, new GridConstraints(15, 0, 1, 4, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel5.setBorder(BorderFactory.createTitledBorder(null, "Cluster Tribute Options", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); noTransferFromFilteringCheckBox = new JCheckBox(); noTransferFromFilteringCheckBox.setText("No Transfer from Filtering"); panel5.add(noTransferFromFilteringCheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final Spacer spacer1 = new Spacer(); panel5.add(spacer1, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); final JLabel label17 = new JLabel(); label17.setText("Override Survivor Upload Expiration"); panel5.add(label17, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText10 = new SliderWithText(); panel5.add(sliderWithText10, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label18 = new JLabel(); label18.setText("minutes"); panel5.add(label18, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label19 = new JLabel(); label19.setText("Override Item Upload Expiration"); panel5.add(label19, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText11 = new SliderWithText(); panel5.add(sliderWithText11, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label20 = new JLabel(); label20.setText("minutes"); panel5.add(label20, new GridConstraints(2, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label21 = new JLabel(); label21.setText("Override Dino Upload Expiration"); panel5.add(label21, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText12 = new SliderWithText(); panel5.add(sliderWithText12, new GridConstraints(3, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label22 = new JLabel(); label22.setText("minutes"); panel5.add(label22, new GridConstraints(3, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label23 = new JLabel(); label23.setText("Override Minimum Dino Re-upload Interval"); panel5.add(label23, new GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText13 = new SliderWithText(); panel5.add(sliderWithText13, new GridConstraints(4, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label24 = new JLabel(); label24.setText("minutes"); panel5.add(label24, new GridConstraints(4, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel6 = new JPanel(); panel6.setLayout(new GridLayoutManager(4, 3, new Insets(0, 0, 0, 0), -1, -1)); panel1.add(panel6, new GridConstraints(16, 0, 1, 4, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel6.setBorder(BorderFactory.createTitledBorder(null, "PvP Respawn Options", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); final JLabel label25 = new JLabel(); label25.setText("Interval Check Period"); panel6.add(label25, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText14 = new SliderWithText(); panel6.add(sliderWithText14, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label26 = new JLabel(); label26.setText("seconds"); panel6.add(label26, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label27 = new JLabel(); label27.setText("Interval Multiplier:"); panel6.add(label27, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText15 = new SliderWithText(); panel6.add(sliderWithText15, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label28 = new JLabel(); label28.setText("x"); panel6.add(label28, new GridConstraints(2, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label29 = new JLabel(); label29.setText("Interval Base Amount:"); panel6.add(label29, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText16 = new SliderWithText(); panel6.add(sliderWithText16, new GridConstraints(3, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label30 = new JLabel(); label30.setText("seconds"); panel6.add(label30, new GridConstraints(3, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); increasePvPRespawnIntervalCheckBox = new JCheckBox(); increasePvPRespawnIntervalCheckBox.setText("Increase PvP Respawn Interval"); panel6.add(increasePvPRespawnIntervalCheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel7 = new JPanel(); panel7.setLayout(new GridLayoutManager(3, 3, new Insets(0, 0, 0, 0), -1, -1)); panel1.add(panel7, new GridConstraints(17, 0, 1, 4, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel7.setBorder(BorderFactory.createTitledBorder(null, "PvP Offline Options", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); preventOfflinePvPCheckBox = new JCheckBox(); preventOfflinePvPCheckBox.setText("Prevent Offline PvP"); panel7.add(preventOfflinePvPCheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final Spacer spacer2 = new Spacer(); panel7.add(spacer2, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); final JLabel label31 = new JLabel(); label31.setText("Logout Interval"); panel7.add(label31, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText17 = new SliderWithText(); panel7.add(sliderWithText17, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label32 = new JLabel(); label32.setText("seconds"); panel7.add(label32, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label33 = new JLabel(); label33.setText("Connection Invincible Interval"); panel7.add(label33, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText18 = new SliderWithText(); panel7.add(sliderWithText18, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label34 = new JLabel(); label34.setText("seconds"); panel7.add(label34, new GridConstraints(2, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel8 = new JPanel(); panel8.setLayout(new GridLayoutManager(2, 5, new Insets(0, 0, 0, 0), -1, -1)); panel1.add(panel8, new GridConstraints(18, 0, 1, 4, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel8.setBorder(BorderFactory.createTitledBorder(null, "PvE Schedule", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); enablePvEScheduleCheckBox = new JCheckBox(); enablePvEScheduleCheckBox.setText("Enable PvE Schedule"); panel8.add(enablePvEScheduleCheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); useServerTimeCheckBox = new JCheckBox(); useServerTimeCheckBox.setText("Use Server Time"); panel8.add(useServerTimeCheckBox, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label35 = new JLabel(); label35.setText("Start Time"); panel8.add(label35, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label36 = new JLabel(); label36.setText("Stop Time"); panel8.add(label36, new GridConstraints(1, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel9 = new JPanel(); panel9.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1)); panel8.add(panel9, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
package dev.cele.asa_sm.ui.components.server_tab_accordions; public class RulesAccordion { private JCheckBox enableHardcoreModeCheckBox; private JCheckBox enablePvPCheckBox; private JCheckBox enableCreativeModeCheckBox; public JPanel contentPane; private JCheckBox disablePvEFriendlyFireCheckBox; private JCheckBox disablePvPFriendlyFireCheckBox; private JCheckBox preventBuildingInResourceCheckBox; private JCheckBox enableSignlePlayerSettingsCheckBox; private JCheckBox enablePvPCaveBuildingCheckBox; private JCheckBox disableCustomTributeFoldersCheckBox; private JCheckBox disablePvPRailgunCheckBox; private JCheckBox enablePveCryoSicknessCheckBox; private JCheckBox disableSupllyCratesCheckBox; private JCheckBox allowCratesSpawnOnCheckBox; private JCheckBox randomSupplyCratesPointsCheckBox; private JCheckBox useCorpseLocatorCheckBox; private JCheckBox preventSpawnAnimationsCheckBox; private JCheckBox allowUnlimitedRespecsCheckBox; private JCheckBox allowPlatformSaddleMultiCheckBox; private JCheckBox enableDifficultyOverrideCheckBox; private JCheckBox enablePvECaveBuildingCheckBox; private JCheckBox enableTributeDownloadsCheckBox; private JCheckBox noSurvivorDownloadsCheckBox; private JCheckBox noItemDownloadsCheckBox; private JCheckBox noDinoDownloadsCheckBox; private JCheckBox allowForeignsDinoDownloadsCheckBox; private JCheckBox noSurvivorUploadsCheckBox; private JCheckBox noItemUploadsCheckBox; private JCheckBox noDinoUploadsCheckBox; private JCheckBox noTransferFromFilteringCheckBox; private JCheckBox increasePvPRespawnIntervalCheckBox; private JCheckBox preventOfflinePvPCheckBox; private JCheckBox enablePvEScheduleCheckBox; private JCheckBox useServerTimeCheckBox; private JCheckBox allowTribeAlliancesCheckBox; private JCheckBox allowTribeWarfareCheckBox; private JCheckBox allowCancellingTribeWarfareCheckBox; private JCheckBox allowCustomRecipesCheckBox; private AsaServerConfigDto configDto; public RulesAccordion(AsaServerConfigDto configDto) { this.configDto = configDto; SwingUtilities.invokeLater(this::afterInit); } Environment environment = SpringApplicationContext.autoWire(Environment.class); private void afterInit() { enableHardcoreModeCheckBox.setSelected(configDto.getGameUserSettingsINI().getServerSettings().getServerHardcore()); enableHardcoreModeCheckBox.addActionListener(e -> configDto.getGameUserSettingsINI().getServerSettings().setServerHardcore(enableHardcoreModeCheckBox.isSelected()) ); enablePvPCheckBox.setSelected(!configDto.getGameUserSettingsINI().getServerSettings().getServerPVE()); enablePvPCheckBox.addActionListener(e -> configDto.getGameUserSettingsINI().getServerSettings().setServerPVE(!enablePvPCheckBox.isSelected()) ); } { // GUI initializer generated by IntelliJ IDEA GUI Designer // >>> IMPORTANT!! <<< // DO NOT EDIT OR ADD ANY CODE HERE! $$$setupUI$$$(); } /** * Method generated by IntelliJ IDEA GUI Designer * >>> IMPORTANT!! <<< * DO NOT edit this method OR call it in your code! * * @noinspection ALL */ private void $$$setupUI$$$() { contentPane = new JPanel(); contentPane.setLayout(new BorderLayout(0, 0)); contentPane.setVisible(true); final JPanel panel1 = new JPanel(); panel1.setLayout(new GridLayoutManager(25, 4, new Insets(0, 0, 0, 0), -1, -1)); contentPane.add(panel1, BorderLayout.CENTER); enableHardcoreModeCheckBox = new JCheckBox(); enableHardcoreModeCheckBox.setText("Enable Hardcore Mode"); panel1.add(enableHardcoreModeCheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); disablePvEFriendlyFireCheckBox = new JCheckBox(); disablePvEFriendlyFireCheckBox.setText("Disable Pve Friendly Fire"); panel1.add(disablePvEFriendlyFireCheckBox, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); disablePvPFriendlyFireCheckBox = new JCheckBox(); disablePvPFriendlyFireCheckBox.setText("Disable PvP Friendly Fire"); panel1.add(disablePvPFriendlyFireCheckBox, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); preventBuildingInResourceCheckBox = new JCheckBox(); preventBuildingInResourceCheckBox.setText("Prevent Building in Resource Rich Areas"); panel1.add(preventBuildingInResourceCheckBox, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); disableCustomTributeFoldersCheckBox = new JCheckBox(); disableCustomTributeFoldersCheckBox.setText("Disable Custom Tribute Folders"); panel1.add(disableCustomTributeFoldersCheckBox, new GridConstraints(3, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); enablePvPCheckBox = new JCheckBox(); enablePvPCheckBox.setText("Enable PvP"); panel1.add(enablePvPCheckBox, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); enableCreativeModeCheckBox = new JCheckBox(); enableCreativeModeCheckBox.setText("Enable Creative Mode"); panel1.add(enableCreativeModeCheckBox, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); enablePvPCaveBuildingCheckBox = new JCheckBox(); enablePvPCaveBuildingCheckBox.setText("Enable PvP Cave Building"); panel1.add(enablePvPCaveBuildingCheckBox, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); enableSignlePlayerSettingsCheckBox = new JCheckBox(); enableSignlePlayerSettingsCheckBox.setText("Enable Signle Player Settings"); panel1.add(enableSignlePlayerSettingsCheckBox, new GridConstraints(3, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); disablePvPRailgunCheckBox = new JCheckBox(); disablePvPRailgunCheckBox.setText("Disable PvP Railgun"); panel1.add(disablePvPRailgunCheckBox, new GridConstraints(2, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); enablePveCryoSicknessCheckBox = new JCheckBox(); enablePveCryoSicknessCheckBox.setText("Enable Pve Cryo Sickness"); panel1.add(enablePveCryoSicknessCheckBox, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); disableSupllyCratesCheckBox = new JCheckBox(); disableSupllyCratesCheckBox.setText("Disable Suplly Crates"); panel1.add(disableSupllyCratesCheckBox, new GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); allowCratesSpawnOnCheckBox = new JCheckBox(); allowCratesSpawnOnCheckBox.setText("Allow Crates Spawn on top of Structures"); panel1.add(allowCratesSpawnOnCheckBox, new GridConstraints(4, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); randomSupplyCratesPointsCheckBox = new JCheckBox(); randomSupplyCratesPointsCheckBox.setText("Random Supply Crates Points"); panel1.add(randomSupplyCratesPointsCheckBox, new GridConstraints(4, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText1 = new SliderWithText(); panel1.add(sliderWithText1, new GridConstraints(5, 1, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final SliderWithText sliderWithText2 = new SliderWithText(); panel1.add(sliderWithText2, new GridConstraints(6, 1, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); useCorpseLocatorCheckBox = new JCheckBox(); useCorpseLocatorCheckBox.setText("Use Corpse Locator"); panel1.add(useCorpseLocatorCheckBox, new GridConstraints(7, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); preventSpawnAnimationsCheckBox = new JCheckBox(); preventSpawnAnimationsCheckBox.setText("Prevent Spawn Animations"); panel1.add(preventSpawnAnimationsCheckBox, new GridConstraints(7, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); allowUnlimitedRespecsCheckBox = new JCheckBox(); allowUnlimitedRespecsCheckBox.setText("Allow Unlimited Respecs"); panel1.add(allowUnlimitedRespecsCheckBox, new GridConstraints(7, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); allowPlatformSaddleMultiCheckBox = new JCheckBox(); allowPlatformSaddleMultiCheckBox.setText("Allow Platform Saddle Multi Floors"); panel1.add(allowPlatformSaddleMultiCheckBox, new GridConstraints(8, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText3 = new SliderWithText(); panel1.add(sliderWithText3, new GridConstraints(9, 1, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final SliderWithText sliderWithText4 = new SliderWithText(); panel1.add(sliderWithText4, new GridConstraints(10, 1, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final SliderWithText sliderWithText5 = new SliderWithText(); panel1.add(sliderWithText5, new GridConstraints(12, 1, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label1 = new JLabel(); label1.setText("Fishing Loot Quality Multiplier"); panel1.add(label1, new GridConstraints(6, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label2 = new JLabel(); label2.setText("Supply Crate Loot Quality Multiplier"); panel1.add(label2, new GridConstraints(5, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label3 = new JLabel(); label3.setText("Platform Saddle Build Area Bounds Multiplier"); panel1.add(label3, new GridConstraints(9, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label4 = new JLabel(); label4.setText("Max Gateways on Saddles"); panel1.add(label4, new GridConstraints(10, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label5 = new JLabel(); label5.setText("Destroy Tames Over Level:"); panel1.add(label5, new GridConstraints(12, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel2 = new JPanel(); panel2.setLayout(new GridLayoutManager(3, 3, new Insets(0, 0, 0, 0), -1, -1)); panel1.add(panel2, new GridConstraints(11, 0, 1, 4, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel2.setBorder(BorderFactory.createTitledBorder(null, "Difficulty Ovveride", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); enableDifficultyOverrideCheckBox = new JCheckBox(); enableDifficultyOverrideCheckBox.setText("Enable Difficulty Override"); panel2.add(enableDifficultyOverrideCheckBox, new GridConstraints(0, 0, 1, 2, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label6 = new JLabel(); label6.setText("Max Dino Level:"); panel2.add(label6, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText6 = new SliderWithText(); panel2.add(sliderWithText6, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label7 = new JLabel(); label7.setText("levels"); panel2.add(label7, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label8 = new JLabel(); label8.setText("Difficulty Offset:"); panel2.add(label8, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText7 = new SliderWithText(); panel2.add(sliderWithText7, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label9 = new JLabel(); label9.setText("x"); panel1.add(label9, new GridConstraints(5, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label10 = new JLabel(); label10.setText("x"); panel1.add(label10, new GridConstraints(6, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label11 = new JLabel(); label11.setText("x"); panel1.add(label11, new GridConstraints(9, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label12 = new JLabel(); label12.setText("levels"); panel1.add(label12, new GridConstraints(12, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); enablePvECaveBuildingCheckBox = new JCheckBox(); enablePvECaveBuildingCheckBox.setText("Enable PvE Cave Building"); panel1.add(enablePvECaveBuildingCheckBox, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel3 = new JPanel(); panel3.setLayout(new GridLayoutManager(3, 3, new Insets(0, 0, 0, 0), -1, -1)); panel1.add(panel3, new GridConstraints(13, 0, 1, 4, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel3.setBorder(BorderFactory.createTitledBorder(null, "Tribute Downloads Options", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); enableTributeDownloadsCheckBox = new JCheckBox(); enableTributeDownloadsCheckBox.setText("Enable Tribute Downloads"); panel3.add(enableTributeDownloadsCheckBox, new GridConstraints(0, 0, 1, 3, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); noSurvivorDownloadsCheckBox = new JCheckBox(); noSurvivorDownloadsCheckBox.setText("No Survivor Downloads"); panel3.add(noSurvivorDownloadsCheckBox, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); noItemDownloadsCheckBox = new JCheckBox(); noItemDownloadsCheckBox.setText("No Item Downloads"); panel3.add(noItemDownloadsCheckBox, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 1, false)); noDinoDownloadsCheckBox = new JCheckBox(); noDinoDownloadsCheckBox.setText("No Dino Downloads"); panel3.add(noDinoDownloadsCheckBox, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); allowForeignsDinoDownloadsCheckBox = new JCheckBox(); allowForeignsDinoDownloadsCheckBox.setText("Allow Foreigns Dino Downloads"); panel3.add(allowForeignsDinoDownloadsCheckBox, new GridConstraints(2, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel4 = new JPanel(); panel4.setLayout(new GridLayoutManager(3, 4, new Insets(0, 0, 0, 0), -1, -1)); panel1.add(panel4, new GridConstraints(14, 0, 1, 4, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel4.setBorder(BorderFactory.createTitledBorder(null, "Tribute Uploads Options", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); noSurvivorUploadsCheckBox = new JCheckBox(); noSurvivorUploadsCheckBox.setText("No Survivor Uploads"); panel4.add(noSurvivorUploadsCheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); noItemUploadsCheckBox = new JCheckBox(); noItemUploadsCheckBox.setText("No Item Uploads"); panel4.add(noItemUploadsCheckBox, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); noDinoUploadsCheckBox = new JCheckBox(); noDinoUploadsCheckBox.setText("No Dino Uploads"); panel4.add(noDinoUploadsCheckBox, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label13 = new JLabel(); label13.setText("Max Tribute Dinos"); panel4.add(label13, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText8 = new SliderWithText(); panel4.add(sliderWithText8, new GridConstraints(1, 1, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label14 = new JLabel(); label14.setText("Max Tribute Items"); panel4.add(label14, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText9 = new SliderWithText(); panel4.add(sliderWithText9, new GridConstraints(2, 1, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label15 = new JLabel(); label15.setText("dinos"); panel4.add(label15, new GridConstraints(1, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label16 = new JLabel(); label16.setText("items"); panel4.add(label16, new GridConstraints(2, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel5 = new JPanel(); panel5.setLayout(new GridLayoutManager(5, 3, new Insets(0, 0, 0, 0), -1, -1)); panel1.add(panel5, new GridConstraints(15, 0, 1, 4, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel5.setBorder(BorderFactory.createTitledBorder(null, "Cluster Tribute Options", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); noTransferFromFilteringCheckBox = new JCheckBox(); noTransferFromFilteringCheckBox.setText("No Transfer from Filtering"); panel5.add(noTransferFromFilteringCheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final Spacer spacer1 = new Spacer(); panel5.add(spacer1, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); final JLabel label17 = new JLabel(); label17.setText("Override Survivor Upload Expiration"); panel5.add(label17, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText10 = new SliderWithText(); panel5.add(sliderWithText10, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label18 = new JLabel(); label18.setText("minutes"); panel5.add(label18, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label19 = new JLabel(); label19.setText("Override Item Upload Expiration"); panel5.add(label19, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText11 = new SliderWithText(); panel5.add(sliderWithText11, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label20 = new JLabel(); label20.setText("minutes"); panel5.add(label20, new GridConstraints(2, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label21 = new JLabel(); label21.setText("Override Dino Upload Expiration"); panel5.add(label21, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText12 = new SliderWithText(); panel5.add(sliderWithText12, new GridConstraints(3, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label22 = new JLabel(); label22.setText("minutes"); panel5.add(label22, new GridConstraints(3, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label23 = new JLabel(); label23.setText("Override Minimum Dino Re-upload Interval"); panel5.add(label23, new GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText13 = new SliderWithText(); panel5.add(sliderWithText13, new GridConstraints(4, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label24 = new JLabel(); label24.setText("minutes"); panel5.add(label24, new GridConstraints(4, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel6 = new JPanel(); panel6.setLayout(new GridLayoutManager(4, 3, new Insets(0, 0, 0, 0), -1, -1)); panel1.add(panel6, new GridConstraints(16, 0, 1, 4, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel6.setBorder(BorderFactory.createTitledBorder(null, "PvP Respawn Options", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); final JLabel label25 = new JLabel(); label25.setText("Interval Check Period"); panel6.add(label25, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText14 = new SliderWithText(); panel6.add(sliderWithText14, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label26 = new JLabel(); label26.setText("seconds"); panel6.add(label26, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label27 = new JLabel(); label27.setText("Interval Multiplier:"); panel6.add(label27, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText15 = new SliderWithText(); panel6.add(sliderWithText15, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label28 = new JLabel(); label28.setText("x"); panel6.add(label28, new GridConstraints(2, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label29 = new JLabel(); label29.setText("Interval Base Amount:"); panel6.add(label29, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText16 = new SliderWithText(); panel6.add(sliderWithText16, new GridConstraints(3, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label30 = new JLabel(); label30.setText("seconds"); panel6.add(label30, new GridConstraints(3, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); increasePvPRespawnIntervalCheckBox = new JCheckBox(); increasePvPRespawnIntervalCheckBox.setText("Increase PvP Respawn Interval"); panel6.add(increasePvPRespawnIntervalCheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel7 = new JPanel(); panel7.setLayout(new GridLayoutManager(3, 3, new Insets(0, 0, 0, 0), -1, -1)); panel1.add(panel7, new GridConstraints(17, 0, 1, 4, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel7.setBorder(BorderFactory.createTitledBorder(null, "PvP Offline Options", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); preventOfflinePvPCheckBox = new JCheckBox(); preventOfflinePvPCheckBox.setText("Prevent Offline PvP"); panel7.add(preventOfflinePvPCheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final Spacer spacer2 = new Spacer(); panel7.add(spacer2, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); final JLabel label31 = new JLabel(); label31.setText("Logout Interval"); panel7.add(label31, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText17 = new SliderWithText(); panel7.add(sliderWithText17, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label32 = new JLabel(); label32.setText("seconds"); panel7.add(label32, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label33 = new JLabel(); label33.setText("Connection Invincible Interval"); panel7.add(label33, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText18 = new SliderWithText(); panel7.add(sliderWithText18, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label34 = new JLabel(); label34.setText("seconds"); panel7.add(label34, new GridConstraints(2, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel8 = new JPanel(); panel8.setLayout(new GridLayoutManager(2, 5, new Insets(0, 0, 0, 0), -1, -1)); panel1.add(panel8, new GridConstraints(18, 0, 1, 4, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel8.setBorder(BorderFactory.createTitledBorder(null, "PvE Schedule", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); enablePvEScheduleCheckBox = new JCheckBox(); enablePvEScheduleCheckBox.setText("Enable PvE Schedule"); panel8.add(enablePvEScheduleCheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); useServerTimeCheckBox = new JCheckBox(); useServerTimeCheckBox.setText("Use Server Time"); panel8.add(useServerTimeCheckBox, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label35 = new JLabel(); label35.setText("Start Time"); panel8.add(label35, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label36 = new JLabel(); label36.setText("Stop Time"); panel8.add(label36, new GridConstraints(1, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel9 = new JPanel(); panel9.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1)); panel8.add(panel9, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
final TimeField timeField1 = new TimeField();
4
2023-11-07 19:36:49+00:00
16k
By1337/BAuction
Core/src/main/java/org/by1337/bauction/action/BuyItemProcess.java
[ { "identifier": "Main", "path": "Core/src/main/java/org/by1337/bauction/Main.java", "snippet": "public final class Main extends JavaPlugin {\n private static Message message;\n private static Plugin instance;\n private static Config cfg;\n private static FileDataBase storage;\n private Co...
import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.by1337.api.chat.Placeholderable; import org.by1337.bauction.Main; import org.by1337.bauction.auc.SellItem; import org.by1337.bauction.auc.User; import org.by1337.bauction.db.event.BuyItemEvent; import org.by1337.bauction.db.kernel.MysqlDb; import org.by1337.bauction.lang.Lang; import org.by1337.bauction.menu.Menu; import org.by1337.bauction.menu.impl.CallBack; import org.by1337.bauction.menu.impl.ConfirmMenu; import org.by1337.bauction.network.out.PlayOutSendMessagePacket; import org.by1337.bauction.util.PlayerUtil; import org.jetbrains.annotations.NotNull; import java.util.Optional;
14,157
package org.by1337.bauction.action; public class BuyItemProcess implements Placeholderable { private final SellItem buyingItem; private final User buyer; private final Menu menu; private final Player player; private final boolean fast; public BuyItemProcess(@NotNull SellItem buyingItem, @NotNull User buyer, Menu menu, Player player) { this(buyingItem, buyer, menu,player, false); } public BuyItemProcess(@NotNull SellItem buyingItem, @NotNull User buyer, Menu menu, Player player, boolean fast) { this.buyingItem = buyingItem; this.buyer = buyer; this.menu = menu; this.player = player; this.fast = fast; } public void process() { try { // if (Main.getEcon().getBalance(player) < buyingItem.getPrice()) { // Main.getMessage().sendMsg(player, Lang.getMessages("insufficient_balance")); // menu.reopen(); // return; // }
package org.by1337.bauction.action; public class BuyItemProcess implements Placeholderable { private final SellItem buyingItem; private final User buyer; private final Menu menu; private final Player player; private final boolean fast; public BuyItemProcess(@NotNull SellItem buyingItem, @NotNull User buyer, Menu menu, Player player) { this(buyingItem, buyer, menu,player, false); } public BuyItemProcess(@NotNull SellItem buyingItem, @NotNull User buyer, Menu menu, Player player, boolean fast) { this.buyingItem = buyingItem; this.buyer = buyer; this.menu = menu; this.player = player; this.fast = fast; } public void process() { try { // if (Main.getEcon().getBalance(player) < buyingItem.getPrice()) { // Main.getMessage().sendMsg(player, Lang.getMessages("insufficient_balance")); // menu.reopen(); // return; // }
CallBack<Optional<ConfirmMenu.Result>> callBack = result -> {
8
2023-11-08 18:25:18+00:00
16k
YufiriaMazenta/CrypticLib
nms/src/main/java/crypticlib/nms/item/ItemFactory.java
[ { "identifier": "CrypticLib", "path": "common/src/main/java/crypticlib/CrypticLib.java", "snippet": "public class CrypticLib {\n\n\n private static final CommandManager commandManager;\n private static final PermissionManager permissionManager;\n private static IPlatform platform;\n private ...
import crypticlib.CrypticLib; import crypticlib.function.TernaryFunction; import crypticlib.nms.item.v1_12_R1.V1_12_R1NbtItem; import crypticlib.nms.item.v1_13_R1.V1_13_R1NbtItem; import crypticlib.nms.item.v1_13_R2.V1_13_R2NbtItem; import crypticlib.nms.item.v1_14_R1.V1_14_R1NbtItem; import crypticlib.nms.item.v1_15_R1.V1_15_R1NbtItem; import crypticlib.nms.item.v1_16_R1.V1_16_R1NbtItem; import crypticlib.nms.item.v1_16_R2.V1_16_R2NbtItem; import crypticlib.nms.item.v1_16_R3.V1_16_R3NbtItem; import crypticlib.nms.item.v1_17_R1.V1_17_R1NbtItem; import crypticlib.nms.item.v1_18_R1.V1_18_R1NbtItem; import crypticlib.nms.item.v1_18_R2.V1_18_R2NbtItem; import crypticlib.nms.item.v1_19_R1.V1_19_R1NbtItem; import crypticlib.nms.item.v1_19_R2.V1_19_R2NbtItem; import crypticlib.nms.item.v1_19_R3.V1_19_R3NbtItem; import crypticlib.nms.item.v1_20_R1.V1_20_R1NbtItem; import crypticlib.nms.item.v1_20_R2.V1_20_R2NbtItem; import crypticlib.nms.item.v1_20_R3.V1_20_R3NbtItem; import crypticlib.nms.nbt.NbtFactory; import crypticlib.nms.nbt.NbtTagCompound; import crypticlib.util.MaterialUtil; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.inventory.ItemStack; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiFunction; import java.util.function.Function;
13,295
package crypticlib.nms.item; /** * CrypticLib的物品提供工厂 */ public class ItemFactory { private static final Map<String, Function<ItemStack, NbtItem>> nbtItemProviderMap1; private static final Map<String, BiFunction<Material, NbtTagCompound, NbtItem>> nbtItemProviderMap2; private static final Map<String, TernaryFunction<Material, NbtTagCompound, Integer, NbtItem>> nbtItemProviderMap3; static { nbtItemProviderMap1 = new ConcurrentHashMap<>(); nbtItemProviderMap2 = new ConcurrentHashMap<>(); nbtItemProviderMap3 = new ConcurrentHashMap<>(); regNbtItemProvider("v1_12_R1", V1_12_R1NbtItem::new, V1_12_R1NbtItem::new, V1_12_R1NbtItem::new); regNbtItemProvider("v1_13_R1", V1_13_R1NbtItem::new, V1_13_R1NbtItem::new, V1_13_R1NbtItem::new); regNbtItemProvider("v1_13_R2", V1_13_R2NbtItem::new, V1_13_R2NbtItem::new, V1_13_R2NbtItem::new); regNbtItemProvider("v1_14_R1", V1_14_R1NbtItem::new, V1_14_R1NbtItem::new, V1_14_R1NbtItem::new); regNbtItemProvider("v1_15_R1", V1_15_R1NbtItem::new, V1_15_R1NbtItem::new, V1_15_R1NbtItem::new); regNbtItemProvider("v1_16_R1", V1_16_R1NbtItem::new, V1_16_R1NbtItem::new, V1_16_R1NbtItem::new); regNbtItemProvider("v1_16_R2", V1_16_R2NbtItem::new, V1_16_R2NbtItem::new, V1_16_R2NbtItem::new); regNbtItemProvider("v1_16_R3", V1_16_R3NbtItem::new, V1_16_R3NbtItem::new, V1_16_R3NbtItem::new); regNbtItemProvider("v1_17_R1", V1_17_R1NbtItem::new, V1_17_R1NbtItem::new, V1_17_R1NbtItem::new); regNbtItemProvider("v1_18_R1", V1_18_R1NbtItem::new, V1_18_R1NbtItem::new, V1_18_R1NbtItem::new); regNbtItemProvider("v1_18_R2", V1_18_R2NbtItem::new, V1_18_R2NbtItem::new, V1_18_R2NbtItem::new); regNbtItemProvider("v1_19_R1", V1_19_R1NbtItem::new, V1_19_R1NbtItem::new, V1_19_R1NbtItem::new); regNbtItemProvider("v1_19_R2", V1_19_R2NbtItem::new, V1_19_R2NbtItem::new, V1_19_R2NbtItem::new); regNbtItemProvider("v1_19_R3", V1_19_R3NbtItem::new, V1_19_R3NbtItem::new, V1_19_R3NbtItem::new); regNbtItemProvider("v1_20_R1", V1_20_R1NbtItem::new, V1_20_R1NbtItem::new, V1_20_R1NbtItem::new); regNbtItemProvider("v1_20_R2", V1_20_R2NbtItem::new, V1_20_R2NbtItem::new, V1_20_R2NbtItem::new);
package crypticlib.nms.item; /** * CrypticLib的物品提供工厂 */ public class ItemFactory { private static final Map<String, Function<ItemStack, NbtItem>> nbtItemProviderMap1; private static final Map<String, BiFunction<Material, NbtTagCompound, NbtItem>> nbtItemProviderMap2; private static final Map<String, TernaryFunction<Material, NbtTagCompound, Integer, NbtItem>> nbtItemProviderMap3; static { nbtItemProviderMap1 = new ConcurrentHashMap<>(); nbtItemProviderMap2 = new ConcurrentHashMap<>(); nbtItemProviderMap3 = new ConcurrentHashMap<>(); regNbtItemProvider("v1_12_R1", V1_12_R1NbtItem::new, V1_12_R1NbtItem::new, V1_12_R1NbtItem::new); regNbtItemProvider("v1_13_R1", V1_13_R1NbtItem::new, V1_13_R1NbtItem::new, V1_13_R1NbtItem::new); regNbtItemProvider("v1_13_R2", V1_13_R2NbtItem::new, V1_13_R2NbtItem::new, V1_13_R2NbtItem::new); regNbtItemProvider("v1_14_R1", V1_14_R1NbtItem::new, V1_14_R1NbtItem::new, V1_14_R1NbtItem::new); regNbtItemProvider("v1_15_R1", V1_15_R1NbtItem::new, V1_15_R1NbtItem::new, V1_15_R1NbtItem::new); regNbtItemProvider("v1_16_R1", V1_16_R1NbtItem::new, V1_16_R1NbtItem::new, V1_16_R1NbtItem::new); regNbtItemProvider("v1_16_R2", V1_16_R2NbtItem::new, V1_16_R2NbtItem::new, V1_16_R2NbtItem::new); regNbtItemProvider("v1_16_R3", V1_16_R3NbtItem::new, V1_16_R3NbtItem::new, V1_16_R3NbtItem::new); regNbtItemProvider("v1_17_R1", V1_17_R1NbtItem::new, V1_17_R1NbtItem::new, V1_17_R1NbtItem::new); regNbtItemProvider("v1_18_R1", V1_18_R1NbtItem::new, V1_18_R1NbtItem::new, V1_18_R1NbtItem::new); regNbtItemProvider("v1_18_R2", V1_18_R2NbtItem::new, V1_18_R2NbtItem::new, V1_18_R2NbtItem::new); regNbtItemProvider("v1_19_R1", V1_19_R1NbtItem::new, V1_19_R1NbtItem::new, V1_19_R1NbtItem::new); regNbtItemProvider("v1_19_R2", V1_19_R2NbtItem::new, V1_19_R2NbtItem::new, V1_19_R2NbtItem::new); regNbtItemProvider("v1_19_R3", V1_19_R3NbtItem::new, V1_19_R3NbtItem::new, V1_19_R3NbtItem::new); regNbtItemProvider("v1_20_R1", V1_20_R1NbtItem::new, V1_20_R1NbtItem::new, V1_20_R1NbtItem::new); regNbtItemProvider("v1_20_R2", V1_20_R2NbtItem::new, V1_20_R2NbtItem::new, V1_20_R2NbtItem::new);
regNbtItemProvider("v1_20_R3", V1_20_R3NbtItem::new, V1_20_R3NbtItem::new, V1_20_R3NbtItem::new);
18
2023-11-07 12:39:20+00:00
16k
txline0420/nacos-dm
plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/dm/ConfigInfoMapperByDm.java
[ { "identifier": "NamespaceUtil", "path": "common/src/main/java/com/alibaba/nacos/common/utils/NamespaceUtil.java", "snippet": "public class NamespaceUtil {\n\n private NamespaceUtil() {\n }\n \n private static final String NAMESPACE_PUBLIC_KEY = \"public\";\n \n /**\n * public id,默...
import com.alibaba.nacos.common.utils.NamespaceUtil; import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant; import com.alibaba.nacos.plugin.datasource.mapper.AbstractMapper; import com.alibaba.nacos.plugin.datasource.mapper.ConfigInfoMapper; import java.sql.Timestamp; import java.util.Map;
14,252
/* * Copyright 1999-2022 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.nacos.plugin.datasource.impl.dm; /** * The DM implementation of ConfigInfoMapper. * * @author TXLINE **/ public class ConfigInfoMapperByDm extends AbstractMapper implements ConfigInfoMapper { private static final String DATA_ID = "dataId"; private static final String GROUP = "group"; private static final String APP_NAME = "appName"; private static final String CONTENT = "content"; private static final String TENANT = "tenant"; @Override public String findConfigInfoByAppFetchRows(int startRow, int pageSize) { return "SELECT id,data_id,group_id,tenant_id,app_name,content FROM config_info" + " WHERE tenant_id LIKE ? AND app_name= ?" + " LIMIT " + startRow + "," + pageSize; } @Override public String getTenantIdList(int startRow, int pageSize) {
/* * Copyright 1999-2022 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.nacos.plugin.datasource.impl.dm; /** * The DM implementation of ConfigInfoMapper. * * @author TXLINE **/ public class ConfigInfoMapperByDm extends AbstractMapper implements ConfigInfoMapper { private static final String DATA_ID = "dataId"; private static final String GROUP = "group"; private static final String APP_NAME = "appName"; private static final String CONTENT = "content"; private static final String TENANT = "tenant"; @Override public String findConfigInfoByAppFetchRows(int startRow, int pageSize) { return "SELECT id,data_id,group_id,tenant_id,app_name,content FROM config_info" + " WHERE tenant_id LIKE ? AND app_name= ?" + " LIMIT " + startRow + "," + pageSize; } @Override public String getTenantIdList(int startRow, int pageSize) {
return "SELECT tenant_id FROM config_info WHERE tenant_id != '" + NamespaceUtil.getNamespaceDefaultId()
0
2023-11-02 01:34:09+00:00
16k
ynwynw/oaSystemPublic
src/main/java/cn/gson/oasys/controller/attendce/AttendceController.java
[ { "identifier": "StringtoDate", "path": "src/main/java/cn/gson/oasys/common/StringtoDate.java", "snippet": "@Configuration\npublic class StringtoDate implements Converter<String, Date> {\n\n\t SimpleDateFormat sdf=new SimpleDateFormat();\n\t private List<String> patterns = new ArrayList<>();\n\t \...
import java.net.InetAddress; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.ibatis.annotations.Param; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import ch.qos.logback.core.joran.action.IADataForComplexProperty; import ch.qos.logback.core.net.SyslogOutputStream; import cn.gson.oasys.common.StringtoDate; import cn.gson.oasys.model.dao.attendcedao.AttendceDao; import cn.gson.oasys.model.dao.attendcedao.AttendceService; import cn.gson.oasys.model.dao.system.StatusDao; import cn.gson.oasys.model.dao.system.TypeDao; import cn.gson.oasys.model.dao.user.UserDao; import cn.gson.oasys.model.dao.user.UserService; import cn.gson.oasys.model.entity.attendce.Attends; import cn.gson.oasys.model.entity.system.SystemStatusList; import cn.gson.oasys.model.entity.system.SystemTypeList; import cn.gson.oasys.model.entity.user.User;
13,360
@RequestParam(value = "page", defaultValue = "0") int page, @RequestParam(value = "baseKey", required = false) String baseKey, @RequestParam(value = "type", required = false) String type, @RequestParam(value = "status", required = false) String status, @RequestParam(value = "time", required = false) String time, @RequestParam(value = "icon", required = false) String icon,Model model) { allsortpaging(request, session, page, baseKey, type, status, time, icon, model); return "attendce/attendceview"; } // 分頁分页 @RequestMapping("attendcetable") public String table(HttpServletRequest request, HttpSession session, @RequestParam(value = "page", defaultValue = "0") int page, @RequestParam(value = "baseKey", required = false) String baseKey, @RequestParam(value = "type", required = false) String type, @RequestParam(value = "status", required = false) String status, @RequestParam(value = "time", required = false) String time, @RequestParam(value = "icon", required = false) String icon,Model model) { allsortpaging(request, session, page, baseKey, type, status, time, icon, model); return "attendce/attendcetable"; } // 删除 @RequestMapping("attdelete") public String dsfa(HttpServletRequest request, HttpSession session) { long aid = Long.valueOf(request.getParameter("aid")); attendceService.delete(aid); return "redirect:/attendceatt"; } // 月报表 @RequestMapping("attendcemonth") public String test2(HttpServletRequest request, Model model, HttpSession session, @RequestParam(value = "page", defaultValue = "0") int page, @RequestParam(value = "baseKey", required = false) String baseKey) { monthtablepaging(request, model, session, page, baseKey); return "attendce/monthtable"; } @RequestMapping("realmonthtable") public String dfshe(HttpServletRequest request, Model model, HttpSession session, @RequestParam(value = "page", defaultValue = "0") int page, @RequestParam(value = "baseKey", required = false) String baseKey) { monthtablepaging(request, model, session, page, baseKey); return "attendce/realmonthtable"; } // 周报表 @RequestMapping("attendceweek") public String test3(HttpServletRequest request, HttpSession session, @RequestParam(value = "page", defaultValue = "0") int page, @RequestParam(value = "baseKey", required = false) String baseKey) { weektablepaging(request, session, page, baseKey); return "attendce/weektable"; } @RequestMapping("realweektable") public String dsaf(HttpServletRequest request, HttpSession session, @RequestParam(value = "page", defaultValue = "0") int page, @RequestParam(value = "baseKey", required = false) String baseKey) { weektablepaging(request, session, page, baseKey); return "attendce/realweektable"; } @RequestMapping("attendceedit") public String test4(@Param("aid") String aid, Model model,HttpServletRequest request, HttpSession session) { Long userid = Long.valueOf(session.getAttribute("userId") + ""); if (aid == null) { model.addAttribute("write", 0); } else if (aid != null) { long id = Long.valueOf(aid); Attends attends = attenceDao.findOne(id); model.addAttribute("write", 1); model.addAttribute("attends", attends); } typestatus(request); return "attendce/attendceedit"; } @RequestMapping("attendceedit2") public String DSAGen(HttpServletRequest request) { long id = Long.valueOf(request.getParameter("id")); Attends attends = attenceDao.findOne(id); request.setAttribute("attends", attends); typestatus(request); return "attendce/attendceedit2"; } @RequestMapping(value = "attendcesave", method = RequestMethod.GET) public void Datadf() { } // 修改保存 @RequestMapping(value = "attendcesave", method = RequestMethod.POST) public String test4(Model model, HttpSession session, HttpServletRequest request) { Long userid = Long.parseLong(session.getAttribute("userId") + ""); String remark = request.getParameter("remark"); String statusname=request.getParameter("status"); SystemStatusList statusList= statusDao.findByStatusModelAndStatusName("aoa_attends_list", statusname); long id = Long.parseLong(request.getParameter("id")); Attends attends=attenceDao.findOne(id); attends.setAttendsRemark(remark); attends.setStatusId(statusList.getStatusId()); attenceDao.save(attends); //attendceService.updatereamrk(remark, id); return "redirect:/attendceatt"; } // 状态类型方法 private void typestatus(HttpServletRequest request) {
package cn.gson.oasys.controller.attendce; @Controller @RequestMapping("/") public class AttendceController { Logger log = LoggerFactory.getLogger(getClass()); @Autowired AttendceDao attenceDao; @Autowired AttendceService attendceService; @Autowired UserDao uDao; @Autowired UserService userService; @Autowired TypeDao typeDao; @Autowired StatusDao statusDao; List<Attends> alist; List<User> uList; Date start,end; String month_; // 格式转化导入 DefaultConversionService service = new DefaultConversionService(); // 考勤 前面的签到 @RequestMapping("singin") public String Datag(HttpSession session, Model model, HttpServletRequest request) throws InterruptedException, UnknownHostException { //首先获取ip InetAddress ia=null; ia=ia.getLocalHost(); String attendip=ia.getHostAddress(); // 时间规范 String start = "08:00:00", end = "17:00:00"; service.addConverter(new StringtoDate()); // 状态默认是正常 long typeId, statusId = 10; Attends attends = null; Long userId = Long.parseLong(session.getAttribute("userId") + ""); User user = uDao.findOne(userId); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(); String nowdate = sdf.format(date); // 星期 判断该日期是星期几 SimpleDateFormat sdf3 = new SimpleDateFormat("EEEE"); // 截取时分 SimpleDateFormat sdf4 = new SimpleDateFormat("HH:mm"); // 截取时分秒 SimpleDateFormat sdf5 = new SimpleDateFormat("HH:mm:ss"); // 一周当中的星期几 String weekofday = sdf3.format(date); // 时分 String hourmin = sdf4.format(date); // 时分秒 String hourminsec = sdf5.format(date); //System.out.println("星期" + weekofday + "时分" + hourmin + "时分秒" + hourminsec); //System.out.println(date); Long aid = null; // 查找用户当天的所有记录 Integer count = attenceDao.countrecord(nowdate, userId); if (hourminsec.compareTo(end) > 0) { // 在17之后签到无效 System.out.println("----不能签到"); model.addAttribute("error", "1"); } if(hourminsec.compareTo("05:00:00") <0){ //在凌晨5点之前不能签到 System.out.println("----不能签到"); model.addAttribute("error", "2"); } else if((hourminsec.compareTo("05:00:00") >0)&&(hourminsec.compareTo(end) <0)){ // 明确一点就是一个用户一天只能产生两条记录 if (count == 0) { if (hourminsec.compareTo(end) < 0) { // 没有找到当天的记录就表示此次点击是上班 就是用来判断该记录的类型 // 上班id8 typeId = 8; // 上班就只有迟到和正常 if (hourminsec.compareTo(start) > 0) { // 迟于规定时间 迟到 statusId = 11; } else if (hourminsec.compareTo(start) < 0) { statusId = 10; } attends = new Attends(typeId, statusId, date, hourmin, weekofday, attendip, user); attenceDao.save(attends); } } if (count == 1) { // 找到当天的一条记录就表示此次点击是下班 // 下班id9 typeId = 9; // 下班就只有早退和正常 if (hourminsec.compareTo(end) > 0) { // 在规定时间晚下班正常 statusId = 10; } else if (hourminsec.compareTo(end) < 0) { // 在规定时间早下班早退 statusId = 12; } attends = new Attends(typeId, statusId, date, hourmin, weekofday, attendip, user); attenceDao.save(attends); } if (count >= 2) { // 已经是下班的状态了 大于2就是修改考勤时间了 // 下班id9 if (hourminsec.compareTo(end) > 0) { // 最进一次签到在规定时间晚下班正常 statusId = 10; } else if (hourminsec.compareTo(end) < 0) { // 最进一次签到在规定时间早下班早退 statusId = 12; } aid = attenceDao.findoffworkid(nowdate, userId); Attends attends2=attenceDao.findOne(aid); attends2.setAttendsIp(attendip); attenceDao.save(attends2); attendceService.updatetime(date, hourmin, statusId, aid); Attends aList = attenceDao.findlastest(nowdate, userId); } } // 显示用户当天最新的记录 Attends aList = attenceDao.findlastest(nowdate, userId); if (aList != null) { String type = typeDao.findname(aList.getTypeId()); model.addAttribute("type", type); } model.addAttribute("alist", aList); return "systemcontrol/signin"; } // 考情列表 给单个用户使用 @RequestMapping(value="attendcelist",method=RequestMethod.GET) public String test(HttpServletRequest request, Model model,HttpSession session, @RequestParam(value = "page", defaultValue = "0") int page, @RequestParam(value = "baseKey", required = false) String baseKey, @RequestParam(value = "type", required = false) String type, @RequestParam(value = "status", required = false) String status, @RequestParam(value = "time", required = false) String time, @RequestParam(value = "icon", required = false) String icon) { signsortpaging(request, model, session, page, null, type, status, time, icon); return "attendce/attendcelist"; } @RequestMapping(value="attendcelisttable",method=RequestMethod.GET) public String testdf(HttpServletRequest request, Model model,HttpSession session, @RequestParam(value = "page", defaultValue = "0") int page, @RequestParam(value = "baseKey", required = false) String baseKey, @RequestParam(value = "type", required = false) String type, @RequestParam(value = "status", required = false) String status, @RequestParam(value = "time", required = false) String time, @RequestParam(value = "icon", required = false) String icon) { signsortpaging(request, model, session, page, baseKey, type, status, time, icon); return "attendce/attendcelisttable"; } // 考勤管理某个管理员下面的所有员工的信息 @RequestMapping("attendceatt") public String testdasf(HttpServletRequest request, HttpSession session, @RequestParam(value = "page", defaultValue = "0") int page, @RequestParam(value = "baseKey", required = false) String baseKey, @RequestParam(value = "type", required = false) String type, @RequestParam(value = "status", required = false) String status, @RequestParam(value = "time", required = false) String time, @RequestParam(value = "icon", required = false) String icon,Model model) { allsortpaging(request, session, page, baseKey, type, status, time, icon, model); return "attendce/attendceview"; } // 分頁分页 @RequestMapping("attendcetable") public String table(HttpServletRequest request, HttpSession session, @RequestParam(value = "page", defaultValue = "0") int page, @RequestParam(value = "baseKey", required = false) String baseKey, @RequestParam(value = "type", required = false) String type, @RequestParam(value = "status", required = false) String status, @RequestParam(value = "time", required = false) String time, @RequestParam(value = "icon", required = false) String icon,Model model) { allsortpaging(request, session, page, baseKey, type, status, time, icon, model); return "attendce/attendcetable"; } // 删除 @RequestMapping("attdelete") public String dsfa(HttpServletRequest request, HttpSession session) { long aid = Long.valueOf(request.getParameter("aid")); attendceService.delete(aid); return "redirect:/attendceatt"; } // 月报表 @RequestMapping("attendcemonth") public String test2(HttpServletRequest request, Model model, HttpSession session, @RequestParam(value = "page", defaultValue = "0") int page, @RequestParam(value = "baseKey", required = false) String baseKey) { monthtablepaging(request, model, session, page, baseKey); return "attendce/monthtable"; } @RequestMapping("realmonthtable") public String dfshe(HttpServletRequest request, Model model, HttpSession session, @RequestParam(value = "page", defaultValue = "0") int page, @RequestParam(value = "baseKey", required = false) String baseKey) { monthtablepaging(request, model, session, page, baseKey); return "attendce/realmonthtable"; } // 周报表 @RequestMapping("attendceweek") public String test3(HttpServletRequest request, HttpSession session, @RequestParam(value = "page", defaultValue = "0") int page, @RequestParam(value = "baseKey", required = false) String baseKey) { weektablepaging(request, session, page, baseKey); return "attendce/weektable"; } @RequestMapping("realweektable") public String dsaf(HttpServletRequest request, HttpSession session, @RequestParam(value = "page", defaultValue = "0") int page, @RequestParam(value = "baseKey", required = false) String baseKey) { weektablepaging(request, session, page, baseKey); return "attendce/realweektable"; } @RequestMapping("attendceedit") public String test4(@Param("aid") String aid, Model model,HttpServletRequest request, HttpSession session) { Long userid = Long.valueOf(session.getAttribute("userId") + ""); if (aid == null) { model.addAttribute("write", 0); } else if (aid != null) { long id = Long.valueOf(aid); Attends attends = attenceDao.findOne(id); model.addAttribute("write", 1); model.addAttribute("attends", attends); } typestatus(request); return "attendce/attendceedit"; } @RequestMapping("attendceedit2") public String DSAGen(HttpServletRequest request) { long id = Long.valueOf(request.getParameter("id")); Attends attends = attenceDao.findOne(id); request.setAttribute("attends", attends); typestatus(request); return "attendce/attendceedit2"; } @RequestMapping(value = "attendcesave", method = RequestMethod.GET) public void Datadf() { } // 修改保存 @RequestMapping(value = "attendcesave", method = RequestMethod.POST) public String test4(Model model, HttpSession session, HttpServletRequest request) { Long userid = Long.parseLong(session.getAttribute("userId") + ""); String remark = request.getParameter("remark"); String statusname=request.getParameter("status"); SystemStatusList statusList= statusDao.findByStatusModelAndStatusName("aoa_attends_list", statusname); long id = Long.parseLong(request.getParameter("id")); Attends attends=attenceDao.findOne(id); attends.setAttendsRemark(remark); attends.setStatusId(statusList.getStatusId()); attenceDao.save(attends); //attendceService.updatereamrk(remark, id); return "redirect:/attendceatt"; } // 状态类型方法 private void typestatus(HttpServletRequest request) {
List<SystemTypeList> type = (List<SystemTypeList>) typeDao.findByTypeModel("aoa_attends_list");
9
2023-11-03 02:08:22+00:00
16k
firstdarkdev/modfusioner
src/main/java/com/hypherionmc/modfusioner/task/JarFuseTask.java
[ { "identifier": "Constants", "path": "src/main/java/com/hypherionmc/modfusioner/Constants.java", "snippet": "public class Constants {\n\n public static final String TASK_GROUP = \"modfusioner\";\n public static final String TASK_NAME = \"fusejars\";\n public static final String EXTENSION_NAME =...
import com.hypherionmc.modfusioner.Constants; import com.hypherionmc.modfusioner.actions.JarMergeAction; import com.hypherionmc.modfusioner.plugin.FusionerExtension; import com.hypherionmc.modfusioner.plugin.ModFusionerPlugin; import com.hypherionmc.modfusioner.utils.FileChecks; import com.hypherionmc.modfusioner.utils.FileTools; import org.apache.commons.io.FileUtils; import org.gradle.api.Project; import org.gradle.api.internal.file.copy.CopyAction; import org.gradle.api.tasks.WorkResults; import org.gradle.jvm.tasks.Jar; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import static com.hypherionmc.modfusioner.plugin.ModFusionerPlugin.modFusionerExtension; import static com.hypherionmc.modfusioner.plugin.ModFusionerPlugin.rootProject;
13,504
/* * This file is part of ModFusioner, licensed under the GNU Lesser General Public License v2.1. * * This project is based on, and contains code from https://github.com/PacifistMC/Forgix, licensed under the same license. * See their license here: https://github.com/PacifistMC/Forgix/blob/main/LICENSE * * Copyright HypherionSA and Contributors * Forgix Code Copyright by their contributors and Ran-Mewo */ package com.hypherionmc.modfusioner.task; /** * @author HypherionSA * The main task of the plugin */ public class JarFuseTask extends Jar { // Fixed values private final File mergedJar; private static final AtomicBoolean hasRun = new AtomicBoolean(false); public JarFuseTask() { // Set task default values from extension getArchiveBaseName().set(modFusionerExtension.getMergedJarName()); getArchiveVersion().set(modFusionerExtension.getJarVersion()); getDestinationDirectory().set(getProject().file(modFusionerExtension.getOutputDirectory())); // We don't allow custom input files, when the user defines their own task getInputs().files(); // Only allow the task to run once per cycle getOutputs().upToDateWhen(spec -> hasRun.get()); // Set output file mergedJar = new File(getDestinationDirectory().get().getAsFile(), getArchiveFileName().get()); getOutputs().file(mergedJar); } /** * Main task logic * @throws IOException - Thrown when an IO error occurs */ void fuseJars() throws IOException { long time = System.currentTimeMillis();
/* * This file is part of ModFusioner, licensed under the GNU Lesser General Public License v2.1. * * This project is based on, and contains code from https://github.com/PacifistMC/Forgix, licensed under the same license. * See their license here: https://github.com/PacifistMC/Forgix/blob/main/LICENSE * * Copyright HypherionSA and Contributors * Forgix Code Copyright by their contributors and Ran-Mewo */ package com.hypherionmc.modfusioner.task; /** * @author HypherionSA * The main task of the plugin */ public class JarFuseTask extends Jar { // Fixed values private final File mergedJar; private static final AtomicBoolean hasRun = new AtomicBoolean(false); public JarFuseTask() { // Set task default values from extension getArchiveBaseName().set(modFusionerExtension.getMergedJarName()); getArchiveVersion().set(modFusionerExtension.getJarVersion()); getDestinationDirectory().set(getProject().file(modFusionerExtension.getOutputDirectory())); // We don't allow custom input files, when the user defines their own task getInputs().files(); // Only allow the task to run once per cycle getOutputs().upToDateWhen(spec -> hasRun.get()); // Set output file mergedJar = new File(getDestinationDirectory().get().getAsFile(), getArchiveFileName().get()); getOutputs().file(mergedJar); } /** * Main task logic * @throws IOException - Thrown when an IO error occurs */ void fuseJars() throws IOException { long time = System.currentTimeMillis();
ModFusionerPlugin.logger.lifecycle("Start Fusing Jars");
3
2023-11-03 23:19:08+00:00
16k
data-harness-cloud/data_harness-be
common/common-core/src/main/java/supie/common/core/object/MyGroupParam.java
[ { "identifier": "CoreProperties", "path": "common/common-core/src/main/java/supie/common/core/config/CoreProperties.java", "snippet": "@Data\n@Configuration\n@ConfigurationProperties(prefix = \"common-core\")\npublic class CoreProperties {\n\n public static final String MYSQL_TYPE = \"mysql\";\n p...
import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.StrUtil; import supie.common.core.config.CoreProperties; import supie.common.core.constant.ApplicationConstant; import supie.common.core.exception.InvalidClassFieldException; import supie.common.core.exception.InvalidDataFieldException; import supie.common.core.exception.InvalidDataModelException; import supie.common.core.util.ApplicationContextHolder; import supie.common.core.util.MyModelUtil; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.extern.slf4j.Slf4j; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.LinkedList; import java.util.List;
13,833
package supie.common.core.object; /** * 查询分组参数请求对象。 * * @author rm -rf .bug * @date 2020-11-12 */ @EqualsAndHashCode(callSuper = true) @Slf4j @Data public class MyGroupParam extends ArrayList<MyGroupParam.GroupInfo> {
package supie.common.core.object; /** * 查询分组参数请求对象。 * * @author rm -rf .bug * @date 2020-11-12 */ @EqualsAndHashCode(callSuper = true) @Slf4j @Data public class MyGroupParam extends ArrayList<MyGroupParam.GroupInfo> {
private final transient CoreProperties coreProperties =
0
2023-11-04 12:36:44+00:00
16k
FTC-ORBIT/14872-2024-CenterStage
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/SampleMecanumDrive.java
[ { "identifier": "TrajectorySequence", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/trajectorysequence/TrajectorySequence.java", "snippet": "public class TrajectorySequence {\n private final List<SequenceSegment> sequenceList;\n\n public TrajectorySequence(List<SequenceSegment> se...
import androidx.annotation.NonNull; import com.acmerobotics.dashboard.config.Config; import com.acmerobotics.roadrunner.control.PIDCoefficients; import com.acmerobotics.roadrunner.drive.DriveSignal; import com.acmerobotics.roadrunner.drive.MecanumDrive; import com.acmerobotics.roadrunner.followers.HolonomicPIDVAFollower; import com.acmerobotics.roadrunner.followers.TrajectoryFollower; import com.acmerobotics.roadrunner.geometry.Pose2d; import com.acmerobotics.roadrunner.trajectory.Trajectory; import com.acmerobotics.roadrunner.trajectory.TrajectoryBuilder; import com.acmerobotics.roadrunner.trajectory.constraints.AngularVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MecanumVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MinVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.ProfileAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryVelocityConstraint; import com.qualcomm.hardware.lynx.LynxModule; import com.qualcomm.hardware.rev.RevHubOrientationOnRobot; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorEx; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.IMU; import com.qualcomm.robotcore.hardware.PIDFCoefficients; import com.qualcomm.robotcore.hardware.VoltageSensor; import com.qualcomm.robotcore.hardware.configuration.typecontainers.MotorConfigurationType; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequence; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceBuilder; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceRunner; import org.firstinspires.ftc.teamcode.util.LynxModuleUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MOTOR_VELO_PID; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.RUN_USING_ENCODER; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.TRACK_WIDTH; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.encoderTicksToInches; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kA; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kStatic; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kV;
11,644
package org.firstinspires.ftc.teamcode.drive; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config public class SampleMecanumDrive extends MecanumDrive { public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(7, 0, 2); public static PIDCoefficients HEADING_PID = new PIDCoefficients(5, 0, 1); public static double LATERAL_MULTIPLIER = 1.7; public static double VX_WEIGHT = 1; public static double VY_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner; private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(MAX_VEL, MAX_ANG_VEL, TRACK_WIDTH); private static final TrajectoryAccelerationConstraint ACCEL_CONSTRAINT = getAccelerationConstraint(MAX_ACCEL); private TrajectoryFollower follower; private DcMotorEx leftFront, leftRear, rightRear, rightFront; private List<DcMotorEx> motors; private IMU imu; private VoltageSensor batteryVoltageSensor; private List<Integer> lastEncPositions = new ArrayList<>(); private List<Integer> lastEncVels = new ArrayList<>(); public SampleMecanumDrive(HardwareMap hardwareMap) { super(kV, kA, kStatic, TRACK_WIDTH, TRACK_WIDTH, LATERAL_MULTIPLIER); follower = new HolonomicPIDVAFollower(TRANSLATIONAL_PID, TRANSLATIONAL_PID, HEADING_PID, new Pose2d(0.5, 0.5, Math.toRadians(5.0)), 0.5); LynxModuleUtil.ensureMinimumFirmwareVersion(hardwareMap); batteryVoltageSensor = hardwareMap.voltageSensor.iterator().next(); for (LynxModule module : hardwareMap.getAll(LynxModule.class)) { module.setBulkCachingMode(LynxModule.BulkCachingMode.AUTO); } // TODO: adjust the names of the following hardware devices to match your configuration imu = hardwareMap.get(IMU.class, "imu"); IMU.Parameters parameters = new IMU.Parameters(new RevHubOrientationOnRobot( DriveConstants.LOGO_FACING_DIR, DriveConstants.USB_FACING_DIR)); imu.initialize(parameters); leftFront = hardwareMap.get(DcMotorEx.class, "lf"); leftRear = hardwareMap.get(DcMotorEx.class, "lb"); rightRear = hardwareMap.get(DcMotorEx.class, "rb"); rightFront = hardwareMap.get(DcMotorEx.class, "rf"); motors = Arrays.asList(leftFront, leftRear, rightRear, rightFront); for (DcMotorEx motor : motors) { MotorConfigurationType motorConfigurationType = motor.getMotorType().clone(); motorConfigurationType.setAchieveableMaxRPMFraction(1.0); motor.setMotorType(motorConfigurationType); } if (RUN_USING_ENCODER) { setMode(DcMotor.RunMode.RUN_USING_ENCODER); } setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); if (RUN_USING_ENCODER && MOTOR_VELO_PID != null) { setPIDFCoefficients(DcMotor.RunMode.RUN_USING_ENCODER, MOTOR_VELO_PID); } // TODO: reverse any motors using DcMotor.setDirection() leftFront.setDirection(DcMotorSimple.Direction.REVERSE); leftRear.setDirection(DcMotorSimple.Direction.REVERSE); List<Integer> lastTrackingEncPositions = new ArrayList<>(); List<Integer> lastTrackingEncVels = new ArrayList<>(); // TODO: if desired, use setLocalizer() to change the localization method // setLocalizer(new StandardTrackingWheelLocalizer(hardwareMap, lastTrackingEncPositions, lastTrackingEncVels)); setLocalizer(new TwoWheelTrackingLocalizer(hardwareMap, this)); trajectorySequenceRunner = new TrajectorySequenceRunner( follower, HEADING_PID, batteryVoltageSensor, lastEncPositions, lastEncVels, lastTrackingEncPositions, lastTrackingEncVels ); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose) { return new TrajectoryBuilder(startPose, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, boolean reversed) { return new TrajectoryBuilder(startPose, reversed, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, double startHeading) { return new TrajectoryBuilder(startPose, startHeading, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectorySequenceBuilder trajectorySequenceBuilder(Pose2d startPose) { return new TrajectorySequenceBuilder( startPose, VEL_CONSTRAINT, ACCEL_CONSTRAINT,
package org.firstinspires.ftc.teamcode.drive; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config public class SampleMecanumDrive extends MecanumDrive { public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(7, 0, 2); public static PIDCoefficients HEADING_PID = new PIDCoefficients(5, 0, 1); public static double LATERAL_MULTIPLIER = 1.7; public static double VX_WEIGHT = 1; public static double VY_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner; private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(MAX_VEL, MAX_ANG_VEL, TRACK_WIDTH); private static final TrajectoryAccelerationConstraint ACCEL_CONSTRAINT = getAccelerationConstraint(MAX_ACCEL); private TrajectoryFollower follower; private DcMotorEx leftFront, leftRear, rightRear, rightFront; private List<DcMotorEx> motors; private IMU imu; private VoltageSensor batteryVoltageSensor; private List<Integer> lastEncPositions = new ArrayList<>(); private List<Integer> lastEncVels = new ArrayList<>(); public SampleMecanumDrive(HardwareMap hardwareMap) { super(kV, kA, kStatic, TRACK_WIDTH, TRACK_WIDTH, LATERAL_MULTIPLIER); follower = new HolonomicPIDVAFollower(TRANSLATIONAL_PID, TRANSLATIONAL_PID, HEADING_PID, new Pose2d(0.5, 0.5, Math.toRadians(5.0)), 0.5); LynxModuleUtil.ensureMinimumFirmwareVersion(hardwareMap); batteryVoltageSensor = hardwareMap.voltageSensor.iterator().next(); for (LynxModule module : hardwareMap.getAll(LynxModule.class)) { module.setBulkCachingMode(LynxModule.BulkCachingMode.AUTO); } // TODO: adjust the names of the following hardware devices to match your configuration imu = hardwareMap.get(IMU.class, "imu"); IMU.Parameters parameters = new IMU.Parameters(new RevHubOrientationOnRobot( DriveConstants.LOGO_FACING_DIR, DriveConstants.USB_FACING_DIR)); imu.initialize(parameters); leftFront = hardwareMap.get(DcMotorEx.class, "lf"); leftRear = hardwareMap.get(DcMotorEx.class, "lb"); rightRear = hardwareMap.get(DcMotorEx.class, "rb"); rightFront = hardwareMap.get(DcMotorEx.class, "rf"); motors = Arrays.asList(leftFront, leftRear, rightRear, rightFront); for (DcMotorEx motor : motors) { MotorConfigurationType motorConfigurationType = motor.getMotorType().clone(); motorConfigurationType.setAchieveableMaxRPMFraction(1.0); motor.setMotorType(motorConfigurationType); } if (RUN_USING_ENCODER) { setMode(DcMotor.RunMode.RUN_USING_ENCODER); } setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); if (RUN_USING_ENCODER && MOTOR_VELO_PID != null) { setPIDFCoefficients(DcMotor.RunMode.RUN_USING_ENCODER, MOTOR_VELO_PID); } // TODO: reverse any motors using DcMotor.setDirection() leftFront.setDirection(DcMotorSimple.Direction.REVERSE); leftRear.setDirection(DcMotorSimple.Direction.REVERSE); List<Integer> lastTrackingEncPositions = new ArrayList<>(); List<Integer> lastTrackingEncVels = new ArrayList<>(); // TODO: if desired, use setLocalizer() to change the localization method // setLocalizer(new StandardTrackingWheelLocalizer(hardwareMap, lastTrackingEncPositions, lastTrackingEncVels)); setLocalizer(new TwoWheelTrackingLocalizer(hardwareMap, this)); trajectorySequenceRunner = new TrajectorySequenceRunner( follower, HEADING_PID, batteryVoltageSensor, lastEncPositions, lastEncVels, lastTrackingEncPositions, lastTrackingEncVels ); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose) { return new TrajectoryBuilder(startPose, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, boolean reversed) { return new TrajectoryBuilder(startPose, reversed, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, double startHeading) { return new TrajectoryBuilder(startPose, startHeading, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectorySequenceBuilder trajectorySequenceBuilder(Pose2d startPose) { return new TrajectorySequenceBuilder( startPose, VEL_CONSTRAINT, ACCEL_CONSTRAINT,
MAX_ANG_VEL, MAX_ANG_ACCEL
5
2023-11-03 13:32:48+00:00
16k
beminder/BeautyMinder
java/src/main/java/app/beautyminder/service/RecommendService.java
[ { "identifier": "Cosmetic", "path": "java/src/main/java/app/beautyminder/domain/Cosmetic.java", "snippet": "@Document(collection = \"cosmetics\") // mongodb\n@AllArgsConstructor\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\n@Getter\n@Builder\npublic class Cosmetic {\n\n @Id\n private String...
import app.beautyminder.domain.Cosmetic; import app.beautyminder.domain.Review; import app.beautyminder.domain.User; import app.beautyminder.repository.CosmeticRepository; import app.beautyminder.service.auth.UserService; import app.beautyminder.service.cosmetic.CosmeticRankService; import app.beautyminder.service.review.ReviewService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.bson.types.ObjectId; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.cache.annotation.Caching; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.aggregation.Aggregation; import org.springframework.data.mongodb.core.aggregation.AggregationResults; import org.springframework.data.mongodb.core.aggregation.MatchOperation; import org.springframework.data.mongodb.core.aggregation.SampleOperation; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.web.server.ResponseStatusException; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors;
12,367
package app.beautyminder.service; @Slf4j @RequiredArgsConstructor @Service public class RecommendService { private final CosmeticRankService cosmeticRankService; private final UserService userService; private final ReviewService reviewService; private final CosmeticRepository cosmeticRepository; private final MongoTemplate mongoTemplate; private final Integer MAX_MATCHING_KEYWORDS = 2; private static <T> T getByRandomClass(Set<T> set) { if (set == null || set.isEmpty()) { throw new IllegalArgumentException("The Set cannot be empty."); } int randomIndex = ThreadLocalRandom.current().nextInt(set.size()); return set.stream() .skip(randomIndex) .findFirst() .orElseThrow(() -> new IllegalStateException("Something went wrong while picking a random element.")); } @Caching( evict = {@CacheEvict(value = "productRecommendations", key = "#userHash", condition = "#forceRefresh", beforeInvocation = true)}, cacheable = {@Cacheable(value = "productRecommendations", key = "#userHash", condition = "!#forceRefresh", unless = "#result == null or #result.isEmpty()")}, put = {@CachePut(value = "productRecommendations", key = "#userHash", condition = "#forceRefresh")} )
package app.beautyminder.service; @Slf4j @RequiredArgsConstructor @Service public class RecommendService { private final CosmeticRankService cosmeticRankService; private final UserService userService; private final ReviewService reviewService; private final CosmeticRepository cosmeticRepository; private final MongoTemplate mongoTemplate; private final Integer MAX_MATCHING_KEYWORDS = 2; private static <T> T getByRandomClass(Set<T> set) { if (set == null || set.isEmpty()) { throw new IllegalArgumentException("The Set cannot be empty."); } int randomIndex = ThreadLocalRandom.current().nextInt(set.size()); return set.stream() .skip(randomIndex) .findFirst() .orElseThrow(() -> new IllegalStateException("Something went wrong while picking a random element.")); } @Caching( evict = {@CacheEvict(value = "productRecommendations", key = "#userHash", condition = "#forceRefresh", beforeInvocation = true)}, cacheable = {@Cacheable(value = "productRecommendations", key = "#userHash", condition = "!#forceRefresh", unless = "#result == null or #result.isEmpty()")}, put = {@CachePut(value = "productRecommendations", key = "#userHash", condition = "#forceRefresh")} )
public List<Cosmetic> recommendProducts(String userId, String userHash, boolean forceRefresh) {
0
2023-11-01 12:37:16+00:00
16k
FallenDeity/GameEngine2DJava
src/main/java/engine/components/QuestionBlock.java
[ { "identifier": "JImGui", "path": "src/main/java/engine/editor/JImGui.java", "snippet": "public class JImGui {\n\tpublic static void drawVec2Control(String name, Vector2f values) {\n\t\tdrawVec2Control(name, values, 0.0f);\n\t}\n\n\tpublic static void drawVec2Control(String name, Vector2f values, float ...
import engine.editor.JImGui; import engine.ruby.Window; import engine.util.Prefabs;
11,512
package engine.components; public class QuestionBlock extends Block { private int amount = 1; private BlockType type = BlockType.COIN; @Override public void imGui() {
package engine.components; public class QuestionBlock extends Block { private int amount = 1; private BlockType type = BlockType.COIN; @Override public void imGui() {
type = JImGui.comboEnum("Type", type);
0
2023-11-04 13:19:21+00:00
16k
RezaGooner/University-food-ordering
Frames/Admin/FoodManagment/OrdersManage.java
[ { "identifier": "icon", "path": "Classes/Pathes/FilesPath.java", "snippet": "public static ImageIcon icon = new ImageIcon(\"Source/icon.png\");\r" }, { "identifier": "errorSound", "path": "Classes/Theme/SoundEffect.java", "snippet": "public static void errorSound() throws IOException, Un...
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; import javax.swing.*; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableRowSorter; import static Classes.Pathes.FilesPath.icon; import static Classes.Theme.SoundEffect.errorSound; import static Frames.Order.UniversitySelfRestaurant.*;
12,097
package Frames.Admin.FoodManagment; /* این کد یک پنجره مدیریت سفارشات را ایجاد می‌کند. در این پنجره، admin می‌تواند سفارشات را مشاهده، اضافه، ویرایش، و حذف کند. برای این منظور، از یک JTable برای نمایش داده‌ها استفاده شده است. همچنین، از یک DefaultTableModel برای مدیریت داده‌ها، و از یک TableRowSorter برای مرتب‌سازی و جستجو در داده‌ها استفاده شده است. در متد سازنده، ابتدا آرایه‌هایی که شامل گزینه‌ها و قیمت‌های ناهار و شام هستند، ساخته می‌شوند. سپس، داده‌های موجود در فایل سفارشات خوانده می‌شوند و به جدول اضافه می‌شوند. در ادامه، پنلی برای جستجو، و سه دکمه برای اضافه کردن، ویرایش و حذف داده‌ها به پنجره اضافه می‌شوند. سپس، جدول، پنل جستجو، و دکمه‌ها به پنجره اضافه می‌شوند. در نهایت، تنظیمات جدول و پنجره انجام می‌شود و پنجره نمایش داده می‌شود. ````````````````````````````````````````````````````` This code defines an `OrdersManage` class that extends `JFrame` and is used to create a GUI application for managing food orders. Here's a breakdown of the code: - The `OrdersManage` constructor sets up the main components of the GUI. It sets the title of the application window and creates the table, table model, and row sorter for managing the orders. - The constructor reads the orders from a file and populates the table with the data. - It creates a search panel with a text field that allows users to filter the orders based on their input. - Buttons for adding, editing, and deleting orders are created and registered with action listeners to handle button click events. - The constructor also creates a menu bar with a "Refresh" menu item that allows users to refresh the orders. - The `saveToFile` method is used to save the orders to a file. - The `CreateDinnerArray` and `CreateLunchArray` methods are used to read the dinner and lunch options from files and populate the corresponding arrays. Please note that there are some dependencies in the code, such as `Classes.Pathes.FilesPath.icon`, `Classes.Theme. SoundEffect.errorSound`, `Frames.Order.UniversitySelfRestaurant.orderFilename`, `Frames.Order.UniversitySelfRestaurant. dinnerFilePath`, and `Frames.Order.UniversitySelfRestaurant.lunchFilePath`. You need to ensure that these dependencies are properly resolved and that the necessary files exist for the code to work correctly. */ public class OrdersManage extends JFrame { private JTable table; private DefaultTableModel tableModel; private List<String[]> data; private TableRowSorter<DefaultTableModel> sorter; private static String[] lunchOptions = new String[7]; private static int[] lunchPrices = new int[7]; private static String[] dinnerOptions = new String[7]; private static int[] dinnerPrices = new int[7]; public OrdersManage() throws IOException, UnsupportedAudioFileException, LineUnavailableException { super("سفارشات"); CreateDinnerArray(); CreateLunchArray(); data = new ArrayList<>(); try (BufferedReader br = new BufferedReader(new FileReader(new File(orderFilename)))) { String line; while ((line = br.readLine()) != null) { String[] parts = line.split(","); data.add(parts); } } catch (Exception e) {
package Frames.Admin.FoodManagment; /* این کد یک پنجره مدیریت سفارشات را ایجاد می‌کند. در این پنجره، admin می‌تواند سفارشات را مشاهده، اضافه، ویرایش، و حذف کند. برای این منظور، از یک JTable برای نمایش داده‌ها استفاده شده است. همچنین، از یک DefaultTableModel برای مدیریت داده‌ها، و از یک TableRowSorter برای مرتب‌سازی و جستجو در داده‌ها استفاده شده است. در متد سازنده، ابتدا آرایه‌هایی که شامل گزینه‌ها و قیمت‌های ناهار و شام هستند، ساخته می‌شوند. سپس، داده‌های موجود در فایل سفارشات خوانده می‌شوند و به جدول اضافه می‌شوند. در ادامه، پنلی برای جستجو، و سه دکمه برای اضافه کردن، ویرایش و حذف داده‌ها به پنجره اضافه می‌شوند. سپس، جدول، پنل جستجو، و دکمه‌ها به پنجره اضافه می‌شوند. در نهایت، تنظیمات جدول و پنجره انجام می‌شود و پنجره نمایش داده می‌شود. ````````````````````````````````````````````````````` This code defines an `OrdersManage` class that extends `JFrame` and is used to create a GUI application for managing food orders. Here's a breakdown of the code: - The `OrdersManage` constructor sets up the main components of the GUI. It sets the title of the application window and creates the table, table model, and row sorter for managing the orders. - The constructor reads the orders from a file and populates the table with the data. - It creates a search panel with a text field that allows users to filter the orders based on their input. - Buttons for adding, editing, and deleting orders are created and registered with action listeners to handle button click events. - The constructor also creates a menu bar with a "Refresh" menu item that allows users to refresh the orders. - The `saveToFile` method is used to save the orders to a file. - The `CreateDinnerArray` and `CreateLunchArray` methods are used to read the dinner and lunch options from files and populate the corresponding arrays. Please note that there are some dependencies in the code, such as `Classes.Pathes.FilesPath.icon`, `Classes.Theme. SoundEffect.errorSound`, `Frames.Order.UniversitySelfRestaurant.orderFilename`, `Frames.Order.UniversitySelfRestaurant. dinnerFilePath`, and `Frames.Order.UniversitySelfRestaurant.lunchFilePath`. You need to ensure that these dependencies are properly resolved and that the necessary files exist for the code to work correctly. */ public class OrdersManage extends JFrame { private JTable table; private DefaultTableModel tableModel; private List<String[]> data; private TableRowSorter<DefaultTableModel> sorter; private static String[] lunchOptions = new String[7]; private static int[] lunchPrices = new int[7]; private static String[] dinnerOptions = new String[7]; private static int[] dinnerPrices = new int[7]; public OrdersManage() throws IOException, UnsupportedAudioFileException, LineUnavailableException { super("سفارشات"); CreateDinnerArray(); CreateLunchArray(); data = new ArrayList<>(); try (BufferedReader br = new BufferedReader(new FileReader(new File(orderFilename)))) { String line; while ((line = br.readLine()) != null) { String[] parts = line.split(","); data.add(parts); } } catch (Exception e) {
errorSound();
1
2023-11-03 08:35:22+00:00
16k
cyljx9999/talktime-Java
talktime-framework/talktime-service/src/main/java/com/qingmeng/service/impl/FileServiceImpl.java
[ { "identifier": "FileAdapt", "path": "talktime-minio/src/main/java/com/qingmeng/adapt/FileAdapt.java", "snippet": "public class FileAdapt {\n\n\n /**\n * 构建 minio vo\n *\n * @param uploadUrl 上传网址\n * @param downloadUrl 下载网址\n * @return {@link MinioVO }\n * @author qingmeng\n...
import cn.hutool.core.util.RandomUtil; import cn.hutool.extra.qrcode.QrCodeUtil; import cn.hutool.extra.qrcode.QrConfig; import com.qingmeng.adapt.FileAdapt; import com.qingmeng.config.adapt.UserInfoAdapt; import com.qingmeng.config.cache.UserCache; import com.qingmeng.config.cache.UserFriendSettingCache; import com.qingmeng.constant.SystemConstant; import com.qingmeng.dao.SysUserDao; import com.qingmeng.dto.file.MinioDTO; import com.qingmeng.dto.file.ScanQrcodeDTO; import com.qingmeng.dto.file.UploadUrlDTO; import com.qingmeng.dto.login.CheckFriendDTO; import com.qingmeng.entity.SysUser; import com.qingmeng.entity.SysUserFriendSetting; import com.qingmeng.enums.system.ScanQrcodeEnum; import com.qingmeng.enums.system.UploadSceneEnum; import com.qingmeng.service.FileService; import com.qingmeng.service.MinioService; import com.qingmeng.service.SysUserFriendService; import com.qingmeng.utils.AssertUtils; import com.qingmeng.utils.CommonUtils; import com.qingmeng.vo.common.ScanQrcodeInfoVO; import com.qingmeng.vo.file.MinioVO; import com.qingmeng.vo.user.CheckFriendVO; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.io.File; import java.util.ArrayList; import java.util.Objects;
13,604
package com.qingmeng.service.impl; /** * @author 清梦 * @version 1.0.0 * @Description * @createTime 2023年12月05日 21:51:00 */ @Service public class FileServiceImpl implements FileService { @Resource private MinioService minioSerivce; @Resource private UserCache userCache; @Resource private SysUserDao sysUserDao; @Resource private SysUserFriendService sysUserFriendService; @Resource private UserFriendSettingCache userFriendSettingCache; /** * 获取二维码网址 * * @param userId 用户 ID * @return {@link String } * @author qingmeng * @createTime: 2023/12/05 21:59:23 */ @Override public String getQrcodeUrl(Long userId) { QrConfig config = new QrConfig(); config.setHeight(SystemConstant.QRCODE_HEIGHT); config.setWidth(SystemConstant.QRCODE_WIDTH); config.setImg(CommonUtils.getLogoImage()); File file = QrCodeUtil.generate( userId.toString(), config, new File(RandomUtil.randomString(10))); return minioSerivce.uploadFileByStream(userId, UploadSceneEnum.QRCODE.getType(), file); } /** * 获取预签名对象 URL * * @param userId 用户 ID * @param uploadUrlDTO 上传 URL DTO * @return {@link MinioVO } * @author qingmeng * @createTime: 2023/12/05 23:01:29 */ @Override public MinioVO getPreSignedObjectUrl(Long userId, UploadUrlDTO uploadUrlDTO) { MinioDTO minioDTO = FileAdapt.buildMinioDTO(userId, uploadUrlDTO); return minioSerivce.getPreSignedObjectUrl(minioDTO); } /** * 更新二维码网址 * * @param userId 用户 ID * @author qingmeng * @createTime: 2023/12/05 23:08:15 */ @Override @Transactional(rollbackFor = Exception.class) public void updateQrcodeUrl(Long userId) { String qrcodeUrl = getQrcodeUrl(userId); sysUserDao.updateQrcode(userId, qrcodeUrl); userCache.delete(userId); } /** * 扫描二维码信息 * * @param userId 用户 ID * @param scanQrcodeDTO 扫描二维码 DTO * @return {@link ScanQrcodeInfoVO }<{@link ? }> * @author qingmeng * @createTime: 2023/12/06 11:19:13 */ @Override public ScanQrcodeInfoVO<?> scanQrcodeInfo(Long userId,ScanQrcodeDTO scanQrcodeDTO) {
package com.qingmeng.service.impl; /** * @author 清梦 * @version 1.0.0 * @Description * @createTime 2023年12月05日 21:51:00 */ @Service public class FileServiceImpl implements FileService { @Resource private MinioService minioSerivce; @Resource private UserCache userCache; @Resource private SysUserDao sysUserDao; @Resource private SysUserFriendService sysUserFriendService; @Resource private UserFriendSettingCache userFriendSettingCache; /** * 获取二维码网址 * * @param userId 用户 ID * @return {@link String } * @author qingmeng * @createTime: 2023/12/05 21:59:23 */ @Override public String getQrcodeUrl(Long userId) { QrConfig config = new QrConfig(); config.setHeight(SystemConstant.QRCODE_HEIGHT); config.setWidth(SystemConstant.QRCODE_WIDTH); config.setImg(CommonUtils.getLogoImage()); File file = QrCodeUtil.generate( userId.toString(), config, new File(RandomUtil.randomString(10))); return minioSerivce.uploadFileByStream(userId, UploadSceneEnum.QRCODE.getType(), file); } /** * 获取预签名对象 URL * * @param userId 用户 ID * @param uploadUrlDTO 上传 URL DTO * @return {@link MinioVO } * @author qingmeng * @createTime: 2023/12/05 23:01:29 */ @Override public MinioVO getPreSignedObjectUrl(Long userId, UploadUrlDTO uploadUrlDTO) { MinioDTO minioDTO = FileAdapt.buildMinioDTO(userId, uploadUrlDTO); return minioSerivce.getPreSignedObjectUrl(minioDTO); } /** * 更新二维码网址 * * @param userId 用户 ID * @author qingmeng * @createTime: 2023/12/05 23:08:15 */ @Override @Transactional(rollbackFor = Exception.class) public void updateQrcodeUrl(Long userId) { String qrcodeUrl = getQrcodeUrl(userId); sysUserDao.updateQrcode(userId, qrcodeUrl); userCache.delete(userId); } /** * 扫描二维码信息 * * @param userId 用户 ID * @param scanQrcodeDTO 扫描二维码 DTO * @return {@link ScanQrcodeInfoVO }<{@link ? }> * @author qingmeng * @createTime: 2023/12/06 11:19:13 */ @Override public ScanQrcodeInfoVO<?> scanQrcodeInfo(Long userId,ScanQrcodeDTO scanQrcodeDTO) {
if (Objects.equals(scanQrcodeDTO.getScanType(), ScanQrcodeEnum.friend.getCode())) {
12
2023-11-07 16:04:55+00:00
16k
BaderTim/minecraft-measurement-mod
src/main/java/io/github/mmm/measurement/device/DeviceController.java
[ { "identifier": "MMM", "path": "src/main/java/io/github/mmm/MMM.java", "snippet": "@Mod(MMM.MODID)\npublic class MMM {\n // Define mod id in a common place for everything to reference\n public static final String MODID = \"mmm\";\n // Directly reference a slf4j logger\n public static final L...
import io.github.mmm.MMM; import io.github.mmm.measurement.device.objects.imu.IMU; import io.github.mmm.measurement.device.objects.imu.IMUController; import io.github.mmm.measurement.device.objects.lidar.LiDAR; import io.github.mmm.measurement.device.objects.lidar.LiDARController; import io.github.mmm.measurement.device.scans.ImuScan; import io.github.mmm.measurement.device.scans.LidarScan; import io.github.mmm.measurement.device.scans.LidarScan2D; import io.github.mmm.modconfig.Config; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.player.LocalPlayer; import net.minecraft.network.chat.Component; import java.awt.*; import java.nio.file.Files; import java.nio.file.Paths; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import static io.github.mmm.MMM.DEVICE_CONTROLLER; import static io.github.mmm.MMM.MMM_ROOT_PATH; import static io.github.mmm.Utils.saveStringToFile;
12,820
package io.github.mmm.measurement.device; public class DeviceController { private Boolean currentlyMeasuring; private int saveInterval; private String savePath; private boolean tickTimeWarning = false; private int tickTimeWarningTolerance;
package io.github.mmm.measurement.device; public class DeviceController { private Boolean currentlyMeasuring; private int saveInterval; private String savePath; private boolean tickTimeWarning = false; private int tickTimeWarningTolerance;
private LiDARController lidarController;
4
2023-11-06 16:56:46+00:00
16k
KilianCollins/road-runner-quickstart-master
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/SampleMecanumDrive.java
[ { "identifier": "MAX_ACCEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java", "snippet": "public static double MAX_ACCEL = 73.17330064499293;" }, { "identifier": "MAX_ANG_ACCEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/Dr...
import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MOTOR_VELO_PID; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.RUN_USING_ENCODER; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.TRACK_WIDTH; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.encoderTicksToInches; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kA; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kStatic; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kV; import androidx.annotation.NonNull; import com.acmerobotics.dashboard.config.Config; import com.acmerobotics.roadrunner.control.PIDCoefficients; import com.acmerobotics.roadrunner.drive.MecanumDrive; import com.acmerobotics.roadrunner.drive.DriveSignal; import com.acmerobotics.roadrunner.followers.HolonomicPIDVAFollower; import com.acmerobotics.roadrunner.followers.TrajectoryFollower; import com.acmerobotics.roadrunner.geometry.Pose2d; import com.acmerobotics.roadrunner.trajectory.Trajectory; import com.acmerobotics.roadrunner.trajectory.TrajectoryBuilder; import com.acmerobotics.roadrunner.trajectory.constraints.AngularVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MecanumVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MinVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.ProfileAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryVelocityConstraint; import com.qualcomm.hardware.lynx.LynxModule; import com.qualcomm.hardware.rev.RevHubOrientationOnRobot; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorEx; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.IMU; import com.qualcomm.robotcore.hardware.PIDFCoefficients; import com.qualcomm.robotcore.hardware.VoltageSensor; import com.qualcomm.robotcore.hardware.configuration.typecontainers.MotorConfigurationType; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequence; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceBuilder; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceRunner; import org.firstinspires.ftc.teamcode.util.LynxModuleUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
12,458
} public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, double startHeading) { return new TrajectoryBuilder(startPose, startHeading, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectorySequenceBuilder trajectorySequenceBuilder(Pose2d startPose) { return new TrajectorySequenceBuilder( startPose, VEL_CONSTRAINT, ACCEL_CONSTRAINT, MAX_ANG_VEL, MAX_ANG_ACCEL ); } public void turnAsync(double angle) { trajectorySequenceRunner.followTrajectorySequenceAsync( trajectorySequenceBuilder(getPoseEstimate()) .turn(angle) .build() ); } public void turn(double angle) { turnAsync(angle); waitForIdle(); } public void followTrajectoryAsync(Trajectory trajectory) { trajectorySequenceRunner.followTrajectorySequenceAsync( trajectorySequenceBuilder(trajectory.start()) .addTrajectory(trajectory) .build() ); } public void followTrajectory(Trajectory trajectory) { followTrajectoryAsync(trajectory); waitForIdle(); } public void followTrajectorySequenceAsync(TrajectorySequence trajectorySequence) { trajectorySequenceRunner.followTrajectorySequenceAsync(trajectorySequence); } public void followTrajectorySequence(TrajectorySequence trajectorySequence) { followTrajectorySequenceAsync(trajectorySequence); waitForIdle(); } public Pose2d getLastError() { return trajectorySequenceRunner.getLastPoseError(); } public void update() { updatePoseEstimate(); DriveSignal signal = trajectorySequenceRunner.update(getPoseEstimate(), getPoseVelocity()); if (signal != null) setDriveSignal(signal); } public void waitForIdle() { while (!Thread.currentThread().isInterrupted() && isBusy()) update(); } public boolean isBusy() { return trajectorySequenceRunner.isBusy(); } public void setMode(DcMotor.RunMode runMode) { for (DcMotorEx motor : motors) { motor.setMode(runMode); } } public void setZeroPowerBehavior(DcMotor.ZeroPowerBehavior zeroPowerBehavior) { for (DcMotorEx motor : motors) { motor.setZeroPowerBehavior(zeroPowerBehavior); } } public void setPIDFCoefficients(DcMotor.RunMode runMode, PIDFCoefficients coefficients) { PIDFCoefficients compensatedCoefficients = new PIDFCoefficients( coefficients.p, coefficients.i, coefficients.d, coefficients.f * 12 / batteryVoltageSensor.getVoltage() ); for (DcMotorEx motor : motors) { motor.setPIDFCoefficients(runMode, compensatedCoefficients); } } public void setWeightedDrivePower(Pose2d drivePower) { Pose2d vel = drivePower; if (Math.abs(drivePower.getX()) + Math.abs(drivePower.getY()) + Math.abs(drivePower.getHeading()) > 1) { // re-normalize the powers according to the weights double denom = VX_WEIGHT * Math.abs(drivePower.getX()) + VY_WEIGHT * Math.abs(drivePower.getY()) + OMEGA_WEIGHT * Math.abs(drivePower.getHeading()); vel = new Pose2d( VX_WEIGHT * drivePower.getX(), VY_WEIGHT * drivePower.getY(), OMEGA_WEIGHT * drivePower.getHeading() ).div(denom); } setDrivePower(vel); } @NonNull @Override public List<Double> getWheelPositions() { lastEncPositions.clear(); List<Double> wheelPositions = new ArrayList<>(); for (DcMotorEx motor : motors) { int position = motor.getCurrentPosition(); lastEncPositions.add(position);
package org.firstinspires.ftc.teamcode.drive; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config //@TeleOp(name="sample mechna drive ", group="Linear OpMode") public class SampleMecanumDrive extends MecanumDrive { public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(0, 0, 0); public static double LATERAL_MULTIPLIER = .4; public static double VX_WEIGHT = 1; public static double VY_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner; private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(MAX_VEL, MAX_ANG_VEL, TRACK_WIDTH); private static final TrajectoryAccelerationConstraint ACCEL_CONSTRAINT = getAccelerationConstraint(MAX_ACCEL); private TrajectoryFollower follower; private DcMotorEx leftFront, leftRear, rightRear, rightFront; private List<DcMotorEx> motors; private IMU imu; private VoltageSensor batteryVoltageSensor; private List<Integer> lastEncPositions = new ArrayList<>(); private List<Integer> lastEncVels = new ArrayList<>(); public SampleMecanumDrive(HardwareMap hardwareMap) { super(kV, kA, kStatic, TRACK_WIDTH, TRACK_WIDTH, LATERAL_MULTIPLIER); follower = new HolonomicPIDVAFollower(TRANSLATIONAL_PID, TRANSLATIONAL_PID, HEADING_PID, new Pose2d(0.5, 0.5, Math.toRadians(5.0)), 0.5); LynxModuleUtil.ensureMinimumFirmwareVersion(hardwareMap); batteryVoltageSensor = hardwareMap.voltageSensor.iterator().next(); for (LynxModule module : hardwareMap.getAll(LynxModule.class)) { module.setBulkCachingMode(LynxModule.BulkCachingMode.AUTO); } //current functioning rr as of 10/21// //////////////////////////////////////////////////////////////////////////////////////////////////// // TODO: adjust the names of the following hardware devices to match your configuration // imu = hardwareMap.get(IMU.class, "imu"); // IMU.Parameters parameters = new IMU.Parameters(new RevHubOrientationOnRobot( // DriveConstants.LOGO_FACING_DIR, DriveConstants.USB_FACING_DIR)); // imu.initialize(parameters); leftFront = hardwareMap.get(DcMotorEx.class, "leftFront"); leftRear = hardwareMap.get(DcMotorEx.class, "leftRear"); rightRear = hardwareMap.get(DcMotorEx.class, "rightRear"); rightFront = hardwareMap.get(DcMotorEx.class, "rightFront"); leftRear.setDirection(DcMotorSimple.Direction.REVERSE); leftFront.setDirection(DcMotorSimple.Direction.REVERSE); rightFront.setDirection(DcMotorSimple.Direction.FORWARD); rightRear.setDirection(DcMotorSimple.Direction.FORWARD); motors = Arrays.asList(leftFront, leftRear, rightRear, rightFront); for (DcMotorEx motor : motors) { MotorConfigurationType motorConfigurationType = motor.getMotorType().clone(); motorConfigurationType.setAchieveableMaxRPMFraction(1.0); motor.setMotorType(motorConfigurationType); } if (RUN_USING_ENCODER) { setMode(DcMotor.RunMode.RUN_USING_ENCODER); } setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); if (RUN_USING_ENCODER && MOTOR_VELO_PID != null) { setPIDFCoefficients(DcMotor.RunMode.RUN_USING_ENCODER, MOTOR_VELO_PID); } // TODO: reverse any motors using DcMotor.setDirection() List<Integer> lastTrackingEncPositions = new ArrayList<>(); List<Integer> lastTrackingEncVels = new ArrayList<>(); // TODO: if desired, use setLocalizer() to change the localization method setLocalizer(new StandardTrackingWheelLocalizer(hardwareMap, lastTrackingEncPositions, lastTrackingEncVels)); //setLocalizer(new StandardTrackingWheelLocalizer(hardwareMap)); trajectorySequenceRunner = new TrajectorySequenceRunner( follower, HEADING_PID, batteryVoltageSensor, lastEncPositions, lastEncVels, lastTrackingEncPositions, lastTrackingEncVels ); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose) { return new TrajectoryBuilder(startPose, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, boolean reversed) { return new TrajectoryBuilder(startPose, reversed, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, double startHeading) { return new TrajectoryBuilder(startPose, startHeading, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectorySequenceBuilder trajectorySequenceBuilder(Pose2d startPose) { return new TrajectorySequenceBuilder( startPose, VEL_CONSTRAINT, ACCEL_CONSTRAINT, MAX_ANG_VEL, MAX_ANG_ACCEL ); } public void turnAsync(double angle) { trajectorySequenceRunner.followTrajectorySequenceAsync( trajectorySequenceBuilder(getPoseEstimate()) .turn(angle) .build() ); } public void turn(double angle) { turnAsync(angle); waitForIdle(); } public void followTrajectoryAsync(Trajectory trajectory) { trajectorySequenceRunner.followTrajectorySequenceAsync( trajectorySequenceBuilder(trajectory.start()) .addTrajectory(trajectory) .build() ); } public void followTrajectory(Trajectory trajectory) { followTrajectoryAsync(trajectory); waitForIdle(); } public void followTrajectorySequenceAsync(TrajectorySequence trajectorySequence) { trajectorySequenceRunner.followTrajectorySequenceAsync(trajectorySequence); } public void followTrajectorySequence(TrajectorySequence trajectorySequence) { followTrajectorySequenceAsync(trajectorySequence); waitForIdle(); } public Pose2d getLastError() { return trajectorySequenceRunner.getLastPoseError(); } public void update() { updatePoseEstimate(); DriveSignal signal = trajectorySequenceRunner.update(getPoseEstimate(), getPoseVelocity()); if (signal != null) setDriveSignal(signal); } public void waitForIdle() { while (!Thread.currentThread().isInterrupted() && isBusy()) update(); } public boolean isBusy() { return trajectorySequenceRunner.isBusy(); } public void setMode(DcMotor.RunMode runMode) { for (DcMotorEx motor : motors) { motor.setMode(runMode); } } public void setZeroPowerBehavior(DcMotor.ZeroPowerBehavior zeroPowerBehavior) { for (DcMotorEx motor : motors) { motor.setZeroPowerBehavior(zeroPowerBehavior); } } public void setPIDFCoefficients(DcMotor.RunMode runMode, PIDFCoefficients coefficients) { PIDFCoefficients compensatedCoefficients = new PIDFCoefficients( coefficients.p, coefficients.i, coefficients.d, coefficients.f * 12 / batteryVoltageSensor.getVoltage() ); for (DcMotorEx motor : motors) { motor.setPIDFCoefficients(runMode, compensatedCoefficients); } } public void setWeightedDrivePower(Pose2d drivePower) { Pose2d vel = drivePower; if (Math.abs(drivePower.getX()) + Math.abs(drivePower.getY()) + Math.abs(drivePower.getHeading()) > 1) { // re-normalize the powers according to the weights double denom = VX_WEIGHT * Math.abs(drivePower.getX()) + VY_WEIGHT * Math.abs(drivePower.getY()) + OMEGA_WEIGHT * Math.abs(drivePower.getHeading()); vel = new Pose2d( VX_WEIGHT * drivePower.getX(), VY_WEIGHT * drivePower.getY(), OMEGA_WEIGHT * drivePower.getHeading() ).div(denom); } setDrivePower(vel); } @NonNull @Override public List<Double> getWheelPositions() { lastEncPositions.clear(); List<Double> wheelPositions = new ArrayList<>(); for (DcMotorEx motor : motors) { int position = motor.getCurrentPosition(); lastEncPositions.add(position);
wheelPositions.add(encoderTicksToInches(position));
7
2023-11-04 04:11:26+00:00
16k
conductor-oss/conductor
cassandra-persistence/src/main/java/com/netflix/conductor/cassandra/dao/CassandraEventHandlerDAO.java
[ { "identifier": "CassandraProperties", "path": "cassandra-persistence/src/main/java/com/netflix/conductor/cassandra/config/CassandraProperties.java", "snippet": "@ConfigurationProperties(\"conductor.cassandra\")\npublic class CassandraProperties {\n\n /** The address for the cassandra database host *...
import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.conductor.annotations.Trace; import com.netflix.conductor.cassandra.config.CassandraProperties; import com.netflix.conductor.cassandra.util.Statements; import com.netflix.conductor.common.metadata.events.EventHandler; import com.netflix.conductor.core.exception.TransientException; import com.netflix.conductor.dao.EventHandlerDAO; import com.netflix.conductor.metrics.Monitors; import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; import com.datastax.driver.core.Session; import com.datastax.driver.core.exceptions.DriverException; import com.fasterxml.jackson.databind.ObjectMapper; import static com.netflix.conductor.cassandra.util.Constants.EVENT_HANDLER_KEY; import static com.netflix.conductor.cassandra.util.Constants.HANDLERS_KEY;
12,992
/* * Copyright 2022 Conductor Authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.cassandra.dao; @Trace public class CassandraEventHandlerDAO extends CassandraBaseDAO implements EventHandlerDAO { private static final Logger LOGGER = LoggerFactory.getLogger(CassandraEventHandlerDAO.class); private static final String CLASS_NAME = CassandraEventHandlerDAO.class.getSimpleName(); private final PreparedStatement insertEventHandlerStatement; private final PreparedStatement selectAllEventHandlersStatement; private final PreparedStatement deleteEventHandlerStatement; public CassandraEventHandlerDAO( Session session, ObjectMapper objectMapper, CassandraProperties properties, Statements statements) { super(session, objectMapper, properties); insertEventHandlerStatement = session.prepare(statements.getInsertEventHandlerStatement()) .setConsistencyLevel(properties.getWriteConsistencyLevel()); selectAllEventHandlersStatement = session.prepare(statements.getSelectAllEventHandlersStatement()) .setConsistencyLevel(properties.getReadConsistencyLevel()); deleteEventHandlerStatement = session.prepare(statements.getDeleteEventHandlerStatement()) .setConsistencyLevel(properties.getWriteConsistencyLevel()); } @Override public void addEventHandler(EventHandler eventHandler) { insertOrUpdateEventHandler(eventHandler); } @Override public void updateEventHandler(EventHandler eventHandler) { insertOrUpdateEventHandler(eventHandler); } @Override public void removeEventHandler(String name) { try { recordCassandraDaoRequests("removeEventHandler"); session.execute(deleteEventHandlerStatement.bind(name)); } catch (Exception e) { Monitors.error(CLASS_NAME, "removeEventHandler"); String errorMsg = String.format("Failed to remove event handler: %s", name); LOGGER.error(errorMsg, e);
/* * Copyright 2022 Conductor Authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.cassandra.dao; @Trace public class CassandraEventHandlerDAO extends CassandraBaseDAO implements EventHandlerDAO { private static final Logger LOGGER = LoggerFactory.getLogger(CassandraEventHandlerDAO.class); private static final String CLASS_NAME = CassandraEventHandlerDAO.class.getSimpleName(); private final PreparedStatement insertEventHandlerStatement; private final PreparedStatement selectAllEventHandlersStatement; private final PreparedStatement deleteEventHandlerStatement; public CassandraEventHandlerDAO( Session session, ObjectMapper objectMapper, CassandraProperties properties, Statements statements) { super(session, objectMapper, properties); insertEventHandlerStatement = session.prepare(statements.getInsertEventHandlerStatement()) .setConsistencyLevel(properties.getWriteConsistencyLevel()); selectAllEventHandlersStatement = session.prepare(statements.getSelectAllEventHandlersStatement()) .setConsistencyLevel(properties.getReadConsistencyLevel()); deleteEventHandlerStatement = session.prepare(statements.getDeleteEventHandlerStatement()) .setConsistencyLevel(properties.getWriteConsistencyLevel()); } @Override public void addEventHandler(EventHandler eventHandler) { insertOrUpdateEventHandler(eventHandler); } @Override public void updateEventHandler(EventHandler eventHandler) { insertOrUpdateEventHandler(eventHandler); } @Override public void removeEventHandler(String name) { try { recordCassandraDaoRequests("removeEventHandler"); session.execute(deleteEventHandlerStatement.bind(name)); } catch (Exception e) { Monitors.error(CLASS_NAME, "removeEventHandler"); String errorMsg = String.format("Failed to remove event handler: %s", name); LOGGER.error(errorMsg, e);
throw new TransientException(errorMsg, e);
3
2023-12-08 06:06:09+00:00
16k
kaifangqian/open-sign
src/main/java/com/resrun/controller/OpenSignController.java
[ { "identifier": "SignTypeEnum", "path": "src/main/java/com/resrun/enums/SignTypeEnum.java", "snippet": "public enum SignTypeEnum {\n\n\n POSITION(1,\"位置签署\"),\n KEYWORD(2,\"关键字签署\"),\n\n ;\n\n private String msg;\n private Integer code;\n\n\n SignTypeEnum(Integer code,String msg){\n ...
import com.resrun.enums.SignTypeEnum; import com.resrun.service.pojo.CertificateProperty; import com.resrun.service.pojo.GenerateCertificateInfo; import com.resrun.service.pojo.RealPositionProperty; import com.resrun.service.pojo.SourcePositionProperty; import com.resrun.service.cert.CertService; import com.resrun.service.image.EntSealClipService; import com.resrun.service.image.EntSealGenerateService; import com.resrun.service.pdf.CalculatePositionService; import com.resrun.service.pdf.SignService; import com.resrun.service.verify.SignVerifyService; import com.resrun.utils.Base64; import com.resrun.controller.vo.base.Result; import com.resrun.controller.vo.request.*; import com.resrun.controller.vo.response.SealResponse; import com.resrun.controller.vo.response.SignResponse; import com.resrun.controller.vo.response.VerifyResponse; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.pdfbox.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.util.ResourceUtils; import org.springframework.web.bind.annotation.*; import java.io.*; import java.util.ArrayList; import java.util.List;
13,465
package com.resrun.controller; /** * @Description: OpenSignController * @Package: com.resrun.controller * @ClassName: OpenSignController * @copyright 北京资源律动科技有限公司 */ @Api(tags = "开放签-演示demo") @RestController public class OpenSignController { @Autowired private SignVerifyService signVerifyService ; @Autowired private CalculatePositionService calculatePositionService ; @Autowired private SignService signService ; @Autowired private EntSealGenerateService entSealGenerateService ; @Autowired private EntSealClipService entSealClipService ; @Autowired private CertService certService ; @ApiOperation("生成企业签章-上传生成") @RequestMapping(value = "/clip/seal",method = RequestMethod.POST)
package com.resrun.controller; /** * @Description: OpenSignController * @Package: com.resrun.controller * @ClassName: OpenSignController * @copyright 北京资源律动科技有限公司 */ @Api(tags = "开放签-演示demo") @RestController public class OpenSignController { @Autowired private SignVerifyService signVerifyService ; @Autowired private CalculatePositionService calculatePositionService ; @Autowired private SignService signService ; @Autowired private EntSealGenerateService entSealGenerateService ; @Autowired private EntSealClipService entSealClipService ; @Autowired private CertService certService ; @ApiOperation("生成企业签章-上传生成") @RequestMapping(value = "/clip/seal",method = RequestMethod.POST)
public Result<SealResponse> generateUpload(@RequestBody ClipSealRequest request){
12
2023-12-14 06:53:32+00:00
16k
Mahmud0808/ColorBlendr
app/src/main/java/com/drdisagree/colorblendr/utils/FragmentUtil.java
[ { "identifier": "AboutFragment", "path": "app/src/main/java/com/drdisagree/colorblendr/ui/fragments/AboutFragment.java", "snippet": "public class AboutFragment extends Fragment {\n\n private FragmentAboutBinding binding;\n\n @Override\n public View onCreateView(@NonNull LayoutInflater inflater,...
import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import com.drdisagree.colorblendr.R; import com.drdisagree.colorblendr.ui.fragments.AboutFragment; import com.drdisagree.colorblendr.ui.fragments.ColorsFragment; import com.drdisagree.colorblendr.ui.fragments.PerAppThemeFragment; import com.drdisagree.colorblendr.ui.fragments.SettingsFragment; import com.drdisagree.colorblendr.ui.fragments.StylesFragment; import com.drdisagree.colorblendr.ui.fragments.ThemeFragment;
12,455
package com.drdisagree.colorblendr.utils; public class FragmentUtil { public enum TAB_SELECTION { FROM_LEFT_TO_RIGHT, FROM_RIGHT_TO_LEFT, NONE } public static TAB_SELECTION getSlidingDirection(Fragment currentFragment, Fragment newFragment) { if (currentFragment == null) { return TAB_SELECTION.NONE; } TAB_SELECTION direction; if (isInGroup1(currentFragment) && !isInGroup1(newFragment)) { direction = TAB_SELECTION.FROM_LEFT_TO_RIGHT; } else if (isInGroup4(currentFragment) && !isInGroup4(newFragment)) { direction = TAB_SELECTION.FROM_RIGHT_TO_LEFT; } else if (isInGroup2(currentFragment)) { if (isInGroup1(newFragment)) { direction = TAB_SELECTION.FROM_RIGHT_TO_LEFT; } else if (isInGroup3(newFragment) || isInGroup4(newFragment)) { direction = TAB_SELECTION.FROM_LEFT_TO_RIGHT; } else { return TAB_SELECTION.NONE; } } else if (isInGroup3(currentFragment)) { if (isInGroup4(newFragment)) { direction = TAB_SELECTION.FROM_LEFT_TO_RIGHT; } else if (isInGroup1(newFragment) || isInGroup2(newFragment)) { direction = TAB_SELECTION.FROM_RIGHT_TO_LEFT; } else { return TAB_SELECTION.NONE; } } else { return TAB_SELECTION.NONE; } return direction; } public static void setCustomAnimations(TAB_SELECTION direction, FragmentTransaction fragmentTransaction) { switch (direction) { case FROM_LEFT_TO_RIGHT -> fragmentTransaction.setCustomAnimations( R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right ); case FROM_RIGHT_TO_LEFT -> fragmentTransaction.setCustomAnimations( R.anim.slide_in_left, R.anim.slide_out_right, R.anim.slide_in_right, R.anim.slide_out_left ); case NONE -> fragmentTransaction.setCustomAnimations( R.anim.fade_in, R.anim.fade_out, R.anim.fade_in, R.anim.fade_out ); } } private static boolean isInGroup1(Fragment fragment) { return fragment instanceof ColorsFragment || fragment instanceof PerAppThemeFragment; } private static boolean isInGroup2(Fragment fragment) {
package com.drdisagree.colorblendr.utils; public class FragmentUtil { public enum TAB_SELECTION { FROM_LEFT_TO_RIGHT, FROM_RIGHT_TO_LEFT, NONE } public static TAB_SELECTION getSlidingDirection(Fragment currentFragment, Fragment newFragment) { if (currentFragment == null) { return TAB_SELECTION.NONE; } TAB_SELECTION direction; if (isInGroup1(currentFragment) && !isInGroup1(newFragment)) { direction = TAB_SELECTION.FROM_LEFT_TO_RIGHT; } else if (isInGroup4(currentFragment) && !isInGroup4(newFragment)) { direction = TAB_SELECTION.FROM_RIGHT_TO_LEFT; } else if (isInGroup2(currentFragment)) { if (isInGroup1(newFragment)) { direction = TAB_SELECTION.FROM_RIGHT_TO_LEFT; } else if (isInGroup3(newFragment) || isInGroup4(newFragment)) { direction = TAB_SELECTION.FROM_LEFT_TO_RIGHT; } else { return TAB_SELECTION.NONE; } } else if (isInGroup3(currentFragment)) { if (isInGroup4(newFragment)) { direction = TAB_SELECTION.FROM_LEFT_TO_RIGHT; } else if (isInGroup1(newFragment) || isInGroup2(newFragment)) { direction = TAB_SELECTION.FROM_RIGHT_TO_LEFT; } else { return TAB_SELECTION.NONE; } } else { return TAB_SELECTION.NONE; } return direction; } public static void setCustomAnimations(TAB_SELECTION direction, FragmentTransaction fragmentTransaction) { switch (direction) { case FROM_LEFT_TO_RIGHT -> fragmentTransaction.setCustomAnimations( R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right ); case FROM_RIGHT_TO_LEFT -> fragmentTransaction.setCustomAnimations( R.anim.slide_in_left, R.anim.slide_out_right, R.anim.slide_in_right, R.anim.slide_out_left ); case NONE -> fragmentTransaction.setCustomAnimations( R.anim.fade_in, R.anim.fade_out, R.anim.fade_in, R.anim.fade_out ); } } private static boolean isInGroup1(Fragment fragment) { return fragment instanceof ColorsFragment || fragment instanceof PerAppThemeFragment; } private static boolean isInGroup2(Fragment fragment) {
return fragment instanceof ThemeFragment;
5
2023-12-06 13:20:16+00:00
16k
HelpChat/DeluxeMenus
src/main/java/com/extendedclip/deluxemenus/action/ClickActionTask.java
[ { "identifier": "DeluxeMenus", "path": "src/main/java/com/extendedclip/deluxemenus/DeluxeMenus.java", "snippet": "public class DeluxeMenus extends JavaPlugin {\r\n\r\n public final static Map<String, Material> MATERIALS\r\n = Arrays.stream(Material.values()).collect(Collectors.toUnmodifiableMa...
import com.extendedclip.deluxemenus.DeluxeMenus; import com.extendedclip.deluxemenus.menu.Menu; import com.extendedclip.deluxemenus.menu.MenuHolder; import com.extendedclip.deluxemenus.utils.AdventureUtils; import com.extendedclip.deluxemenus.utils.DebugLevel; import com.extendedclip.deluxemenus.utils.ExpUtils; import com.extendedclip.deluxemenus.utils.StringUtils; import com.extendedclip.deluxemenus.utils.VersionHelper; import java.util.logging.Level; import me.clip.placeholderapi.PlaceholderAPI; import net.kyori.adventure.Adventure; import net.kyori.adventure.text.minimessage.MiniMessage; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.Sound; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.scheduler.BukkitRunnable; import org.jetbrains.annotations.NotNull;
11,962
package com.extendedclip.deluxemenus.action; public class ClickActionTask extends BukkitRunnable { private final DeluxeMenus plugin; private final String name; private final ActionType actionType; private final String exec; public ClickActionTask( @NotNull final DeluxeMenus plugin, @NotNull final String name, @NotNull final ActionType actionType, @NotNull final String exec ) { this.plugin = plugin; this.name = name; this.actionType = actionType; this.exec = exec; } @Override public void run() { final Player player = Bukkit.getServer().getPlayerExact(name); if (player == null) { return; } final String executable = PlaceholderAPI.setPlaceholders((OfflinePlayer) player, exec);
package com.extendedclip.deluxemenus.action; public class ClickActionTask extends BukkitRunnable { private final DeluxeMenus plugin; private final String name; private final ActionType actionType; private final String exec; public ClickActionTask( @NotNull final DeluxeMenus plugin, @NotNull final String name, @NotNull final ActionType actionType, @NotNull final String exec ) { this.plugin = plugin; this.name = name; this.actionType = actionType; this.exec = exec; } @Override public void run() { final Player player = Bukkit.getServer().getPlayerExact(name); if (player == null) { return; } final String executable = PlaceholderAPI.setPlaceholders((OfflinePlayer) player, exec);
final MenuHolder holder = Menu.getMenuHolder(player);
2
2023-12-14 23:41:07+00:00
16k
lxs2601055687/contextAdminRuoYi
ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysUserOnlineController.java
[ { "identifier": "CacheConstants", "path": "ruoyi-common/src/main/java/com/ruoyi/common/constant/CacheConstants.java", "snippet": "public interface CacheConstants {\n\n /**\n * 登录用户 redis key\n */\n String LOGIN_TOKEN_KEY = \"Authorization:login:token:\";\n\n /**\n * 在线用户 redis key\n...
import cn.dev33.satoken.annotation.SaCheckPermission; import cn.dev33.satoken.exception.NotLoginException; import cn.dev33.satoken.stp.StpUtil; import cn.hutool.core.bean.BeanUtil; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.constant.CacheConstants; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.R; import com.ruoyi.common.core.domain.dto.UserOnlineDTO; import com.ruoyi.common.core.page.TableDataInfo; import com.ruoyi.common.enums.BusinessType; import com.ruoyi.common.utils.StreamUtils; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.redis.RedisUtils; import com.ruoyi.system.domain.SysUserOnline; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.Collections; import java.util.List;
11,852
package com.ruoyi.web.controller.monitor; /** * 在线用户监控 * * @author Lion Li */ @RequiredArgsConstructor @RestController @RequestMapping("/monitor/online") public class SysUserOnlineController extends BaseController { /** * 获取在线用户监控列表 * * @param ipaddr IP地址 * @param userName 用户名 */ @SaCheckPermission("monitor:online:list") @GetMapping("/list")
package com.ruoyi.web.controller.monitor; /** * 在线用户监控 * * @author Lion Li */ @RequiredArgsConstructor @RestController @RequestMapping("/monitor/online") public class SysUserOnlineController extends BaseController { /** * 获取在线用户监控列表 * * @param ipaddr IP地址 * @param userName 用户名 */ @SaCheckPermission("monitor:online:list") @GetMapping("/list")
public TableDataInfo<SysUserOnline> list(String ipaddr, String userName) {
4
2023-12-07 12:06:21+00:00
16k
DantSu/studio
web-ui/src/main/java/studio/webui/service/LibraryService.java
[ { "identifier": "StudioConfig", "path": "metadata/src/main/java/studio/config/StudioConfig.java", "snippet": "public enum StudioConfig {\n\n // auto open browser (studio.open.browser)\n STUDIO_OPEN_BROWSER(\"true\"),\n // http listen host (studio.host)\n STUDIO_HOST(\"localhost\"),\n // h...
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.Base64; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import studio.config.StudioConfig; import studio.core.v1.model.StoryPack; import studio.core.v1.model.metadata.StoryPackMetadata; import studio.core.v1.utils.PackAssetsCompression; import studio.core.v1.utils.PackFormat; import studio.core.v1.utils.exception.StoryTellerException; import studio.core.v1.writer.fs.FsStoryPackWriter; import studio.driver.fs.FileUtils; import studio.metadata.DatabaseMetadataService; import studio.metadata.DatabasePackMetadata; import studio.webui.model.LibraryPack;
12,704
Files.move(tmp, destinationPath); return destinationPath; } catch (Exception e) { String msg = "Failed to convert " + inputFormat + " format pack to " + outputFormat + " format"; LOGGER.error(msg, e); throw new StoryTellerException(msg, e); } } public Path addConvertedArchivePackFile(String packFile) { PackFormat outputFormat = PackFormat.ARCHIVE; if (packFile.endsWith(".zip")) { assertFormat(outputFormat); } // expected input format type PackFormat inputFormat = packFile.endsWith(".pack") ? PackFormat.RAW : PackFormat.FS; LOGGER.info("Pack is in {} format. Converting to {} format", inputFormat, outputFormat); try { // Packs must first be converted to raw format Path packPath = libraryPath.resolve(packFile); LOGGER.info("Reading {} format pack", inputFormat); StoryPack storyPack = inputFormat.getReader().read(packPath); // Compress pack assets if(inputFormat == PackFormat.RAW) { LOGGER.info("Compressing pack assets"); PackAssetsCompression.processCompressed(storyPack); } String zipName = storyPack.getUuid() + ".converted_" + System.currentTimeMillis() + ".zip"; Path tmp = tmpDirPath.resolve(zipName); LOGGER.info("Writing {} format pack, using temporary file: {}", outputFormat, tmp); outputFormat.getWriter().write(storyPack, tmp, true); Path destinationPath = libraryPath.resolve(zipName); LOGGER.info("Moving {} format pack into local library: {}", outputFormat, destinationPath); Files.move(tmp, destinationPath); return destinationPath; } catch (Exception e) { String msg = "Failed to convert " + inputFormat + " format pack to " + outputFormat + " format"; LOGGER.error(msg, e); throw new StoryTellerException(msg, e); } } public Path addConvertedFsPackFile(String packFile) { PackFormat outputFormat = PackFormat.FS; if (!packFile.endsWith(".zip") && !packFile.endsWith(".pack")) { assertFormat(outputFormat); } // expected input format type PackFormat inputFormat = packFile.endsWith(".zip") ? PackFormat.ARCHIVE : PackFormat.RAW; LOGGER.info("Pack is in {} format. Converting to {} format", inputFormat, outputFormat); try { // Packs must first be converted to raw format Path packPath = libraryPath.resolve(packFile); LOGGER.info("Reading {} format pack", inputFormat); StoryPack storyPack = inputFormat.getReader().read(packPath); // Prepare assets (RLE-encoded BMP, audio must already be MP3) LOGGER.info("Converting assets if necessary"); PackAssetsCompression.processFirmware2dot4(storyPack); Path tmp = createTempDirectory(packFile); LOGGER.info("Writing {} format pack, using temporary folder: {}", outputFormat, tmp); // should we not keep uuid instead ? Path tmpPath = FsStoryPackWriter.createPackFolder(storyPack, tmp); outputFormat.getWriter().write(storyPack, tmpPath, true); String destinationFileName = storyPack.getUuid() + ".converted_" + System.currentTimeMillis(); Path destinationPath = libraryPath.resolve(destinationFileName); LOGGER.info("Moving {} format pack into local library: {}", outputFormat, destinationPath); Files.move(tmpPath, destinationPath); return destinationPath; } catch (Exception e) { String msg = "Failed to convert " + inputFormat + " format pack to " + outputFormat + " format"; LOGGER.error(msg, e); throw new StoryTellerException(msg, e); } } public boolean addPackFile(String destPath, String uploadedFilePath) { try { // Copy temporary file to local library Path src = Path.of(uploadedFilePath); Path dest = libraryPath.resolve(destPath); Files.move(src, dest, StandardCopyOption.REPLACE_EXISTING); return true; } catch (IOException e) { LOGGER.error("Failed to add pack to local library", e); throw new StoryTellerException(e); } } public boolean deletePack(String packPath) { if (!Files.isDirectory(libraryPath)) { return false; } Path packFile = libraryPath.resolve(packPath); if(Files.notExists(packFile)) { LOGGER.error("Cannot remove pack from library because it is not in the folder"); return false; } try { if(Files.isDirectory(packFile)) { FileUtils.deleteDirectory(packFile); } else { Files.delete(packFile); } return true; } catch (IOException e) { LOGGER.error("Failed to remove pack from library", e); return false; } } public static Path libraryPath() {
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package studio.webui.service; public class LibraryService { private static final Logger LOGGER = LogManager.getLogger(LibraryService.class); private static final Path libraryPath = libraryPath(); private static final Path tmpDirPath = tmpDirPath(); private final DatabaseMetadataService databaseMetadataService; public LibraryService(DatabaseMetadataService databaseMetadataService) { this.databaseMetadataService = databaseMetadataService; // Create the local library folder if needed if (!Files.isDirectory(libraryPath)) { try { Files.createDirectories(libraryPath); } catch (IOException e) { LOGGER.error("Failed to initialize local library", e); throw new IllegalStateException("Failed to initialize local library"); } } // Create the temp folder if needed if (!Files.isDirectory(tmpDirPath)) { try { Files.createDirectories(tmpDirPath); } catch (IOException e) { LOGGER.error("Failed to initialize temp folder", e); throw new IllegalStateException("Failed to initialize temp folder"); } } } public JsonObject libraryInfos() { return new JsonObject().put("path", libraryPath.toString()); } public JsonArray packs() { // Check that local library folder exists if (!Files.isDirectory(libraryPath)) { return new JsonArray(); } // List pack files in library folder try (Stream<Path> paths = Files.walk(libraryPath, 1).filter(p -> p != libraryPath)) { // sort by timestamp DESC (=newest first) Comparator<LibraryPack> newestComparator = Comparator.comparingLong(LibraryPack::getTimestamp).reversed(); // Group pack by uuid Map<String, List<LibraryPack>> metadataByUuid = paths // debuging .filter(p -> { LOGGER.info("Read metadata from `{}`", p.getFileName()); return true; }) // actual read .map(this::readMetadata) // filter empty .filter(Optional::isPresent).map(Optional::get) // sort by timestamp DESC (=newer first) .sorted(newestComparator) // Group packs by UUID .collect(Collectors.groupingBy(p -> p.getMetadata().getUuid())); // Converts metadata to Json List<JsonObject> jsonMetasByUuid = metadataByUuid.entrySet().stream() // convert .map(e -> { // find first zip pack e.getValue().stream() // get Metadata .map(LibraryPack::getMetadata) // only zip .filter(meta -> meta.getFormat() == PackFormat.ARCHIVE) // // update database with newest zip .findFirst().ifPresent(meta -> { LOGGER.debug("Refresh metadata from zip for {} ({})", meta.getUuid(), meta.getTitle()); String thumbBase64 = Optional.ofNullable(meta.getThumbnail()) .map(t -> "data:image/png;base64," + Base64.getEncoder().encodeToString(t)) .orElse(null); databaseMetadataService.refreshUnofficialCache(new DatabasePackMetadata( // meta.getUuid(), meta.getTitle(), meta.getDescription(), thumbBase64, false)); }); // Convert to JsonObject List<JsonObject> jsonMetaList = e.getValue().stream()// .map(this::libraryPackToJson)// .collect(Collectors.toList()); return new JsonObject().put("uuid", e.getKey()).put("packs", new JsonArray(jsonMetaList)); }) // .collect(Collectors.toList()); // persist unofficial database cache (if needed) databaseMetadataService.persistUnofficialDatabase(); // return return new JsonArray(jsonMetasByUuid); } catch (IOException e) { LOGGER.error("Failed to read packs from local library", e); throw new StoryTellerException(e); } } public Path getPackFile(String packPath) { return libraryPath.resolve(packPath); } private void assertFormat(PackFormat outputFormat) { String msg = "Pack is already in " + outputFormat + " format"; LOGGER.error(msg); throw new StoryTellerException(msg); } public Path addConvertedPack(String packPath, PackFormat packFormat, boolean allowEnriched) { if (PackFormat.RAW == packFormat) { return addConvertedRawPackFile(packPath, allowEnriched); } if (PackFormat.FS == packFormat) { return addConvertedFsPackFile(packPath); } if (PackFormat.ARCHIVE == packFormat) { return addConvertedArchivePackFile(packPath); } throw new StoryTellerException("Unknown pack format " + packFormat); } public Path addConvertedRawPackFile(String packFile, boolean allowEnriched) { PackFormat outputFormat = PackFormat.RAW; if (packFile.endsWith(".pack")) { assertFormat(outputFormat); } // expected input format type PackFormat inputFormat = packFile.endsWith(".zip") ? PackFormat.ARCHIVE : PackFormat.FS; LOGGER.info("Pack is in {} format. Converting to {} format", inputFormat, outputFormat); try { // Packs must first be converted to raw format Path packPath = libraryPath.resolve(packFile); LOGGER.info("Reading {} format pack", inputFormat); StoryPack storyPack = inputFormat.getReader().read(packPath); // Uncompress pack assets if (PackAssetsCompression.hasCompressedAssets(storyPack)) { LOGGER.info("Uncompressing pack assets"); PackAssetsCompression.processUncompressed(storyPack); } Path tmp = createTempFile(packFile, ".pack"); LOGGER.info("Writing {} format pack, using temporary file: {}", outputFormat, tmp); outputFormat.getWriter().write(storyPack, tmp, allowEnriched); String destinationFileName = storyPack.getUuid() + ".converted_" + System.currentTimeMillis() + ".pack"; Path destinationPath = libraryPath.resolve(destinationFileName); LOGGER.info("Moving {} format pack into local library: {}", outputFormat, destinationPath); Files.move(tmp, destinationPath); return destinationPath; } catch (Exception e) { String msg = "Failed to convert " + inputFormat + " format pack to " + outputFormat + " format"; LOGGER.error(msg, e); throw new StoryTellerException(msg, e); } } public Path addConvertedArchivePackFile(String packFile) { PackFormat outputFormat = PackFormat.ARCHIVE; if (packFile.endsWith(".zip")) { assertFormat(outputFormat); } // expected input format type PackFormat inputFormat = packFile.endsWith(".pack") ? PackFormat.RAW : PackFormat.FS; LOGGER.info("Pack is in {} format. Converting to {} format", inputFormat, outputFormat); try { // Packs must first be converted to raw format Path packPath = libraryPath.resolve(packFile); LOGGER.info("Reading {} format pack", inputFormat); StoryPack storyPack = inputFormat.getReader().read(packPath); // Compress pack assets if(inputFormat == PackFormat.RAW) { LOGGER.info("Compressing pack assets"); PackAssetsCompression.processCompressed(storyPack); } String zipName = storyPack.getUuid() + ".converted_" + System.currentTimeMillis() + ".zip"; Path tmp = tmpDirPath.resolve(zipName); LOGGER.info("Writing {} format pack, using temporary file: {}", outputFormat, tmp); outputFormat.getWriter().write(storyPack, tmp, true); Path destinationPath = libraryPath.resolve(zipName); LOGGER.info("Moving {} format pack into local library: {}", outputFormat, destinationPath); Files.move(tmp, destinationPath); return destinationPath; } catch (Exception e) { String msg = "Failed to convert " + inputFormat + " format pack to " + outputFormat + " format"; LOGGER.error(msg, e); throw new StoryTellerException(msg, e); } } public Path addConvertedFsPackFile(String packFile) { PackFormat outputFormat = PackFormat.FS; if (!packFile.endsWith(".zip") && !packFile.endsWith(".pack")) { assertFormat(outputFormat); } // expected input format type PackFormat inputFormat = packFile.endsWith(".zip") ? PackFormat.ARCHIVE : PackFormat.RAW; LOGGER.info("Pack is in {} format. Converting to {} format", inputFormat, outputFormat); try { // Packs must first be converted to raw format Path packPath = libraryPath.resolve(packFile); LOGGER.info("Reading {} format pack", inputFormat); StoryPack storyPack = inputFormat.getReader().read(packPath); // Prepare assets (RLE-encoded BMP, audio must already be MP3) LOGGER.info("Converting assets if necessary"); PackAssetsCompression.processFirmware2dot4(storyPack); Path tmp = createTempDirectory(packFile); LOGGER.info("Writing {} format pack, using temporary folder: {}", outputFormat, tmp); // should we not keep uuid instead ? Path tmpPath = FsStoryPackWriter.createPackFolder(storyPack, tmp); outputFormat.getWriter().write(storyPack, tmpPath, true); String destinationFileName = storyPack.getUuid() + ".converted_" + System.currentTimeMillis(); Path destinationPath = libraryPath.resolve(destinationFileName); LOGGER.info("Moving {} format pack into local library: {}", outputFormat, destinationPath); Files.move(tmpPath, destinationPath); return destinationPath; } catch (Exception e) { String msg = "Failed to convert " + inputFormat + " format pack to " + outputFormat + " format"; LOGGER.error(msg, e); throw new StoryTellerException(msg, e); } } public boolean addPackFile(String destPath, String uploadedFilePath) { try { // Copy temporary file to local library Path src = Path.of(uploadedFilePath); Path dest = libraryPath.resolve(destPath); Files.move(src, dest, StandardCopyOption.REPLACE_EXISTING); return true; } catch (IOException e) { LOGGER.error("Failed to add pack to local library", e); throw new StoryTellerException(e); } } public boolean deletePack(String packPath) { if (!Files.isDirectory(libraryPath)) { return false; } Path packFile = libraryPath.resolve(packPath); if(Files.notExists(packFile)) { LOGGER.error("Cannot remove pack from library because it is not in the folder"); return false; } try { if(Files.isDirectory(packFile)) { FileUtils.deleteDirectory(packFile); } else { Files.delete(packFile); } return true; } catch (IOException e) { LOGGER.error("Failed to remove pack from library", e); return false; } } public static Path libraryPath() {
return Path.of(StudioConfig.STUDIO_LIBRARY.getValue());
0
2023-12-14 15:08:35+00:00
16k
Ispirer/COBOL-to-Java-Conversion-Samples
IspirerFramework/com/ispirer/sw/db/TransactionManager.java
[ { "identifier": "Oraca", "path": "IspirerFramework/com/ispirer/sw/db/utils/Oraca.java", "snippet": "public class Oraca {\r\n\r\n\tpublic static int orastxtf = 1;\r\n\tpublic static int oraslnr;\r\n\tpublic static int orastxtl = 0;\r\n\tpublic static String orastxtc = \"\";\r\n\tpublic static int orahoc ...
import com.ispirer.sw.db.utils.Oraca; import com.ispirer.sw.types.PictureType; import org.apache.commons.lang3.mutable.MutableInt; import com.ispirer.sw.db.utils.SqlCA; import java.sql.*; import java.util.HashMap; import java.util.function.Function;
13,067
/* © 2021, Ispirer Systems OÜ. All rights reserved. NOTICE OF LICENSE This file\library is Ispirer Reusable Code (“IRC”) and you are granted a non-exclusive, worldwide, perpetual, irrevocable and fully paid up license to use, modify, adapt, sublicense and otherwise exploit this IRC as provided below and under the terms of Ispirer Systems OÜ. Reusable Code License Agreement (“License”), which can be found in supplementary LICENSE.txt file. By using this IRC, you acknowledge that you have read the License and agree with its terms as well as with the fact that IRC is the property of and belongs to Ispirer Systems OÜ only. IF YOU ARE NOT AGREE WITH THE TERMS OF THE LICENSE, PLEASE, STOP USING THIS IRC IMMEDIATELY! PLEASE, NOTE, THAT IRC IS DISTRIBUTED “AS IS” AND WITHOUT ANY WARRANTY. IN NO EVENT WILL ISPIRER BE LIABLE FOR ANY DAMAGES, CLAIMS OR COSTS WHATSOEVER OR ANY CONSEQUENTIAL, INDIRECT, INCIDENTAL DAMAGES, OR ANY LOST PROFITS OR LOST SAVINGS. Redistributions of this IRC must retain the above copyright notice and a list of significant changes made to this IRC with indication of its author(s) and date of changes. If you need more information, or you think that the License has been violated, please let us know by e-mail: legal.department@ispirer.com */ package com.ispirer.sw.db; public class TransactionManager extends SqlCA { private static TransactionManager instance; private boolean useSqlca = false; private boolean useOraca = false; private Function<SQLException, SQLException> sqlerror = e -> null; private Function<SQLWarning, SQLWarning> sqlwarning = e -> null; private Function<String, String> notFound = e -> null; private SQLException exception; private String statementText; PreparedStatement statement; private HashMap<String, Cursor> cursors = new HashMap<>(); //private HashMap<String, Boolean> isScrollable = new HashMap<>(); private TransactionManager() { } public static TransactionManager getInstance() { if (instance == null) { instance = new TransactionManager(); } return instance; } // can execute SQL statements, such as DDL statements public void executeUpdate(String command) { try { checkAndClose(); statement = SqlConnect.getInstance().getConnect().prepareStatement(command); statement.executeUpdate(); statementText = command; handleWarning(statement.getWarnings()); setSuccess(); if (useSqlca) { sqlerrd[2] = statement.getUpdateCount(); sqlerrd[4] = statement.getUpdateCount(); } if (useOraca) {
/* © 2021, Ispirer Systems OÜ. All rights reserved. NOTICE OF LICENSE This file\library is Ispirer Reusable Code (“IRC”) and you are granted a non-exclusive, worldwide, perpetual, irrevocable and fully paid up license to use, modify, adapt, sublicense and otherwise exploit this IRC as provided below and under the terms of Ispirer Systems OÜ. Reusable Code License Agreement (“License”), which can be found in supplementary LICENSE.txt file. By using this IRC, you acknowledge that you have read the License and agree with its terms as well as with the fact that IRC is the property of and belongs to Ispirer Systems OÜ only. IF YOU ARE NOT AGREE WITH THE TERMS OF THE LICENSE, PLEASE, STOP USING THIS IRC IMMEDIATELY! PLEASE, NOTE, THAT IRC IS DISTRIBUTED “AS IS” AND WITHOUT ANY WARRANTY. IN NO EVENT WILL ISPIRER BE LIABLE FOR ANY DAMAGES, CLAIMS OR COSTS WHATSOEVER OR ANY CONSEQUENTIAL, INDIRECT, INCIDENTAL DAMAGES, OR ANY LOST PROFITS OR LOST SAVINGS. Redistributions of this IRC must retain the above copyright notice and a list of significant changes made to this IRC with indication of its author(s) and date of changes. If you need more information, or you think that the License has been violated, please let us know by e-mail: legal.department@ispirer.com */ package com.ispirer.sw.db; public class TransactionManager extends SqlCA { private static TransactionManager instance; private boolean useSqlca = false; private boolean useOraca = false; private Function<SQLException, SQLException> sqlerror = e -> null; private Function<SQLWarning, SQLWarning> sqlwarning = e -> null; private Function<String, String> notFound = e -> null; private SQLException exception; private String statementText; PreparedStatement statement; private HashMap<String, Cursor> cursors = new HashMap<>(); //private HashMap<String, Boolean> isScrollable = new HashMap<>(); private TransactionManager() { } public static TransactionManager getInstance() { if (instance == null) { instance = new TransactionManager(); } return instance; } // can execute SQL statements, such as DDL statements public void executeUpdate(String command) { try { checkAndClose(); statement = SqlConnect.getInstance().getConnect().prepareStatement(command); statement.executeUpdate(); statementText = command; handleWarning(statement.getWarnings()); setSuccess(); if (useSqlca) { sqlerrd[2] = statement.getUpdateCount(); sqlerrd[4] = statement.getUpdateCount(); } if (useOraca) {
Oraca.oranpr++;
0
2023-12-13 14:56:32+00:00
16k
Patbox/PolyDecorations
src/main/java/eu/pb4/polydecorations/ModInit.java
[ { "identifier": "BrazierBlock", "path": "src/main/java/eu/pb4/polydecorations/block/furniture/BrazierBlock.java", "snippet": "public class BrazierBlock extends Block implements FactoryBlock, BarrierBasedWaterloggable {\n public static final BooleanProperty LIT = Properties.LIT;\n\n public BrazierB...
import eu.pb4.factorytools.impl.DebugData; import eu.pb4.polydecorations.block.furniture.BrazierBlock; import eu.pb4.polydecorations.block.item.GlobeBlock; import eu.pb4.polydecorations.block.extension.WallAttachedLanternBlock; import eu.pb4.polydecorations.entity.DecorationsEntities; import eu.pb4.polydecorations.polydex.PolydexCompat; import eu.pb4.polydecorations.recipe.DecorationsRecipeSerializers; import eu.pb4.polydecorations.recipe.DecorationsRecipeTypes; import eu.pb4.polydecorations.ui.GuiTextures; import eu.pb4.polydecorations.ui.UiResourceCreator; import eu.pb4.polydecorations.util.*; import eu.pb4.polymer.resourcepack.api.PolymerResourcePackUtils; import eu.pb4.polydecorations.block.DecorationsBlockEntities; import eu.pb4.polydecorations.block.DecorationsBlocks; import eu.pb4.polydecorations.item.DecorationsItems; import net.fabricmc.api.ModInitializer; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.util.Identifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
11,751
package eu.pb4.polydecorations; public class ModInit implements ModInitializer { public static final String ID = "polydecorations"; public static final String VERSION = FabricLoader.getInstance().getModContainer(ID).get().getMetadata().getVersion().getFriendlyString(); public static final Logger LOGGER = LoggerFactory.getLogger("PolyDecorations"); public static final boolean DEV_ENV = FabricLoader.getInstance().isDevelopmentEnvironment(); public static final boolean DEV_MODE = VERSION.contains("-dev.") || DEV_ENV; @SuppressWarnings("PointlessBooleanExpression") public static final boolean DYNAMIC_ASSETS = true && DEV_ENV; public static Identifier id(String path) { return new Identifier(ID, path); } @Override public void onInitialize() { if (VERSION.contains("-dev.")) { LOGGER.warn("====================================================="); LOGGER.warn("You are using development version of PolyDecorations!"); LOGGER.warn("Support is limited, as features might be unfinished!"); LOGGER.warn("You are on your own!"); LOGGER.warn("====================================================="); } DecorationsBlocks.register(); DecorationsBlockEntities.register();
package eu.pb4.polydecorations; public class ModInit implements ModInitializer { public static final String ID = "polydecorations"; public static final String VERSION = FabricLoader.getInstance().getModContainer(ID).get().getMetadata().getVersion().getFriendlyString(); public static final Logger LOGGER = LoggerFactory.getLogger("PolyDecorations"); public static final boolean DEV_ENV = FabricLoader.getInstance().isDevelopmentEnvironment(); public static final boolean DEV_MODE = VERSION.contains("-dev.") || DEV_ENV; @SuppressWarnings("PointlessBooleanExpression") public static final boolean DYNAMIC_ASSETS = true && DEV_ENV; public static Identifier id(String path) { return new Identifier(ID, path); } @Override public void onInitialize() { if (VERSION.contains("-dev.")) { LOGGER.warn("====================================================="); LOGGER.warn("You are using development version of PolyDecorations!"); LOGGER.warn("Support is limited, as features might be unfinished!"); LOGGER.warn("You are on your own!"); LOGGER.warn("====================================================="); } DecorationsBlocks.register(); DecorationsBlockEntities.register();
DecorationsItems.register();
11
2023-12-10 16:20:36+00:00
16k
i-moonlight/Suricate
src/test/java/com/michelin/suricate/controllers/ProjectWidgetControllerTest.java
[ { "identifier": "ProjectWidgetRequestDto", "path": "src/main/java/com/michelin/suricate/model/dto/api/projectwidget/ProjectWidgetRequestDto.java", "snippet": "@Data\n@NoArgsConstructor\n@EqualsAndHashCode(callSuper = false)\n@Schema(description = \"Create/update project widget\")\npublic class ProjectWi...
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import com.michelin.suricate.model.dto.api.projectwidget.ProjectWidgetRequestDto; import com.michelin.suricate.model.dto.api.projectwidget.ProjectWidgetResponseDto; import com.michelin.suricate.model.entities.Project; import com.michelin.suricate.model.entities.ProjectGrid; import com.michelin.suricate.model.entities.ProjectWidget; import com.michelin.suricate.model.entities.Role; import com.michelin.suricate.model.entities.User; import com.michelin.suricate.security.LocalUser; import com.michelin.suricate.services.api.ProjectService; import com.michelin.suricate.services.api.ProjectWidgetService; import com.michelin.suricate.services.mapper.ProjectWidgetMapper; import com.michelin.suricate.utils.exceptions.ApiException; import com.michelin.suricate.utils.exceptions.ObjectNotFoundException; import java.util.Collections; import java.util.List; import java.util.Optional; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes;
10,943
package com.michelin.suricate.controllers; @ExtendWith(MockitoExtension.class) class ProjectWidgetControllerTest { @Mock private ProjectWidgetService projectWidgetService; @Mock private ProjectWidgetMapper projectWidgetMapper; @Mock private ProjectService projectService; @InjectMocks private ProjectWidgetController projectWidgetController; @Test void shouldGetByIdNotFound() { when(projectWidgetService.getOne(any())) .thenReturn(Optional.empty()); assertThatThrownBy(() -> projectWidgetController.getById(1L)) .isInstanceOf(ObjectNotFoundException.class) .hasMessage("ProjectWidget '1' not found"); } @Test void shouldGetById() { ProjectWidget projectWidget = new ProjectWidget(); projectWidget.setId(1L); ProjectWidgetResponseDto projectWidgetResponseDto = new ProjectWidgetResponseDto(); projectWidgetResponseDto.setId(1L); when(projectWidgetService.getOne(any())) .thenReturn(Optional.of(projectWidget)); when(projectWidgetMapper.toProjectWidgetDto(any())) .thenReturn(projectWidgetResponseDto); ResponseEntity<ProjectWidgetResponseDto> actual = projectWidgetController.getById(1L); assertThat(actual.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(actual.getBody()).isEqualTo(projectWidgetResponseDto); } @Test void shouldGetByProjectNotFound() { when(projectService.getOneByToken(any())) .thenReturn(Optional.empty()); assertThatThrownBy(() -> projectWidgetController.getByProject("token")) .isInstanceOf(ObjectNotFoundException.class) .hasMessage("Project 'token' not found"); } @Test void shouldGetByProjectNoGrid() { Project project = new Project(); project.setId(1L); when(projectService.getOneByToken(any())) .thenReturn(Optional.of(project)); ResponseEntity<List<ProjectWidgetResponseDto>> actual = projectWidgetController.getByProject("token"); assertThat(actual.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT); assertThat(actual.getBody()).isNull(); } @Test void shouldGetByProject() { ProjectWidgetResponseDto projectWidgetResponseDto = new ProjectWidgetResponseDto(); projectWidgetResponseDto.setId(1L); ProjectWidget projectWidget = new ProjectWidget(); projectWidget.setId(1L); ProjectGrid projectGrid = new ProjectGrid(); projectGrid.setId(1L); projectGrid.setWidgets(Collections.singleton(projectWidget)); Project project = new Project(); project.setId(1L); project.setGrids(Collections.singleton(projectGrid)); when(projectService.getOneByToken(any())) .thenReturn(Optional.of(project)); when(projectWidgetMapper.toProjectWidgetsDtos(any())) .thenReturn(Collections.singletonList(projectWidgetResponseDto)); ResponseEntity<List<ProjectWidgetResponseDto>> actual = projectWidgetController.getByProject("token"); assertThat(actual.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(actual.getBody()).contains(projectWidgetResponseDto); } @Test void shouldEditByProjectNotFound() {
package com.michelin.suricate.controllers; @ExtendWith(MockitoExtension.class) class ProjectWidgetControllerTest { @Mock private ProjectWidgetService projectWidgetService; @Mock private ProjectWidgetMapper projectWidgetMapper; @Mock private ProjectService projectService; @InjectMocks private ProjectWidgetController projectWidgetController; @Test void shouldGetByIdNotFound() { when(projectWidgetService.getOne(any())) .thenReturn(Optional.empty()); assertThatThrownBy(() -> projectWidgetController.getById(1L)) .isInstanceOf(ObjectNotFoundException.class) .hasMessage("ProjectWidget '1' not found"); } @Test void shouldGetById() { ProjectWidget projectWidget = new ProjectWidget(); projectWidget.setId(1L); ProjectWidgetResponseDto projectWidgetResponseDto = new ProjectWidgetResponseDto(); projectWidgetResponseDto.setId(1L); when(projectWidgetService.getOne(any())) .thenReturn(Optional.of(projectWidget)); when(projectWidgetMapper.toProjectWidgetDto(any())) .thenReturn(projectWidgetResponseDto); ResponseEntity<ProjectWidgetResponseDto> actual = projectWidgetController.getById(1L); assertThat(actual.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(actual.getBody()).isEqualTo(projectWidgetResponseDto); } @Test void shouldGetByProjectNotFound() { when(projectService.getOneByToken(any())) .thenReturn(Optional.empty()); assertThatThrownBy(() -> projectWidgetController.getByProject("token")) .isInstanceOf(ObjectNotFoundException.class) .hasMessage("Project 'token' not found"); } @Test void shouldGetByProjectNoGrid() { Project project = new Project(); project.setId(1L); when(projectService.getOneByToken(any())) .thenReturn(Optional.of(project)); ResponseEntity<List<ProjectWidgetResponseDto>> actual = projectWidgetController.getByProject("token"); assertThat(actual.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT); assertThat(actual.getBody()).isNull(); } @Test void shouldGetByProject() { ProjectWidgetResponseDto projectWidgetResponseDto = new ProjectWidgetResponseDto(); projectWidgetResponseDto.setId(1L); ProjectWidget projectWidget = new ProjectWidget(); projectWidget.setId(1L); ProjectGrid projectGrid = new ProjectGrid(); projectGrid.setId(1L); projectGrid.setWidgets(Collections.singleton(projectWidget)); Project project = new Project(); project.setId(1L); project.setGrids(Collections.singleton(projectGrid)); when(projectService.getOneByToken(any())) .thenReturn(Optional.of(project)); when(projectWidgetMapper.toProjectWidgetsDtos(any())) .thenReturn(Collections.singletonList(projectWidgetResponseDto)); ResponseEntity<List<ProjectWidgetResponseDto>> actual = projectWidgetController.getByProject("token"); assertThat(actual.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(actual.getBody()).contains(projectWidgetResponseDto); } @Test void shouldEditByProjectNotFound() {
Role role = new Role();
5
2023-12-11 11:28:37+00:00
16k
i-moonlight/Beluga
server/src/main/java/com/amnesica/belugaproject/services/aircraft/AircraftService.java
[ { "identifier": "Configuration", "path": "server/src/main/java/com/amnesica/belugaproject/config/Configuration.java", "snippet": "@Data\n@Slf4j\n@Validated\n@ConstructorBinding\n@org.springframework.context.annotation.Configuration\npublic class Configuration {\n\n @Autowired\n private Environment...
import com.amnesica.belugaproject.config.Configuration; import com.amnesica.belugaproject.config.Feeder; import com.amnesica.belugaproject.entities.aircraft.Aircraft; import com.amnesica.belugaproject.entities.aircraft.AircraftSuperclass; import com.amnesica.belugaproject.entities.aircraft.OpenskyAircraft; import com.amnesica.belugaproject.services.data.FlightrouteDataService; import com.amnesica.belugaproject.services.data.OperatorDataService; import com.amnesica.belugaproject.services.data.RegcodeDataService; import com.amnesica.belugaproject.services.helper.HelperService; import com.amnesica.belugaproject.services.helper.NetworkHandlerService; import com.amnesica.belugaproject.services.trails.AircraftTrailService; import lombok.extern.slf4j.Slf4j; import org.json.JSONArray; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Calendar;
10,845
package com.amnesica.belugaproject.services.aircraft; @Slf4j @Service public class AircraftService { @Autowired private RegcodeDataService regcodeDataService; @Autowired private OperatorDataService operatorDataService; @Autowired
package com.amnesica.belugaproject.services.aircraft; @Slf4j @Service public class AircraftService { @Autowired private RegcodeDataService regcodeDataService; @Autowired private OperatorDataService operatorDataService; @Autowired
private FlightrouteDataService flightrouteDataService;
5
2023-12-11 11:37:46+00:00
16k
fiber-net-gateway/fiber-net-gateway
fiber-gateway-proxy/src/main/java/io/fiber/net/proxy/lib/ReqFunc.java
[ { "identifier": "HttpExchange", "path": "fiber-gateway-common/src/main/java/io/fiber/net/common/HttpExchange.java", "snippet": "public abstract class HttpExchange {\n /**\n * 尽量把 HttpExchange 这个类的性能优化得非常好\n *\n * @param <T>\n */\n public static final class Attr<T> {\n privat...
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.BinaryNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.TextNode; import io.fiber.net.common.HttpExchange; import io.fiber.net.common.utils.ArrayUtils; import io.fiber.net.common.utils.Constant; import io.fiber.net.common.utils.JsonUtil; import io.fiber.net.common.utils.StringUtils; import io.fiber.net.http.util.MultiMap; import io.fiber.net.http.util.UrlEncoded; import io.fiber.net.script.ExecutionContext; import io.fiber.net.script.Library; import io.fiber.net.script.ScriptExecException; import io.netty.buffer.ByteBufInputStream; import io.netty.buffer.ByteBufUtil; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map;
12,572
package io.fiber.net.proxy.lib; public class ReqFunc { private static final ObjectNode EMPTY = JsonUtil.createObjectNode(); private static class Ctx { private final HttpExchange exchange; private ObjectNode query; private ObjectNode headers; private Ctx(HttpExchange exchange) { this.exchange = exchange; } public ObjectNode getQuery() { if (query == null) { String queryText = exchange.getQuery(); if (StringUtils.isNotEmpty(queryText)) { MultiMap<String> map = new MultiMap<>(); UrlEncoded.decodeUtf8To(queryText, map); query = JsonUtil.createObjectNode(); for (Map.Entry<String, List<String>> entry : map.entrySet()) { query.put(entry.getKey(), entry.getValue().get(0)); } } else { query = EMPTY; } } return query; } public ObjectNode getHeaders() { if (headers == null) { headers = JsonUtil.createObjectNode(); Collection<String> requestNames = exchange.getRequestHeaderNames(); for (String requestName : requestNames) { headers.put(requestName, exchange.getRequestHeader(requestName)); } } return headers; } } private static final HttpExchange.Attr<Ctx> CTX_ATTR = HttpExchange.createAttr(); private static Ctx getOrCreateCtx(ExecutionContext context) { HttpExchange exchange = HttpDynamicFunc.httpExchange(context); Ctx ctx = CTX_ATTR.get(exchange); if (ctx != null) { return ctx; } CTX_ATTR.set(exchange, ctx = new Ctx(exchange)); return ctx; } private static class GetHeader implements HttpDynamicFunc { @Override public void call(ExecutionContext context, JsonNode... args) { Ctx ctx = getOrCreateCtx(context); if (ArrayUtils.isEmpty(args)) { context.returnVal(this, ctx.getHeaders()); } else { String texted = args[0].textValue(); if (StringUtils.isEmpty(texted)) { context.returnVal(this, null); return; } context.returnVal(this, ctx.getHeaders().get(texted)); } } } private static class GetQuery implements HttpDynamicFunc { @Override public void call(ExecutionContext context, JsonNode... args) { Ctx ctx = getOrCreateCtx(context); if (ArrayUtils.isEmpty(args)) { context.returnVal(this, ctx.getQuery()); } else { String texted = args[0].textValue(); if (StringUtils.isEmpty(texted)) { context.returnVal(this, null); return; } context.returnVal(this, ctx.getQuery().get(texted)); } } } private static class ReadJsonBody implements HttpDynamicFunc { @Override public void call(ExecutionContext context, JsonNode... args) { HttpExchange exchange = HttpDynamicFunc.httpExchange(context); exchange.readFullReqBody().subscribe((buf, throwable) -> { if (throwable != null) {
package io.fiber.net.proxy.lib; public class ReqFunc { private static final ObjectNode EMPTY = JsonUtil.createObjectNode(); private static class Ctx { private final HttpExchange exchange; private ObjectNode query; private ObjectNode headers; private Ctx(HttpExchange exchange) { this.exchange = exchange; } public ObjectNode getQuery() { if (query == null) { String queryText = exchange.getQuery(); if (StringUtils.isNotEmpty(queryText)) { MultiMap<String> map = new MultiMap<>(); UrlEncoded.decodeUtf8To(queryText, map); query = JsonUtil.createObjectNode(); for (Map.Entry<String, List<String>> entry : map.entrySet()) { query.put(entry.getKey(), entry.getValue().get(0)); } } else { query = EMPTY; } } return query; } public ObjectNode getHeaders() { if (headers == null) { headers = JsonUtil.createObjectNode(); Collection<String> requestNames = exchange.getRequestHeaderNames(); for (String requestName : requestNames) { headers.put(requestName, exchange.getRequestHeader(requestName)); } } return headers; } } private static final HttpExchange.Attr<Ctx> CTX_ATTR = HttpExchange.createAttr(); private static Ctx getOrCreateCtx(ExecutionContext context) { HttpExchange exchange = HttpDynamicFunc.httpExchange(context); Ctx ctx = CTX_ATTR.get(exchange); if (ctx != null) { return ctx; } CTX_ATTR.set(exchange, ctx = new Ctx(exchange)); return ctx; } private static class GetHeader implements HttpDynamicFunc { @Override public void call(ExecutionContext context, JsonNode... args) { Ctx ctx = getOrCreateCtx(context); if (ArrayUtils.isEmpty(args)) { context.returnVal(this, ctx.getHeaders()); } else { String texted = args[0].textValue(); if (StringUtils.isEmpty(texted)) { context.returnVal(this, null); return; } context.returnVal(this, ctx.getHeaders().get(texted)); } } } private static class GetQuery implements HttpDynamicFunc { @Override public void call(ExecutionContext context, JsonNode... args) { Ctx ctx = getOrCreateCtx(context); if (ArrayUtils.isEmpty(args)) { context.returnVal(this, ctx.getQuery()); } else { String texted = args[0].textValue(); if (StringUtils.isEmpty(texted)) { context.returnVal(this, null); return; } context.returnVal(this, ctx.getQuery().get(texted)); } } } private static class ReadJsonBody implements HttpDynamicFunc { @Override public void call(ExecutionContext context, JsonNode... args) { HttpExchange exchange = HttpDynamicFunc.httpExchange(context); exchange.readFullReqBody().subscribe((buf, throwable) -> { if (throwable != null) {
context.throwErr(this, new ScriptExecException(throwable.getMessage(), throwable, 400,
9
2023-12-08 15:18:05+00:00
16k
netty/netty-incubator-codec-ohttp
codec-ohttp/src/test/java/io/netty/incubator/codec/ohttp/OHttpCodecsTest.java
[ { "identifier": "BinaryHttpRequest", "path": "codec-bhttp/src/main/java/io/netty/incubator/codec/bhttp/BinaryHttpRequest.java", "snippet": "public interface BinaryHttpRequest extends HttpRequest {\n\n /**\n * Returns the scheme used.\n *\n * @return scheme.\n */\n String scheme();\...
import io.netty.incubator.codec.bhttp.BinaryHttpRequest; import io.netty.incubator.codec.bhttp.DefaultBinaryHttpRequest; import io.netty.incubator.codec.bhttp.DefaultBinaryHttpResponse; import io.netty.incubator.codec.bhttp.DefaultFullBinaryHttpRequest; import io.netty.incubator.codec.bhttp.DefaultFullBinaryHttpResponse; import io.netty.incubator.codec.bhttp.FullBinaryHttpRequest; import io.netty.incubator.codec.hpke.AEAD; import io.netty.incubator.codec.hpke.AsymmetricCipherKeyPair; import io.netty.incubator.codec.hpke.AsymmetricKeyParameter; import io.netty.incubator.codec.hpke.KDF; import io.netty.incubator.codec.hpke.KEM; import io.netty.incubator.codec.hpke.OHttpCryptoProvider; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.socket.ChannelInputShutdownEvent; import io.netty.handler.codec.http.DefaultHttpContent; import io.netty.handler.codec.http.DefaultHttpRequest; import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.DefaultLastHttpContent; import io.netty.handler.codec.http.HttpClientCodec; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpObject; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.HttpUtil; import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.logging.LoggingHandler; import io.netty.incubator.codec.hpke.boringssl.BoringSSLHPKE; import io.netty.incubator.codec.hpke.boringssl.BoringSSLOHttpCryptoProvider; import io.netty.incubator.codec.hpke.bouncycastle.BouncyCastleOHttpCryptoProvider; import io.netty.util.ReferenceCountUtil; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsProvider; import org.junit.jupiter.params.provider.ArgumentsSource; import java.nio.charset.StandardCharsets; import java.security.Security; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeTrue;
12,706
/* * Copyright 2023 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.incubator.codec.ohttp; public class OHttpCodecsTest { private static final class OHttpVersionArgumentsProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) { List<Arguments> arguments = new ArrayList<>(); arguments.add(Arguments.of(OHttpVersionDraft.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionChunkDraft.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE)); if (BoringSSLHPKE.isAvailable()) { arguments.add(Arguments.of(OHttpVersionDraft.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionChunkDraft.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionDraft.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionChunkDraft.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionDraft.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionChunkDraft.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE)); } return arguments.stream(); } } @BeforeAll public static void setupAll() { System.setProperty("io.netty.leakDetection.level", "paranoid"); Security.addProvider(new BouncyCastleProvider()); } private static void transfer(EmbeddedChannel writer, EmbeddedChannel reader) { for (;;) { ByteBuf buffer = writer.readOutbound(); if (buffer == null) { break; } reader.writeInbound(buffer); } } public interface ChannelPair { EmbeddedChannel client(); EmbeddedChannel server(); }
/* * Copyright 2023 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.incubator.codec.ohttp; public class OHttpCodecsTest { private static final class OHttpVersionArgumentsProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) { List<Arguments> arguments = new ArrayList<>(); arguments.add(Arguments.of(OHttpVersionDraft.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionChunkDraft.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE)); if (BoringSSLHPKE.isAvailable()) { arguments.add(Arguments.of(OHttpVersionDraft.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionChunkDraft.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionDraft.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionChunkDraft.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionDraft.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionChunkDraft.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE)); } return arguments.stream(); } } @BeforeAll public static void setupAll() { System.setProperty("io.netty.leakDetection.level", "paranoid"); Security.addProvider(new BouncyCastleProvider()); } private static void transfer(EmbeddedChannel writer, EmbeddedChannel reader) { for (;;) { ByteBuf buffer = writer.readOutbound(); if (buffer == null) { break; } reader.writeInbound(buffer); } } public interface ChannelPair { EmbeddedChannel client(); EmbeddedChannel server(); }
public static ChannelPair createChannelPair(OHttpVersion version, OHttpCryptoProvider clientProvider,
11
2023-12-06 09:14:09+00:00
16k
lyswhut/react-native-local-media-metadata
android/src/main/java/org/jaudiotagger/tag/id3/AbstractID3v2Frame.java
[ { "identifier": "MP3File", "path": "android/src/main/java/org/jaudiotagger/audio/mp3/MP3File.java", "snippet": "public class MP3File extends AudioFile\n{\n private static final int MINIMUM_FILESIZE = 150;\n\n protected static AbstractTagDisplayFormatter tagFormatter;\n\n /**\n * the ID3v2 t...
import org.jaudiotagger.audio.mp3.MP3File; import org.jaudiotagger.tag.*; import org.jaudiotagger.tag.id3.framebody.AbstractID3v2FrameBody; import org.jaudiotagger.tag.id3.framebody.FrameBodyEncrypted; import org.jaudiotagger.tag.id3.framebody.FrameBodyUnsupported; import org.jaudiotagger.tag.id3.valuepair.TextEncoding; import org.jaudiotagger.utils.EqualsUtil; import java.io.ByteArrayOutputStream; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.logging.Level;
13,572
/* * MusicTag Copyright (C)2003,2004 * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser * General Public License as published by the Free Software Foundation; either version 2.1 of the License, * or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * you can get a copy from http://www.opensource.org/licenses/lgpl-license.php or write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jaudiotagger.tag.id3; /** * This abstract class is each frame header inside a ID3v2 tag. * * @author : Paul Taylor * @author : Eric Farng * @version $Id$ */ public abstract class AbstractID3v2Frame extends AbstractTagFrame implements TagTextField { protected static final String TYPE_FRAME = "frame"; protected static final String TYPE_FRAME_SIZE = "frameSize"; protected static final String UNSUPPORTED_ID = "Unsupported"; //Frame identifier protected String identifier = ""; //Frame Size protected int frameSize; //The purpose of this is to provide the filename that should be used when writing debug messages //when problems occur reading or writing to file, otherwise it is difficult to track down the error //when processing many files private String loggingFilename = ""; /** * * @return size in bytes of the frameid field */ protected abstract int getFrameIdSize(); /** * * @return the size in bytes of the frame size field */ protected abstract int getFrameSizeSize(); /** * * @return the size in bytes of the frame header */ protected abstract int getFrameHeaderSize(); /** * Create an empty frame */ protected AbstractID3v2Frame() { } /** * This holds the Status flags (not supported in v2.20 */ StatusFlags statusFlags = null; /** * This holds the Encoding flags (not supported in v2.20) */ EncodingFlags encodingFlags = null; /** * Create a frame based on another frame * @param frame */ public AbstractID3v2Frame(AbstractID3v2Frame frame) { super(frame); } /** * Create a frame based on a body * @param body */
/* * MusicTag Copyright (C)2003,2004 * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser * General Public License as published by the Free Software Foundation; either version 2.1 of the License, * or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * you can get a copy from http://www.opensource.org/licenses/lgpl-license.php or write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jaudiotagger.tag.id3; /** * This abstract class is each frame header inside a ID3v2 tag. * * @author : Paul Taylor * @author : Eric Farng * @version $Id$ */ public abstract class AbstractID3v2Frame extends AbstractTagFrame implements TagTextField { protected static final String TYPE_FRAME = "frame"; protected static final String TYPE_FRAME_SIZE = "frameSize"; protected static final String UNSUPPORTED_ID = "Unsupported"; //Frame identifier protected String identifier = ""; //Frame Size protected int frameSize; //The purpose of this is to provide the filename that should be used when writing debug messages //when problems occur reading or writing to file, otherwise it is difficult to track down the error //when processing many files private String loggingFilename = ""; /** * * @return size in bytes of the frameid field */ protected abstract int getFrameIdSize(); /** * * @return the size in bytes of the frame size field */ protected abstract int getFrameSizeSize(); /** * * @return the size in bytes of the frame header */ protected abstract int getFrameHeaderSize(); /** * Create an empty frame */ protected AbstractID3v2Frame() { } /** * This holds the Status flags (not supported in v2.20 */ StatusFlags statusFlags = null; /** * This holds the Encoding flags (not supported in v2.20) */ EncodingFlags encodingFlags = null; /** * Create a frame based on another frame * @param frame */ public AbstractID3v2Frame(AbstractID3v2Frame frame) { super(frame); } /** * Create a frame based on a body * @param body */
public AbstractID3v2Frame(AbstractID3v2FrameBody body)
1
2023-12-11 05:58:19+00:00
16k
xhtcode/xht-cloud-parent
xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/dept/service/impl/SysDeptServiceImpl.java
[ { "identifier": "Assert", "path": "xht-cloud-framework/xht-cloud-framework-exception/src/main/java/com/xht/cloud/framework/exception/Assert.java", "snippet": "public abstract class Assert {\n\n /**\n * 字符串为空抛出异常\n *\n * @param str 字符串\n */\n public static void hasText(String str) {...
import cn.hutool.core.bean.BeanUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.xht.cloud.framework.exception.Assert; import com.xht.cloud.framework.exception.business.BizException; import com.xht.cloud.framework.core.treenode.INode; import com.xht.cloud.framework.core.treenode.TreeNode; import com.xht.cloud.framework.core.treenode.TreeUtils; import com.xht.cloud.framework.mybatis.core.DataScopeFieldBuilder; import com.xht.cloud.framework.mybatis.core.enums.DataScopeTypeEnums; import com.xht.cloud.framework.mybatis.handler.DataScopeFactory; import com.xht.cloud.system.exceptions.PermissionException; import com.xht.cloud.system.manager.PermissionsManager; import com.xht.cloud.system.module.dept.controller.request.SysDeptAddRequest; import com.xht.cloud.system.module.dept.controller.request.SysDeptQueryRequest; import com.xht.cloud.system.module.dept.controller.request.SysDeptRequest; import com.xht.cloud.system.module.dept.controller.request.SysDeptUpdateRequest; import com.xht.cloud.system.module.dept.controller.response.SysDeptResponse; import com.xht.cloud.system.module.dept.convert.SysDeptConvert; import com.xht.cloud.system.module.dept.dao.dataobject.SysDeptDO; import com.xht.cloud.system.module.dept.dao.mapper.SysDeptMapper; import com.xht.cloud.system.module.dept.dao.wrapper.SysDeptWrapper; import com.xht.cloud.system.module.dept.service.ISysDeptService; import com.xht.cloud.system.module.permissions.dao.dataobject.SysMenuDO; import com.xht.cloud.system.module.user.dao.dataobject.SysUserDO; import com.xht.cloud.system.module.user.dao.mapper.SysUserMapper; import com.xht.cloud.system.module.user.dao.wrapper.SysUserWrapper; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects;
12,429
package com.xht.cloud.system.module.dept.service.impl; /** * 描述 :部门 * * @author : xht **/ @Slf4j @Service @RequiredArgsConstructor public class SysDeptServiceImpl implements ISysDeptService { private final SysDeptMapper sysDeptMapper; private final SysUserMapper sysUserMapper; private final SysDeptConvert sysDeptConvert; private final DataScopeFactory dataScopeFactory; /** * 创建 * * @param addRequest {@link SysDeptAddRequest} * @return {@link String} 主键 */ @Override @Transactional(rollbackFor = Exception.class) public String create(SysDeptAddRequest addRequest) { SysDeptDO entity = sysDeptConvert.toDO(addRequest); sysDeptMapper.insert(entity); return entity.getId(); } /** * 根据id修改 * * @param updateRequest SysDeptUpdateRequest */ @Override @Transactional(rollbackFor = Exception.class) public void update(SysDeptUpdateRequest updateRequest) { if (Objects.isNull(findById(updateRequest.getId()))) { throw new BizException("修改的对象不存在!"); } sysDeptMapper.updateById(sysDeptConvert.toDO(updateRequest)); } /** * 校验 * * @param request */ @Override public void validate(SysDeptRequest request) throws Exception { if (Objects.isNull(request)) { Assert.fail("部门信息为空"); } LambdaQueryWrapper<SysDeptDO> lambdaQuery = SysDeptWrapper.getInstance().lambdaQuery(); if (request instanceof SysDeptUpdateRequest) { lambdaQuery.ne(SysDeptDO::getId, ((SysDeptUpdateRequest) request).getId()); } lambdaQuery.eq(SysDeptDO::getDeptCode, request.getDeptCode()); List<SysDeptDO> sysDeptDOS = sysDeptMapper.selectList(lambdaQuery); if (!CollectionUtils.isEmpty(sysDeptDOS)) { Assert.fail("部门编码重复"); } } /** * 删除 * * @param ids {@link List<String>} id集合 */ @Override @Transactional(rollbackFor = Exception.class) public void remove(List<String> ids) { List<SysDeptDO> sysDeptDOS = sysDeptMapper.selectList(SysDeptWrapper.getInstance().lambdaQuery().in(SysDeptDO::getParentId, ids)); if (!CollectionUtils.isEmpty(sysDeptDOS)) { Assert.fail("选择的部门存在有下级部门禁止删除!"); } List<SysUserDO> sysUserDOS = sysUserMapper.selectList(SysUserWrapper.getInstance().lambdaQuery().in(SysUserDO::getDeptId, ids)); if (!CollectionUtils.isEmpty(sysUserDOS)) { Assert.fail("选择的部门中已绑定用户禁止删除!"); } sysDeptMapper.deleteBatchIds(ids); } /** * 根据id查询详细 * * @param id {@link String} 数据库主键 * @return {@link SysDeptResponse} */ @Override public SysDeptResponse findById(String id) { return sysDeptConvert.toResponse(sysDeptMapper.findById(id).orElse(null)); } /** * 查询 * @param queryRequest {@link SysDeptQueryRequest} * @return {@link List<SysDeptResponse>} 详情 */ @Override public List<SysDeptResponse> findList(SysDeptQueryRequest queryRequest) { LambdaQueryWrapper<SysDeptDO> lambdaQuery = SysDeptWrapper.getInstance().lambdaQuery(sysDeptConvert.toDO(queryRequest)); //List<String> deptIds = permissionsManager.selectDeptIdByDataScope(); //SqlGenerator.generateInClause(SysDeptDO::getId, deptIds, sysDeptDOLambdaQueryWrapper); dataScopeFactory.getDataScopeHandler(DataScopeTypeEnums.DEPT_USER_TYPE).execute(DataScopeFieldBuilder.<SysDeptDO>builder() .deptField(SysDeptDO::getId) .build(), lambdaQuery); List<SysDeptDO> sysDeptDOS = sysDeptMapper.selectList(lambdaQuery); return sysDeptConvert.toResponse(sysDeptDOS); } /** * 部门 转换成树结构 * * @param deptResponses {@link SysMenuDO} 部门 * @return 树结构 */ @Override public List<INode<String>> convert(List<SysDeptResponse> deptResponses) { if (CollectionUtils.isEmpty(deptResponses)) { return Collections.emptyList(); } List<INode<String>> result = new ArrayList<>(deptResponses.size()); for (SysDeptResponse item : deptResponses) { result.add(new TreeNode<>(item.getId(), item.getParentId(), item.getDeptSort()).setExtra(BeanUtil.beanToMap(item))); }
package com.xht.cloud.system.module.dept.service.impl; /** * 描述 :部门 * * @author : xht **/ @Slf4j @Service @RequiredArgsConstructor public class SysDeptServiceImpl implements ISysDeptService { private final SysDeptMapper sysDeptMapper; private final SysUserMapper sysUserMapper; private final SysDeptConvert sysDeptConvert; private final DataScopeFactory dataScopeFactory; /** * 创建 * * @param addRequest {@link SysDeptAddRequest} * @return {@link String} 主键 */ @Override @Transactional(rollbackFor = Exception.class) public String create(SysDeptAddRequest addRequest) { SysDeptDO entity = sysDeptConvert.toDO(addRequest); sysDeptMapper.insert(entity); return entity.getId(); } /** * 根据id修改 * * @param updateRequest SysDeptUpdateRequest */ @Override @Transactional(rollbackFor = Exception.class) public void update(SysDeptUpdateRequest updateRequest) { if (Objects.isNull(findById(updateRequest.getId()))) { throw new BizException("修改的对象不存在!"); } sysDeptMapper.updateById(sysDeptConvert.toDO(updateRequest)); } /** * 校验 * * @param request */ @Override public void validate(SysDeptRequest request) throws Exception { if (Objects.isNull(request)) { Assert.fail("部门信息为空"); } LambdaQueryWrapper<SysDeptDO> lambdaQuery = SysDeptWrapper.getInstance().lambdaQuery(); if (request instanceof SysDeptUpdateRequest) { lambdaQuery.ne(SysDeptDO::getId, ((SysDeptUpdateRequest) request).getId()); } lambdaQuery.eq(SysDeptDO::getDeptCode, request.getDeptCode()); List<SysDeptDO> sysDeptDOS = sysDeptMapper.selectList(lambdaQuery); if (!CollectionUtils.isEmpty(sysDeptDOS)) { Assert.fail("部门编码重复"); } } /** * 删除 * * @param ids {@link List<String>} id集合 */ @Override @Transactional(rollbackFor = Exception.class) public void remove(List<String> ids) { List<SysDeptDO> sysDeptDOS = sysDeptMapper.selectList(SysDeptWrapper.getInstance().lambdaQuery().in(SysDeptDO::getParentId, ids)); if (!CollectionUtils.isEmpty(sysDeptDOS)) { Assert.fail("选择的部门存在有下级部门禁止删除!"); } List<SysUserDO> sysUserDOS = sysUserMapper.selectList(SysUserWrapper.getInstance().lambdaQuery().in(SysUserDO::getDeptId, ids)); if (!CollectionUtils.isEmpty(sysUserDOS)) { Assert.fail("选择的部门中已绑定用户禁止删除!"); } sysDeptMapper.deleteBatchIds(ids); } /** * 根据id查询详细 * * @param id {@link String} 数据库主键 * @return {@link SysDeptResponse} */ @Override public SysDeptResponse findById(String id) { return sysDeptConvert.toResponse(sysDeptMapper.findById(id).orElse(null)); } /** * 查询 * @param queryRequest {@link SysDeptQueryRequest} * @return {@link List<SysDeptResponse>} 详情 */ @Override public List<SysDeptResponse> findList(SysDeptQueryRequest queryRequest) { LambdaQueryWrapper<SysDeptDO> lambdaQuery = SysDeptWrapper.getInstance().lambdaQuery(sysDeptConvert.toDO(queryRequest)); //List<String> deptIds = permissionsManager.selectDeptIdByDataScope(); //SqlGenerator.generateInClause(SysDeptDO::getId, deptIds, sysDeptDOLambdaQueryWrapper); dataScopeFactory.getDataScopeHandler(DataScopeTypeEnums.DEPT_USER_TYPE).execute(DataScopeFieldBuilder.<SysDeptDO>builder() .deptField(SysDeptDO::getId) .build(), lambdaQuery); List<SysDeptDO> sysDeptDOS = sysDeptMapper.selectList(lambdaQuery); return sysDeptConvert.toResponse(sysDeptDOS); } /** * 部门 转换成树结构 * * @param deptResponses {@link SysMenuDO} 部门 * @return 树结构 */ @Override public List<INode<String>> convert(List<SysDeptResponse> deptResponses) { if (CollectionUtils.isEmpty(deptResponses)) { return Collections.emptyList(); } List<INode<String>> result = new ArrayList<>(deptResponses.size()); for (SysDeptResponse item : deptResponses) { result.add(new TreeNode<>(item.getId(), item.getParentId(), item.getDeptSort()).setExtra(BeanUtil.beanToMap(item))); }
return TreeUtils.buildList(result);
4
2023-12-12 08:16:30+00:00
16k
serendipitk/LunarCore
src/main/java/emu/lunarcore/server/http/HttpServer.java
[ { "identifier": "HttpServerConfig", "path": "src/main/java/emu/lunarcore/Config.java", "snippet": "@Getter\npublic static class HttpServerConfig extends ServerConfig {\n public boolean useSSL = true;\n public long regionListRefresh = 60_000; // Time in milliseconds to wait before refreshing region...
import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.SecureRequestCustomizer; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.util.ssl.SslContextFactory; import emu.lunarcore.Config.HttpServerConfig; import emu.lunarcore.LunarCore; import emu.lunarcore.LunarCore.ServerType; import emu.lunarcore.proto.DispatchRegionDataOuterClass.DispatchRegionData; import emu.lunarcore.server.game.RegionInfo; import emu.lunarcore.server.http.handlers.*; import emu.lunarcore.util.Utils; import io.javalin.Javalin; import io.javalin.http.ContentType; import io.javalin.http.Context; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
10,943
package emu.lunarcore.server.http; public class HttpServer { private final Javalin app; private final ServerType type; private List<String> modes; private boolean started; private long nextRegionUpdate; private Object2ObjectMap<String, RegionInfo> regions; private String regionList; public HttpServer(ServerType type) { this.type = type; this.app = Javalin.create(); this.modes = new LinkedList<>(); this.regions = new Object2ObjectOpenHashMap<>(); this.addRoutes(); } public Javalin getApp() { return this.app; } public ServerType getType() { return type; } public HttpServerConfig getServerConfig() { return LunarCore.getConfig().getHttpServer(); } private HttpConnectionFactory getHttpFactory() { HttpConfiguration httpsConfig = new HttpConfiguration(); SecureRequestCustomizer src = new SecureRequestCustomizer(); src.setSniHostCheck(false); httpsConfig.addCustomizer(src); return new HttpConnectionFactory(httpsConfig); } private SslContextFactory.Server getSSLContextFactory() { SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); sslContextFactory.setKeyStorePath(LunarCore.getConfig().getKeystore().getPath()); sslContextFactory.setKeyStorePassword(LunarCore.getConfig().getKeystore().getPassword()); sslContextFactory.setSniRequired(false); sslContextFactory.setRenegotiationAllowed(false); return sslContextFactory; } public void forceRegionListRefresh() { this.nextRegionUpdate = 0; } public String getRegionList() { synchronized (this.regions) { // Check if region list needs to be cached if (System.currentTimeMillis() > this.nextRegionUpdate || this.regionList == null) { // Clear regions first this.regions.clear(); // Pull region infos from database LunarCore.getAccountDatabase().getObjects(RegionInfo.class) .forEach(region -> { this.regions.put(region.getId(), region); }); // Serialize to proto
package emu.lunarcore.server.http; public class HttpServer { private final Javalin app; private final ServerType type; private List<String> modes; private boolean started; private long nextRegionUpdate; private Object2ObjectMap<String, RegionInfo> regions; private String regionList; public HttpServer(ServerType type) { this.type = type; this.app = Javalin.create(); this.modes = new LinkedList<>(); this.regions = new Object2ObjectOpenHashMap<>(); this.addRoutes(); } public Javalin getApp() { return this.app; } public ServerType getType() { return type; } public HttpServerConfig getServerConfig() { return LunarCore.getConfig().getHttpServer(); } private HttpConnectionFactory getHttpFactory() { HttpConfiguration httpsConfig = new HttpConfiguration(); SecureRequestCustomizer src = new SecureRequestCustomizer(); src.setSniHostCheck(false); httpsConfig.addCustomizer(src); return new HttpConnectionFactory(httpsConfig); } private SslContextFactory.Server getSSLContextFactory() { SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); sslContextFactory.setKeyStorePath(LunarCore.getConfig().getKeystore().getPath()); sslContextFactory.setKeyStorePassword(LunarCore.getConfig().getKeystore().getPassword()); sslContextFactory.setSniRequired(false); sslContextFactory.setRenegotiationAllowed(false); return sslContextFactory; } public void forceRegionListRefresh() { this.nextRegionUpdate = 0; } public String getRegionList() { synchronized (this.regions) { // Check if region list needs to be cached if (System.currentTimeMillis() > this.nextRegionUpdate || this.regionList == null) { // Clear regions first this.regions.clear(); // Pull region infos from database LunarCore.getAccountDatabase().getObjects(RegionInfo.class) .forEach(region -> { this.regions.put(region.getId(), region); }); // Serialize to proto
DispatchRegionData regionData = DispatchRegionData.newInstance();
3
2023-12-08 14:13:04+00:00
16k
quentin452/Garden-Stuff-Continuation
src/main/java/com/jaquadro/minecraft/gardenstuff/renderer/LanternRenderer.java
[ { "identifier": "GardenAPI", "path": "src/main/java/com/jaquadro/minecraft/gardenapi/api/GardenAPI.java", "snippet": "public class GardenAPI {\n\n private static IGardenAPI instance;\n\n public static IGardenAPI instance() {\n if (instance == null) {\n try {\n Clas...
import com.jaquadro.minecraft.gardenapi.api.GardenAPI; import com.jaquadro.minecraft.gardenapi.api.component.ILanternSource; import com.jaquadro.minecraft.gardenapi.api.connect.IAttachable; import com.jaquadro.minecraft.gardenapi.api.connect.IChainSingleAttachable; import com.jaquadro.minecraft.gardenapi.internal.Api; import com.jaquadro.minecraft.gardencore.util.BindingStack; import com.jaquadro.minecraft.gardencore.util.RenderHelper; import com.jaquadro.minecraft.gardenstuff.GardenStuff; import com.jaquadro.minecraft.gardenstuff.block.BlockLantern; import com.jaquadro.minecraft.gardenstuff.block.tile.TileEntityLantern; import com.jaquadro.minecraft.gardenstuff.core.ClientProxy; import com.jaquadro.minecraft.gardenstuff.core.ModBlocks; import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.util.IIcon; import net.minecraft.util.Vec3; import net.minecraft.world.IBlockAccess; import net.minecraftforge.common.util.ForgeDirection;
14,186
package com.jaquadro.minecraft.gardenstuff.renderer; public class LanternRenderer implements ISimpleBlockRenderingHandler { public int renderPass = 0; private float[] colorScratch = new float[3]; private static final Vec3 defaultAttachPoint = Vec3.createVectorHelper(0.5D, 0.0D, 0.5D); public void renderInventoryBlock(Block block, int metadata, int modelId, RenderBlocks renderer) {} public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) {
package com.jaquadro.minecraft.gardenstuff.renderer; public class LanternRenderer implements ISimpleBlockRenderingHandler { public int renderPass = 0; private float[] colorScratch = new float[3]; private static final Vec3 defaultAttachPoint = Vec3.createVectorHelper(0.5D, 0.0D, 0.5D); public void renderInventoryBlock(Block block, int metadata, int modelId, RenderBlocks renderer) {} public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) {
return !(block instanceof BlockLantern) ? false
8
2023-12-12 08:13:16+00:00
16k
Zergatul/java-scripting-language
src/test/java/com/zergatul/scripting/tests/FunctionsTest.java
[ { "identifier": "ScriptCompileException", "path": "src/main/java/com/zergatul/scripting/compiler/ScriptCompileException.java", "snippet": "public class ScriptCompileException extends Exception {\n\n public ScriptCompileException(String message) {\n super(message);\n }\n}" }, { "iden...
import com.zergatul.scripting.compiler.ScriptCompileException; import com.zergatul.scripting.compiler.ScriptingLanguageCompiler; import com.zergatul.scripting.helpers.FloatStorage; import com.zergatul.scripting.helpers.IntStorage; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.List; import static org.junit.jupiter.api.Assertions.assertThrows;
13,662
package com.zergatul.scripting.tests; public class FunctionsTest { @BeforeEach public void clean() { ApiRoot.intStorage = new IntStorage();
package com.zergatul.scripting.tests; public class FunctionsTest { @BeforeEach public void clean() { ApiRoot.intStorage = new IntStorage();
ApiRoot.floatStorage = new FloatStorage();
2
2023-12-10 00:37:27+00:00
16k
muchfish/ruoyi-vue-pro-sample
yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsTemplateServiceImplTest.java
[ { "identifier": "CommonStatusEnum", "path": "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.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.util.collection.ArrayUtils; import cn.iocoder.yudao.framework.common.util.object.ObjectUtils; import cn.iocoder.yudao.framework.sms.core.client.SmsClient; import cn.iocoder.yudao.framework.sms.core.client.SmsCommonResult; import cn.iocoder.yudao.framework.sms.core.client.dto.SmsTemplateRespDTO; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.module.system.controller.admin.sms.vo.template.SmsTemplateCreateReqVO; import cn.iocoder.yudao.module.system.controller.admin.sms.vo.template.SmsTemplateExportReqVO; import cn.iocoder.yudao.module.system.controller.admin.sms.vo.template.SmsTemplatePageReqVO; import cn.iocoder.yudao.module.system.controller.admin.sms.vo.template.SmsTemplateUpdateReqVO; import cn.iocoder.yudao.module.system.dal.dataobject.sms.SmsChannelDO; import cn.iocoder.yudao.module.system.dal.dataobject.sms.SmsTemplateDO; import cn.iocoder.yudao.module.system.dal.mysql.sms.SmsTemplateMapper; import cn.iocoder.yudao.module.system.enums.sms.SmsTemplateTypeEnum; import com.google.common.collect.Lists; import org.junit.jupiter.api.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; import java.util.List; import java.util.function.Consumer; import static cn.hutool.core.util.RandomUtil.randomEle; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when;
11,700
package cn.iocoder.yudao.module.system.service.sms; @Import(SmsTemplateServiceImpl.class) public class SmsTemplateServiceImplTest extends BaseDbUnitTest { @Resource private SmsTemplateServiceImpl smsTemplateService; @Resource private SmsTemplateMapper smsTemplateMapper; @MockBean private SmsChannelService smsChannelService; @MockBean private SmsClient smsClient; @Test public void testParseTemplateContentParams() { // 准备参数 String content = "正在进行登录操作{operation},您的验证码是{code}"; // mock 方法 // 调用 List<String> params = smsTemplateService.parseTemplateContentParams(content); // 断言 assertEquals(Lists.newArrayList("operation", "code"), params); } @Test @SuppressWarnings("unchecked") public void testCreateSmsTemplate_success() { // 准备参数 SmsTemplateCreateReqVO reqVO = randomPojo(SmsTemplateCreateReqVO.class, o -> { o.setContent("正在进行登录操作{operation},您的验证码是{code}"); o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()); // 保证 status 的范围 o.setType(randomEle(SmsTemplateTypeEnum.values()).getType()); // 保证 type 的 范围 }); // mock Channel 的方法 SmsChannelDO channelDO = randomPojo(SmsChannelDO.class, o -> { o.setId(reqVO.getChannelId()); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); // 保证 status 开启,创建必须处于这个状态 }); when(smsChannelService.getSmsChannel(eq(channelDO.getId()))).thenReturn(channelDO); // mock 获得 API 短信模板成功 when(smsChannelService.getSmsClient(eq(reqVO.getChannelId()))).thenReturn(smsClient);
package cn.iocoder.yudao.module.system.service.sms; @Import(SmsTemplateServiceImpl.class) public class SmsTemplateServiceImplTest extends BaseDbUnitTest { @Resource private SmsTemplateServiceImpl smsTemplateService; @Resource private SmsTemplateMapper smsTemplateMapper; @MockBean private SmsChannelService smsChannelService; @MockBean private SmsClient smsClient; @Test public void testParseTemplateContentParams() { // 准备参数 String content = "正在进行登录操作{operation},您的验证码是{code}"; // mock 方法 // 调用 List<String> params = smsTemplateService.parseTemplateContentParams(content); // 断言 assertEquals(Lists.newArrayList("operation", "code"), params); } @Test @SuppressWarnings("unchecked") public void testCreateSmsTemplate_success() { // 准备参数 SmsTemplateCreateReqVO reqVO = randomPojo(SmsTemplateCreateReqVO.class, o -> { o.setContent("正在进行登录操作{operation},您的验证码是{code}"); o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()); // 保证 status 的范围 o.setType(randomEle(SmsTemplateTypeEnum.values()).getType()); // 保证 type 的 范围 }); // mock Channel 的方法 SmsChannelDO channelDO = randomPojo(SmsChannelDO.class, o -> { o.setId(reqVO.getChannelId()); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); // 保证 status 开启,创建必须处于这个状态 }); when(smsChannelService.getSmsChannel(eq(channelDO.getId()))).thenReturn(channelDO); // mock 获得 API 短信模板成功 when(smsChannelService.getSmsClient(eq(reqVO.getChannelId()))).thenReturn(smsClient);
when(smsClient.getSmsTemplate(eq(reqVO.getApiTemplateId()))).thenReturn(randomPojo(SmsCommonResult.class, SmsTemplateRespDTO.class,
6
2023-12-08 02:48:42+00:00
16k
mklemmingen/senet-boom
core/src/com/senetboom/game/frontend/special/moveBotTile.java
[ { "identifier": "SenetBoom", "path": "core/src/com/senetboom/game/SenetBoom.java", "snippet": "public class SenetBoom extends ApplicationAdapter {\n\n\t// for the stage the bot moves a piece on\n\tpublic static Group botMovingStage;\n\n\t// for the empty tile texture\n\tpublic static Texture emptyTextur...
import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.ui.Stack; import com.senetboom.game.SenetBoom; import com.senetboom.game.backend.Board; import com.senetboom.game.backend.Coordinate; import com.senetboom.game.backend.Piece; import com.senetboom.game.backend.Tile; import static com.senetboom.game.SenetBoom.tileSize;
11,377
package com.senetboom.game.frontend.special; public class moveBotTile { /* * This class is used to simulate the dragging of a piece by the bot. It slowly moves an image * of the soldier along the white line */ // properties for beginning and end coordinates public int start; public int end; private Coordinate startPx; private Coordinate endPx; // properties for elapsed time, boolean isMoving and current position private static float elapsedTime; private static float moveDuration; public static boolean isMoving; public boolean movingFinished; private Stack pieceStack; private Image pieceImage; public moveBotTile() { elapsedTime = 0; isMoving = false; movingFinished = false; } // method for starting the move public void startMove(int startX, int startY, int endX, int endY) { /* * Method to simulate a move (start of the Move) */ // coordinates this.start = startX; this.end = endX; // rerender Board with new Empty Variables SenetBoom.renderBoard(); // set the maximum duration fitting the length of the way that the soldier moves // per 50 pixel, add 0.5f to max duration // Begin: calculate Vector: startPx = SenetBoom.calculatePXbyTile(startX); endPx = SenetBoom.calculatePXbyTile(endX); Vector2 pointA = new Vector2(startPx.getX(), startPx.getY()); Vector2 pointB = new Vector2(endPx.getX(), endPx.getY()); Vector2 vectorAB = pointB.sub(pointA); float lengthVec = vectorAB.len(); int timefactor = (int) lengthVec / 50; moveDuration = timefactor * 0.75f; Tile[] gameBoard = Board.getBoard(); Tile startTile = gameBoard[start]; if (startTile.getPiece().getColour() == Piece.Color.WHITE) { startTile.setPiece(null); } else { startTile.setPiece(null); } pieceStack = new Stack();
package com.senetboom.game.frontend.special; public class moveBotTile { /* * This class is used to simulate the dragging of a piece by the bot. It slowly moves an image * of the soldier along the white line */ // properties for beginning and end coordinates public int start; public int end; private Coordinate startPx; private Coordinate endPx; // properties for elapsed time, boolean isMoving and current position private static float elapsedTime; private static float moveDuration; public static boolean isMoving; public boolean movingFinished; private Stack pieceStack; private Image pieceImage; public moveBotTile() { elapsedTime = 0; isMoving = false; movingFinished = false; } // method for starting the move public void startMove(int startX, int startY, int endX, int endY) { /* * Method to simulate a move (start of the Move) */ // coordinates this.start = startX; this.end = endX; // rerender Board with new Empty Variables SenetBoom.renderBoard(); // set the maximum duration fitting the length of the way that the soldier moves // per 50 pixel, add 0.5f to max duration // Begin: calculate Vector: startPx = SenetBoom.calculatePXbyTile(startX); endPx = SenetBoom.calculatePXbyTile(endX); Vector2 pointA = new Vector2(startPx.getX(), startPx.getY()); Vector2 pointB = new Vector2(endPx.getX(), endPx.getY()); Vector2 vectorAB = pointB.sub(pointA); float lengthVec = vectorAB.len(); int timefactor = (int) lengthVec / 50; moveDuration = timefactor * 0.75f; Tile[] gameBoard = Board.getBoard(); Tile startTile = gameBoard[start]; if (startTile.getPiece().getColour() == Piece.Color.WHITE) { startTile.setPiece(null); } else { startTile.setPiece(null); } pieceStack = new Stack();
pieceStack.setSize(tileSize, tileSize);
5
2023-12-05 22:19:00+00:00
16k
ItzOverS/CoReScreen
src/main/java/me/overlight/corescreen/Freeze/Listeners.java
[ { "identifier": "CoReScreen", "path": "src/main/java/me/overlight/corescreen/CoReScreen.java", "snippet": "public final class CoReScreen extends JavaPlugin {\n\n private static CoReScreen instance;\n\n public CoReScreen() {\n instance = this;\n }\n\n public static CoReScreen getInstan...
import me.overlight.corescreen.CoReScreen; import me.overlight.corescreen.Commands; import me.overlight.corescreen.DiscordWebhook; import me.overlight.corescreen.api.Freeze.PlayerFreezeQuitEvent; import me.overlight.powerlib.Chat.Text.impl.PlayerChatMessage; import me.overlight.powerlib.Chat.Text.impl.ext.ClickableCommand; import net.md_5.bungee.api.chat.BaseComponent; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityShootBowEvent; import org.bukkit.event.player.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects;
10,877
package me.overlight.corescreen.Freeze; public class Listeners implements Listener { @EventHandler public void event(AsyncPlayerChatEvent e) { if (FreezeManager.isFrozen(e.getPlayer())) { e.getRecipients().removeIf(r -> !r.hasPermission("corescreen.freeze.chat") && !Objects.equals(e.getPlayer().getName(), r.getName())); } } @EventHandler public void event(PlayerQuitEvent e) { if (FreezeManager.isFrozen(e.getPlayer())) { PlayerFreezeQuitEvent event = new PlayerFreezeQuitEvent(false, e.getPlayer()); Bukkit.getServer().getPluginManager().callEvent(event); if(event.isCancelled()) return; FreezeManager.unfreezePlayer(e.getPlayer()); Bukkit.getOnlinePlayers().stream().filter(p -> p.hasPermission("corescreen.freeze.alert")).forEach(p -> { p.sendMessage(CoReScreen.translate("messages.freeze.game.other-logout.message").replace("%who%", e.getPlayer().getName())); List<BaseComponent> components = new ArrayList<>(); for (String k : CoReScreen.getInstance().getConfig().getStringList("messages.freeze.game.other-logout.action-message")) { if (k.startsWith("%")) { ConfigurationSection section = CoReScreen.getInstance().getConfig().getConfigurationSection("messages.freeze.game.other-logout.actions." + k.replace("%", "").trim()); if (section != null) { components.add(new PlayerChatMessage(ChatColor.translateAlternateColorCodes('&', section.getString("content") .replace("%who%", e.getPlayer().getName())
package me.overlight.corescreen.Freeze; public class Listeners implements Listener { @EventHandler public void event(AsyncPlayerChatEvent e) { if (FreezeManager.isFrozen(e.getPlayer())) { e.getRecipients().removeIf(r -> !r.hasPermission("corescreen.freeze.chat") && !Objects.equals(e.getPlayer().getName(), r.getName())); } } @EventHandler public void event(PlayerQuitEvent e) { if (FreezeManager.isFrozen(e.getPlayer())) { PlayerFreezeQuitEvent event = new PlayerFreezeQuitEvent(false, e.getPlayer()); Bukkit.getServer().getPluginManager().callEvent(event); if(event.isCancelled()) return; FreezeManager.unfreezePlayer(e.getPlayer()); Bukkit.getOnlinePlayers().stream().filter(p -> p.hasPermission("corescreen.freeze.alert")).forEach(p -> { p.sendMessage(CoReScreen.translate("messages.freeze.game.other-logout.message").replace("%who%", e.getPlayer().getName())); List<BaseComponent> components = new ArrayList<>(); for (String k : CoReScreen.getInstance().getConfig().getStringList("messages.freeze.game.other-logout.action-message")) { if (k.startsWith("%")) { ConfigurationSection section = CoReScreen.getInstance().getConfig().getConfigurationSection("messages.freeze.game.other-logout.actions." + k.replace("%", "").trim()); if (section != null) { components.add(new PlayerChatMessage(ChatColor.translateAlternateColorCodes('&', section.getString("content") .replace("%who%", e.getPlayer().getName())
.replace("%prefix%", Commands.prefix == null ? "&e&lCoRe&cVanish &6»" : Commands.prefix)))
1
2023-12-07 16:34:39+00:00
16k
fabriciofx/cactoos-pdf
src/test/java/com/github/fabriciofx/cactoos/pdf/DocumentTest.java
[ { "identifier": "Contents", "path": "src/main/java/com/github/fabriciofx/cactoos/pdf/content/Contents.java", "snippet": "public final class Contents extends ListEnvelope<Content> implements Object {\n /**\n * Ctor.\n *\n * @param objects An array of objects\n */\n public Contents(f...
import com.github.fabriciofx.cactoos.pdf.content.Contents; import com.github.fabriciofx.cactoos.pdf.content.Image; import com.github.fabriciofx.cactoos.pdf.content.Text; import com.github.fabriciofx.cactoos.pdf.id.Serial; import com.github.fabriciofx.cactoos.pdf.image.format.Jpeg; import com.github.fabriciofx.cactoos.pdf.image.format.Png; import com.github.fabriciofx.cactoos.pdf.object.Catalog; import com.github.fabriciofx.cactoos.pdf.page.DefaultPage; import com.github.fabriciofx.cactoos.pdf.page.Format; import com.github.fabriciofx.cactoos.pdf.pages.DefaultPages; import com.github.fabriciofx.cactoos.pdf.resource.ProcSet; import com.github.fabriciofx.cactoos.pdf.resource.Resources; import com.github.fabriciofx.cactoos.pdf.resource.XObject; import com.github.fabriciofx.cactoos.pdf.resource.font.Courier; import com.github.fabriciofx.cactoos.pdf.resource.font.Helvetica; import com.github.fabriciofx.cactoos.pdf.resource.font.Symbol; import com.github.fabriciofx.cactoos.pdf.resource.font.TimesRoman; import com.github.fabriciofx.cactoos.pdf.resource.font.ZapfDingbats; import java.io.File; import java.nio.file.Files; import org.cactoos.bytes.BytesOf; import org.cactoos.io.ResourceOf; import org.cactoos.text.TextOf; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion;
12,908
/* * The MIT License (MIT) * * Copyright (C) 2023-2024 Fabrício Barros Cabral * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.fabriciofx.cactoos.pdf; /** * Test case for {@link Document}. * * @since 0.0.1 */ @SuppressWarnings({"PMD.AvoidDuplicateLiterals", "PMD.ExcessiveMethodLength"}) final class DocumentTest { @Test void buildDocumentHelloWorld() throws Exception { final Id id = new Serial(); final Font font = new TimesRoman(id, 18); final byte[] actual = new Document( id, new Catalog( id, new DefaultPages( id, Format.A4, new DefaultPage( id, new Resources(id, font), new Contents( new Text( id, font, 0, 500, 80, new TextOf("Hello World!") ) ) ) ) ) ).asBytes(); new Assertion<>( "Must match with hello world PDF document", new BytesOf(new ResourceOf("document/hello-world.pdf")).asBytes(), new IsEqual<>(actual) ).affirm(); } @Test void buildDocumentWithFileContent() throws Exception { final Id id = new Serial(); final Font font = new TimesRoman(id, 12); final byte[] actual = new Document( id, new Catalog( id, new DefaultPages( id, Format.A4, new DefaultPage( id, new Resources(id, font), new Contents( new Text( id, font, 20, 800, 100, new TextOf( new ResourceOf("text/20k_c1.txt") ) ) ) ) ) ) ).asBytes(); new Assertion<>( "Must match with PDF document with a text file", new BytesOf(new ResourceOf("document/text-20k.pdf")).asBytes(), new IsEqual<>(actual) ).affirm(); } @Test void buildDocumentWithFontsAndImages() throws Exception { final Id id = new Serial(); final Font times = new TimesRoman(id, 16); final Font helvetica = new Helvetica(id, 16); final Font courier = new Courier(id, 16); final Font symbol = new Symbol(id, 16); final Font zapf = new ZapfDingbats(id, 16); final Image cat = new Image( id, new Jpeg( id, new BytesOf(new ResourceOf("image/sample-1.jpg")) ), 0, 100 ); final Image logo = new Image( id, new Png( id, new BytesOf(new ResourceOf("image/logo.png")) ), 28, 766 ); final org.cactoos.Text text = new TextOf( "The quick brown fox jumps over the lazy dog" ); final byte[] actual = new Document( id, new Catalog( id, new DefaultPages( id, Format.A4, new DefaultPage( id, new Resources( id, times, helvetica, courier, symbol, zapf, new ProcSet(),
/* * The MIT License (MIT) * * Copyright (C) 2023-2024 Fabrício Barros Cabral * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.fabriciofx.cactoos.pdf; /** * Test case for {@link Document}. * * @since 0.0.1 */ @SuppressWarnings({"PMD.AvoidDuplicateLiterals", "PMD.ExcessiveMethodLength"}) final class DocumentTest { @Test void buildDocumentHelloWorld() throws Exception { final Id id = new Serial(); final Font font = new TimesRoman(id, 18); final byte[] actual = new Document( id, new Catalog( id, new DefaultPages( id, Format.A4, new DefaultPage( id, new Resources(id, font), new Contents( new Text( id, font, 0, 500, 80, new TextOf("Hello World!") ) ) ) ) ) ).asBytes(); new Assertion<>( "Must match with hello world PDF document", new BytesOf(new ResourceOf("document/hello-world.pdf")).asBytes(), new IsEqual<>(actual) ).affirm(); } @Test void buildDocumentWithFileContent() throws Exception { final Id id = new Serial(); final Font font = new TimesRoman(id, 12); final byte[] actual = new Document( id, new Catalog( id, new DefaultPages( id, Format.A4, new DefaultPage( id, new Resources(id, font), new Contents( new Text( id, font, 20, 800, 100, new TextOf( new ResourceOf("text/20k_c1.txt") ) ) ) ) ) ) ).asBytes(); new Assertion<>( "Must match with PDF document with a text file", new BytesOf(new ResourceOf("document/text-20k.pdf")).asBytes(), new IsEqual<>(actual) ).affirm(); } @Test void buildDocumentWithFontsAndImages() throws Exception { final Id id = new Serial(); final Font times = new TimesRoman(id, 16); final Font helvetica = new Helvetica(id, 16); final Font courier = new Courier(id, 16); final Font symbol = new Symbol(id, 16); final Font zapf = new ZapfDingbats(id, 16); final Image cat = new Image( id, new Jpeg( id, new BytesOf(new ResourceOf("image/sample-1.jpg")) ), 0, 100 ); final Image logo = new Image( id, new Png( id, new BytesOf(new ResourceOf("image/logo.png")) ), 28, 766 ); final org.cactoos.Text text = new TextOf( "The quick brown fox jumps over the lazy dog" ); final byte[] actual = new Document( id, new Catalog( id, new DefaultPages( id, Format.A4, new DefaultPage( id, new Resources( id, times, helvetica, courier, symbol, zapf, new ProcSet(),
new XObject(id, cat),
12
2023-12-05 00:07:24+00:00
16k
sinbad-navigator/erp-crm
center/src/main/java/com/ec/web/controller/monitor/SysOperlogController.java
[ { "identifier": "BaseController", "path": "common/src/main/java/com/ec/common/core/controller/BaseController.java", "snippet": "public class BaseController {\n protected final Logger logger = LoggerFactory.getLogger(this.getClass());\n\n @InitBinder //@InitBinder 标注的方法名为 initBinder,它被用于将 WebDataBi...
import java.util.List; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.ec.common.annotation.Log; import com.ec.common.core.controller.BaseController; import com.ec.common.core.domain.AjaxResult; import com.ec.common.core.page.TableDataInfo; import com.ec.common.enums.BusinessType; import com.ec.common.utils.poi.ExcelUtil; import com.ec.sys.domain.SysOperLog; import com.ec.sys.service.ISysOperLogService;
14,287
package com.ec.web.controller.monitor; /** * 操作日志记录 * * @author ec */ @RestController @RequestMapping("/monitor/operlog")
package com.ec.web.controller.monitor; /** * 操作日志记录 * * @author ec */ @RestController @RequestMapping("/monitor/operlog")
public class SysOperlogController extends BaseController {
0
2023-12-07 14:23:12+00:00
16k
gaetanBloch/jhlite-gateway
src/main/java/com/mycompany/myapp/shared/pagination/infrastructure/secondary/JhipsterSampleApplicationPages.java
[ { "identifier": "Assert", "path": "src/main/java/com/mycompany/myapp/shared/error/domain/Assert.java", "snippet": "public class Assert {\n\n private Assert() {}\n\n /**\n * Ensure that the input is not null\n *\n * @param field\n * name of the field to check (will be displayed in exce...
import java.util.function.Function; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import com.mycompany.myapp.shared.error.domain.Assert; import com.mycompany.myapp.shared.pagination.domain.JhipsterSampleApplicationPage; import com.mycompany.myapp.shared.pagination.domain.JhipsterSampleApplicationPageable;
11,222
package com.mycompany.myapp.shared.pagination.infrastructure.secondary; public final class JhipsterSampleApplicationPages { private JhipsterSampleApplicationPages() {} public static Pageable from(JhipsterSampleApplicationPageable pagination) { return from(pagination, Sort.unsorted()); } public static Pageable from(JhipsterSampleApplicationPageable pagination, Sort sort) {
package com.mycompany.myapp.shared.pagination.infrastructure.secondary; public final class JhipsterSampleApplicationPages { private JhipsterSampleApplicationPages() {} public static Pageable from(JhipsterSampleApplicationPageable pagination) { return from(pagination, Sort.unsorted()); } public static Pageable from(JhipsterSampleApplicationPageable pagination, Sort sort) {
Assert.notNull("pagination", pagination);
0
2023-12-10 06:39:18+00:00
16k
Crydsch/the-one
src/gui/playfield/PlayField.java
[ { "identifier": "DTNSimGUI", "path": "src/gui/DTNSimGUI.java", "snippet": "public class DTNSimGUI extends DTNSimUI {\n\tprivate MainWindow main;\n\tprivate PlayField field;\n\tprivate GUIControls guiControls;\n\tprivate EventLogPanel eventLogPanel;\n\tprivate InfoPanel infoPanel;\n\n\tprivate void start...
import gui.DTNSimGUI; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.swing.JPanel; import movement.Path; import movement.map.SimMap; import core.Coord; import core.DTNHost; import core.World;
13,032
/* * Copyright 2010 Aalto University, ComNet * Released under GPLv3. See LICENSE.txt for details. */ package gui.playfield; /** * The canvas where node graphics and message visualizations are drawn. * */ public class PlayField extends JPanel { public static final int PLAYFIELD_OFFSET = 10; private World w; private DTNSimGUI gui; private Color bgColor = Color.WHITE; private List<PlayFieldGraphic> overlayGraphics; private boolean autoClearOverlay; // automatically clear overlay graphics private MapGraphic mapGraphic; private boolean showMapGraphic; private ScaleReferenceGraphic refGraphic; private boolean focusOnClick; private boolean zoomWheelInvert; private BufferedImage underlayImage; private AffineTransform imageTransform; private AffineTransform curTransform; private double underlayImgDx; private double underlayImgDy; private float underlayImgOpacity; private boolean underlayImgOffsetRelMap; /** * Creates a playfield * @param w The world that contains the actors to be drawn */ public PlayField (World w, DTNSimGUI gui) { this.w = w; this.gui = gui; this.refGraphic = new ScaleReferenceGraphic(); updateFieldSize(); this.setBackground(bgColor); this.overlayGraphics = Collections.synchronizedList( new ArrayList<PlayFieldGraphic>()); this.mapGraphic = null; this.underlayImage = null; this.imageTransform = null; this.autoClearOverlay = true; this.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (focusOnClick) { focusClosestNode(e.getX(), e.getY()); } } }); } /** * Schedule the play field to be drawn */ public void updateField() { this.repaint(); } /** * Sets an image to show under the host graphics * @param image The image to set or null to remove the image * @param dx X offset of the image * @param dy Y offset of the image * @param scale Image scaling factor * @param rotation Rotatation angle of the image (radians) * @param opacity Opacity of the background image */ public void setUnderlayImage(BufferedImage image, double dx, double dy, double scale, double rotation, float opacity, boolean offsetRelMap) { if (image == null) { this.underlayImage = null; this.imageTransform = null; this.curTransform = null; updateField(); return; } this.underlayImage = image; this.underlayImgOpacity = opacity; this.imageTransform = AffineTransform.getRotateInstance(rotation); this.imageTransform.scale(scale, scale); this.underlayImgOffsetRelMap = offsetRelMap; this.underlayImgDx = dx; this.underlayImgDy = dy; updateUnderlyingImageTransform(); updateField(); } private void updateUnderlyingImageTransform(){ if (this.imageTransform != null) { double dx = this.underlayImgDx; double dy = this.underlayImgDy; double scale = PlayFieldGraphic.getScale(); if(this.underlayImgOffsetRelMap && mapGraphic != null){
/* * Copyright 2010 Aalto University, ComNet * Released under GPLv3. See LICENSE.txt for details. */ package gui.playfield; /** * The canvas where node graphics and message visualizations are drawn. * */ public class PlayField extends JPanel { public static final int PLAYFIELD_OFFSET = 10; private World w; private DTNSimGUI gui; private Color bgColor = Color.WHITE; private List<PlayFieldGraphic> overlayGraphics; private boolean autoClearOverlay; // automatically clear overlay graphics private MapGraphic mapGraphic; private boolean showMapGraphic; private ScaleReferenceGraphic refGraphic; private boolean focusOnClick; private boolean zoomWheelInvert; private BufferedImage underlayImage; private AffineTransform imageTransform; private AffineTransform curTransform; private double underlayImgDx; private double underlayImgDy; private float underlayImgOpacity; private boolean underlayImgOffsetRelMap; /** * Creates a playfield * @param w The world that contains the actors to be drawn */ public PlayField (World w, DTNSimGUI gui) { this.w = w; this.gui = gui; this.refGraphic = new ScaleReferenceGraphic(); updateFieldSize(); this.setBackground(bgColor); this.overlayGraphics = Collections.synchronizedList( new ArrayList<PlayFieldGraphic>()); this.mapGraphic = null; this.underlayImage = null; this.imageTransform = null; this.autoClearOverlay = true; this.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (focusOnClick) { focusClosestNode(e.getX(), e.getY()); } } }); } /** * Schedule the play field to be drawn */ public void updateField() { this.repaint(); } /** * Sets an image to show under the host graphics * @param image The image to set or null to remove the image * @param dx X offset of the image * @param dy Y offset of the image * @param scale Image scaling factor * @param rotation Rotatation angle of the image (radians) * @param opacity Opacity of the background image */ public void setUnderlayImage(BufferedImage image, double dx, double dy, double scale, double rotation, float opacity, boolean offsetRelMap) { if (image == null) { this.underlayImage = null; this.imageTransform = null; this.curTransform = null; updateField(); return; } this.underlayImage = image; this.underlayImgOpacity = opacity; this.imageTransform = AffineTransform.getRotateInstance(rotation); this.imageTransform.scale(scale, scale); this.underlayImgOffsetRelMap = offsetRelMap; this.underlayImgDx = dx; this.underlayImgDy = dy; updateUnderlyingImageTransform(); updateField(); } private void updateUnderlyingImageTransform(){ if (this.imageTransform != null) { double dx = this.underlayImgDx; double dy = this.underlayImgDy; double scale = PlayFieldGraphic.getScale(); if(this.underlayImgOffsetRelMap && mapGraphic != null){
Coord c = mapGraphic.getMap().getOffset();
3
2023-12-10 15:51:41+00:00
16k
seleuco/MAME4droid-2024
android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/helpers/DialogHelper.java
[ { "identifier": "PRESS_WAIT", "path": "android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/input/InputHandler.java", "snippet": "final static public int PRESS_WAIT = 100;" }, { "identifier": "Emulator", "path": "android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/Emulator.jav...
import static com.seleuco.mame4droid.input.InputHandler.PRESS_WAIT; import android.app.AlertDialog; import android.app.Dialog; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.view.View; import com.seleuco.mame4droid.Emulator; import com.seleuco.mame4droid.MAME4droid; import com.seleuco.mame4droid.input.ControlCustomizer; import com.seleuco.mame4droid.views.IEmuView; import java.util.Arrays;
11,172
/* * This file is part of MAME4droid. * * Copyright (C) 2015 David Valdeita (Seleuco) * * 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, see <http://www.gnu.org/licenses>. * * Linking MAME4droid statically or dynamically with other modules is * making a combined work based on MAME4droid. Thus, the terms and * conditions of the GNU General Public License cover the whole * combination. * * In addition, as a special exception, the copyright holders of MAME4droid * give you permission to combine MAME4droid with free software programs * or libraries that are released under the GNU LGPL and with code included * in the standard release of MAME under the MAME License (or modified * versions of such code, with unchanged license). You may copy and * distribute such a system following the terms of the GNU GPL for MAME4droid * and the licenses of the other code concerned, provided that you include * the source code of that other code when and as the GNU GPL requires * distribution of source code. * * Note that people who make modified versions of MAME4idroid are not * obligated to grant this special exception for their modified versions; it * is their choice whether to do so. The GNU General Public License * gives permission to release a modified version without this exception; * this exception also makes it possible to release a modified version * which carries forward this exception. * * MAME4droid is dual-licensed: Alternatively, you can license MAME4droid * under a MAME license, as set out in http://mamedev.org/ */ package com.seleuco.mame4droid.helpers; public class DialogHelper { public static int savedDialog = DialogHelper.DIALOG_NONE; public final static int DIALOG_NONE = -1; public final static int DIALOG_EXIT = 1; public final static int DIALOG_ERROR_WRITING = 2; public final static int DIALOG_INFO = 3; public final static int DIALOG_OPTIONS = 5; public final static int DIALOG_FULLSCREEN = 7; public final static int DIALOG_FINISH_CUSTOM_LAYOUT = 10; public final static int DIALOG_EMU_RESTART = 11; public final static int DIALOG_NO_PERMISSIONS = 12; public final static int DIALOG_ROMs = 13; protected MAME4droid mm = null; static protected String errorMsg; static protected String infoMsg; public void setErrorMsg(String errorMsg) { DialogHelper.errorMsg = errorMsg; } public void setInfoMsg(String infoMsg) { DialogHelper.infoMsg = infoMsg; } public DialogHelper(MAME4droid value) { mm = value; } public Dialog createDialog(int id) { Dialog dialog; AlertDialog.Builder builder = new AlertDialog.Builder(mm); switch (id) { case DIALOG_FINISH_CUSTOM_LAYOUT: builder.setMessage("Do you want to save changes?") .setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { DialogHelper.savedDialog = DIALOG_NONE; mm.removeDialog(DIALOG_FINISH_CUSTOM_LAYOUT);
/* * This file is part of MAME4droid. * * Copyright (C) 2015 David Valdeita (Seleuco) * * 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, see <http://www.gnu.org/licenses>. * * Linking MAME4droid statically or dynamically with other modules is * making a combined work based on MAME4droid. Thus, the terms and * conditions of the GNU General Public License cover the whole * combination. * * In addition, as a special exception, the copyright holders of MAME4droid * give you permission to combine MAME4droid with free software programs * or libraries that are released under the GNU LGPL and with code included * in the standard release of MAME under the MAME License (or modified * versions of such code, with unchanged license). You may copy and * distribute such a system following the terms of the GNU GPL for MAME4droid * and the licenses of the other code concerned, provided that you include * the source code of that other code when and as the GNU GPL requires * distribution of source code. * * Note that people who make modified versions of MAME4idroid are not * obligated to grant this special exception for their modified versions; it * is their choice whether to do so. The GNU General Public License * gives permission to release a modified version without this exception; * this exception also makes it possible to release a modified version * which carries forward this exception. * * MAME4droid is dual-licensed: Alternatively, you can license MAME4droid * under a MAME license, as set out in http://mamedev.org/ */ package com.seleuco.mame4droid.helpers; public class DialogHelper { public static int savedDialog = DialogHelper.DIALOG_NONE; public final static int DIALOG_NONE = -1; public final static int DIALOG_EXIT = 1; public final static int DIALOG_ERROR_WRITING = 2; public final static int DIALOG_INFO = 3; public final static int DIALOG_OPTIONS = 5; public final static int DIALOG_FULLSCREEN = 7; public final static int DIALOG_FINISH_CUSTOM_LAYOUT = 10; public final static int DIALOG_EMU_RESTART = 11; public final static int DIALOG_NO_PERMISSIONS = 12; public final static int DIALOG_ROMs = 13; protected MAME4droid mm = null; static protected String errorMsg; static protected String infoMsg; public void setErrorMsg(String errorMsg) { DialogHelper.errorMsg = errorMsg; } public void setInfoMsg(String infoMsg) { DialogHelper.infoMsg = infoMsg; } public DialogHelper(MAME4droid value) { mm = value; } public Dialog createDialog(int id) { Dialog dialog; AlertDialog.Builder builder = new AlertDialog.Builder(mm); switch (id) { case DIALOG_FINISH_CUSTOM_LAYOUT: builder.setMessage("Do you want to save changes?") .setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { DialogHelper.savedDialog = DIALOG_NONE; mm.removeDialog(DIALOG_FINISH_CUSTOM_LAYOUT);
ControlCustomizer.setEnabled(false);
3
2023-12-18 11:16:18+00:00
16k
John200410/rusherhack-spotify
src/main/java/me/john200410/spotify/SpotifyPlugin.java
[ { "identifier": "SpotifyAPI", "path": "src/main/java/me/john200410/spotify/http/SpotifyAPI.java", "snippet": "public class SpotifyAPI {\n\t\n\t/**\n\t * Constants\n\t */\n\tpublic static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient();\n\tprivate static final String API_URL = \"https://api.spo...
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sun.net.httpserver.HttpServer; import me.john200410.spotify.http.SpotifyAPI; import me.john200410.spotify.ui.SpotifyHudElement; import org.apache.commons.io.IOUtils; import org.rusherhack.client.api.RusherHackAPI; import org.rusherhack.client.api.plugin.Plugin; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.Objects;
13,254
package me.john200410.spotify; /** * @author John200410 */ public class SpotifyPlugin extends Plugin { public static final File CONFIG_FILE = RusherHackAPI.getConfigPath().resolve("spotify.json").toFile(); public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); private Config config = new Config(); private HttpServer httpServer; private SpotifyAPI api; @Override public void onLoad() { //try load config if(CONFIG_FILE.exists()) { try { this.config = GSON.fromJson(IOUtils.toString(CONFIG_FILE.toURI(), StandardCharsets.UTF_8), Config.class); } catch(IOException e) { this.logger.warn("Failed to load config"); } } try { this.httpServer = this.setupServer(); this.httpServer.start(); this.api = new SpotifyAPI(this); this.api.appID = this.config.appId; this.api.appSecret = this.config.appSecret; this.api.refreshToken = this.config.refresh_token; if(!this.api.appID.isEmpty() && !this.api.appSecret.isEmpty() && !this.api.refreshToken.isEmpty()) { try { this.api.authorizationRefreshToken(); } catch(Throwable t) { t.printStackTrace(); } } //hud element
package me.john200410.spotify; /** * @author John200410 */ public class SpotifyPlugin extends Plugin { public static final File CONFIG_FILE = RusherHackAPI.getConfigPath().resolve("spotify.json").toFile(); public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); private Config config = new Config(); private HttpServer httpServer; private SpotifyAPI api; @Override public void onLoad() { //try load config if(CONFIG_FILE.exists()) { try { this.config = GSON.fromJson(IOUtils.toString(CONFIG_FILE.toURI(), StandardCharsets.UTF_8), Config.class); } catch(IOException e) { this.logger.warn("Failed to load config"); } } try { this.httpServer = this.setupServer(); this.httpServer.start(); this.api = new SpotifyAPI(this); this.api.appID = this.config.appId; this.api.appSecret = this.config.appSecret; this.api.refreshToken = this.config.refresh_token; if(!this.api.appID.isEmpty() && !this.api.appSecret.isEmpty() && !this.api.refreshToken.isEmpty()) { try { this.api.authorizationRefreshToken(); } catch(Throwable t) { t.printStackTrace(); } } //hud element
RusherHackAPI.getHudManager().registerFeature(new SpotifyHudElement(this));
1
2023-12-19 17:59:37+00:00
16k
Swofty-Developments/HypixelSkyBlock
generic/src/main/java/net/swofty/types/generic/gui/inventory/inventories/GUIMinionRecipes.java
[ { "identifier": "ItemStackCreator", "path": "generic/src/main/java/net/swofty/types/generic/gui/inventory/ItemStackCreator.java", "snippet": "public class ItemStackCreator {\n\n public static ItemStack.Builder createNamedItemStack(Material material, String name) {\n return ItemStack.builder(ma...
import net.minestom.server.event.inventory.InventoryCloseEvent; import net.minestom.server.event.inventory.InventoryPreClickEvent; import net.minestom.server.inventory.Inventory; import net.minestom.server.inventory.InventoryType; import net.minestom.server.item.ItemStack; import net.minestom.server.item.Material; import net.swofty.types.generic.gui.inventory.ItemStackCreator; import net.swofty.types.generic.gui.inventory.SkyBlockInventoryGUI; import net.swofty.types.generic.gui.inventory.inventories.sbmenu.crafting.GUIRecipe; import net.swofty.types.generic.gui.inventory.item.GUIClickableItem; import net.swofty.types.generic.item.SkyBlockItem; import net.swofty.types.generic.item.attribute.attributes.ItemAttributeMinionData; import net.swofty.types.generic.item.updater.NonPlayerItemUpdater; import net.swofty.types.generic.minion.MinionRegistry; import net.swofty.types.generic.user.SkyBlockPlayer; import java.util.Arrays; import java.util.concurrent.atomic.AtomicInteger;
12,464
package net.swofty.types.generic.gui.inventory.inventories; public class GUIMinionRecipes extends SkyBlockInventoryGUI { private static final int[] RECIPE_SLOTS = new int[]{ 11, 12, 13, 14, 15, 21, 22, 23, 30, 31, 32 }; SkyBlockInventoryGUI previousGUI; MinionRegistry registry; public GUIMinionRecipes(MinionRegistry registry, SkyBlockInventoryGUI previousGUI) { super(registry.getDisplay() + " Recipes", InventoryType.CHEST_6_ROW); this.registry = registry; this.previousGUI = previousGUI; } @Override public void onOpen(InventoryGUIOpenEvent e) { fill(ItemStackCreator.createNamedItemStack(Material.BLACK_STAINED_GLASS_PANE)); set(GUIClickableItem.getCloseItem(49)); if (previousGUI != null) set(GUIClickableItem.getGoBackItem(48, previousGUI)); AtomicInteger i = new AtomicInteger(); Arrays.stream(RECIPE_SLOTS).forEach(slot -> { i.getAndIncrement(); SkyBlockItem item = new SkyBlockItem(registry.getItemType()); item.getAttributeHandler().setMinionData(new ItemAttributeMinionData.MinionData( i.get(), 0 )); set(new GUIClickableItem(slot) { @Override public void run(InventoryPreClickEvent e, SkyBlockPlayer player) { new GUIRecipe(item, GUIMinionRecipes.this).open(player); } @Override public ItemStack.Builder getItem(SkyBlockPlayer player) {
package net.swofty.types.generic.gui.inventory.inventories; public class GUIMinionRecipes extends SkyBlockInventoryGUI { private static final int[] RECIPE_SLOTS = new int[]{ 11, 12, 13, 14, 15, 21, 22, 23, 30, 31, 32 }; SkyBlockInventoryGUI previousGUI; MinionRegistry registry; public GUIMinionRecipes(MinionRegistry registry, SkyBlockInventoryGUI previousGUI) { super(registry.getDisplay() + " Recipes", InventoryType.CHEST_6_ROW); this.registry = registry; this.previousGUI = previousGUI; } @Override public void onOpen(InventoryGUIOpenEvent e) { fill(ItemStackCreator.createNamedItemStack(Material.BLACK_STAINED_GLASS_PANE)); set(GUIClickableItem.getCloseItem(49)); if (previousGUI != null) set(GUIClickableItem.getGoBackItem(48, previousGUI)); AtomicInteger i = new AtomicInteger(); Arrays.stream(RECIPE_SLOTS).forEach(slot -> { i.getAndIncrement(); SkyBlockItem item = new SkyBlockItem(registry.getItemType()); item.getAttributeHandler().setMinionData(new ItemAttributeMinionData.MinionData( i.get(), 0 )); set(new GUIClickableItem(slot) { @Override public void run(InventoryPreClickEvent e, SkyBlockPlayer player) { new GUIRecipe(item, GUIMinionRecipes.this).open(player); } @Override public ItemStack.Builder getItem(SkyBlockPlayer player) {
return new NonPlayerItemUpdater(item).getUpdatedItem();
6
2023-12-14 09:51:15+00:00
16k
Tianscar/uxgl
base/src/main/java/unrefined/context/Context.java
[ { "identifier": "Cursor", "path": "base/src/main/java/unrefined/media/graphics/Cursor.java", "snippet": "public abstract class Cursor {\n\n public static Cursor ofSystem(int type) throws CursorNotFoundException {\n return Drawing.getInstance().getCursor(type);\n }\n\n public static Curso...
import unrefined.media.graphics.Cursor; import unrefined.media.graphics.Dimension; import unrefined.media.graphics.Graphics; import unrefined.media.graphics.Point; import unrefined.media.graphics.Rectangle; import java.util.Objects;
14,386
package unrefined.context; public abstract class Context { private final Container container; private volatile ContextListener contextListener; public Context(Container container) { this(container, null); } public Context(Container container, ContextListener contextListener) { this.container = Objects.requireNonNull(container); this.contextListener = contextListener; } public Container getContainer() { return container; } public ContextListener getContextListener() { return contextListener; } public void setContextListener(ContextListener contextListener) { this.contextListener = contextListener; } public abstract void setX(int x); public abstract void setY(int y); public void setPosition(int x, int y) { setX(x); setY(y); } public abstract void setWidth(int width); public abstract void setHeight(int height); public void setSize(int width, int height) { setWidth(width); setHeight(height); } public void setBounds(int x, int y, int width, int height) { setPosition(x, y); setSize(width, height); } public abstract int getX(); public abstract int getY(); public void getPosition(Point position) { position.setPoint(getX(), getY()); } public abstract int getWidth(); public abstract int getHeight(); public void getSize(Dimension size) { size.setDimension(getWidth(), getHeight()); }
package unrefined.context; public abstract class Context { private final Container container; private volatile ContextListener contextListener; public Context(Container container) { this(container, null); } public Context(Container container, ContextListener contextListener) { this.container = Objects.requireNonNull(container); this.contextListener = contextListener; } public Container getContainer() { return container; } public ContextListener getContextListener() { return contextListener; } public void setContextListener(ContextListener contextListener) { this.contextListener = contextListener; } public abstract void setX(int x); public abstract void setY(int y); public void setPosition(int x, int y) { setX(x); setY(y); } public abstract void setWidth(int width); public abstract void setHeight(int height); public void setSize(int width, int height) { setWidth(width); setHeight(height); } public void setBounds(int x, int y, int width, int height) { setPosition(x, y); setSize(width, height); } public abstract int getX(); public abstract int getY(); public void getPosition(Point position) { position.setPoint(getX(), getY()); } public abstract int getWidth(); public abstract int getHeight(); public void getSize(Dimension size) { size.setDimension(getWidth(), getHeight()); }
public void getBounds(Rectangle bounds) {
4
2023-12-15 19:03:31+00:00
16k
Valerde/vadb
vadb-test/src/test/java/com/sovava/vadb/test/collection/map/Test1Part.java
[ { "identifier": "VaMap", "path": "va-collection/src/main/java/com/sovava/vacollection/api/VaMap.java", "snippet": "public interface VaMap<K, V> {\n int size();\n\n boolean isEmpty();\n\n boolean containsKey(Object key);\n\n boolean containValue(Object value);\n\n V get(Object key);\n\n ...
import com.sovava.vacollection.api.VaMap; import com.sovava.vacollection.api.VaSet; import com.sovava.vacollection.vamap.VaHashMap; import com.sovava.vadb.test.collection.utils.RandomObject; import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.Test; import java.util.*;
11,137
package com.sovava.vadb.test.collection.map; /** * Description: * VaHashMap已支持array+链表的方式存储,这个类测试已有功能 * * @author: ykn * @date: 2023年12月24日 6:29 PM **/ @Slf4j public class Test1Part { /** * description: * <p>测试结果: * <p>1. 编译错误,VaArrays中copyOf方法错误,需要强转为Object * <p>2. 代码优化,getNode方法中起始处定义变量优化语法 * * @Author sovava * @Date 12/24/23 7:14 PM */ @Test public void testBasicFunc() { VaMap<String, String> map = new VaHashMap<>(); map.put("ykn", "vbf"); map.put("cuh", "uabi"); map.put("zzz", "dage"); String zzz = map.get("zzz"); Assert.assertEquals("dage", zzz); map.put("zzz", "fage2"); Assert.assertEquals("fage2", map.get("zzz")); map.putIfAbsent("ykn", "test"); Assert.assertEquals("vbf", map.getOrDefault("ykn", "def")); Assert.assertTrue(map.containsKey("ykn")); map.remove("ykn"); Assert.assertNull(map.get("ykn")); Assert.assertEquals("def", map.getOrDefault("ykn", "def")); Assert.assertEquals(2, map.size()); map.clear(); Assert.assertTrue(map.isEmpty()); Assert.assertEquals(0, map.size()); map.putIfAbsent("ykn", "test"); Assert.assertEquals(map.get("ykn"), "test"); map.replace("ykn", "test", "test1"); Assert.assertEquals(map.get("ykn"), "test1"); map.replace("ykn", "test", "test2"); Assert.assertEquals(map.get("ykn"), "test1"); map.replace("ykn", "test3"); Assert.assertEquals(map.get("ykn"), "test3"); } /** * description:这个方法没有Assert,debug进入方法内看到了链表存在通过验证 * <p>测试结果:putValue方法中 p = newNode(hash, key, value, null); -> node.next = newNode(hash, key, value, null); * * @Author sovava * @Date 12/24/23 7:16 PM */ @Test public void testLinkedList() { VaMap<Integer, Integer> vmap = new VaHashMap<>(); Map<Integer, Integer> map = new HashMap<>(); Random rd = new Random(); for (int i = 0; i < 100; i++) { int key = rd.nextInt(); int value = rd.nextInt(); vmap.put(key, value); map.put(key, value); } for (int i = 0; i < 10; i++) { int key = rd.nextInt(); int value = rd.nextInt(); vmap.put(key, value); map.put(key, value); } } /** * description: * 测试结果:resize方法中 * <p>1. else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap > DEFAULT_INITIAL_CAPACITY) 忽略oldCap = Default_* * <p>2. float thr = newCap * loadFactor; newCap需要强转类型(float) * <p>3. ((newCap -1) & head.hash) rehash条件判断错误 * * @Author sovava * @Date 12/24/23 8:01 PM */ @Test public void testResize() { VaMap<String, String> vmap = new VaHashMap<>(); Map<String, String> map2 = new HashMap<>(); for (int i = 0; i < 100; i++) {
package com.sovava.vadb.test.collection.map; /** * Description: * VaHashMap已支持array+链表的方式存储,这个类测试已有功能 * * @author: ykn * @date: 2023年12月24日 6:29 PM **/ @Slf4j public class Test1Part { /** * description: * <p>测试结果: * <p>1. 编译错误,VaArrays中copyOf方法错误,需要强转为Object * <p>2. 代码优化,getNode方法中起始处定义变量优化语法 * * @Author sovava * @Date 12/24/23 7:14 PM */ @Test public void testBasicFunc() { VaMap<String, String> map = new VaHashMap<>(); map.put("ykn", "vbf"); map.put("cuh", "uabi"); map.put("zzz", "dage"); String zzz = map.get("zzz"); Assert.assertEquals("dage", zzz); map.put("zzz", "fage2"); Assert.assertEquals("fage2", map.get("zzz")); map.putIfAbsent("ykn", "test"); Assert.assertEquals("vbf", map.getOrDefault("ykn", "def")); Assert.assertTrue(map.containsKey("ykn")); map.remove("ykn"); Assert.assertNull(map.get("ykn")); Assert.assertEquals("def", map.getOrDefault("ykn", "def")); Assert.assertEquals(2, map.size()); map.clear(); Assert.assertTrue(map.isEmpty()); Assert.assertEquals(0, map.size()); map.putIfAbsent("ykn", "test"); Assert.assertEquals(map.get("ykn"), "test"); map.replace("ykn", "test", "test1"); Assert.assertEquals(map.get("ykn"), "test1"); map.replace("ykn", "test", "test2"); Assert.assertEquals(map.get("ykn"), "test1"); map.replace("ykn", "test3"); Assert.assertEquals(map.get("ykn"), "test3"); } /** * description:这个方法没有Assert,debug进入方法内看到了链表存在通过验证 * <p>测试结果:putValue方法中 p = newNode(hash, key, value, null); -> node.next = newNode(hash, key, value, null); * * @Author sovava * @Date 12/24/23 7:16 PM */ @Test public void testLinkedList() { VaMap<Integer, Integer> vmap = new VaHashMap<>(); Map<Integer, Integer> map = new HashMap<>(); Random rd = new Random(); for (int i = 0; i < 100; i++) { int key = rd.nextInt(); int value = rd.nextInt(); vmap.put(key, value); map.put(key, value); } for (int i = 0; i < 10; i++) { int key = rd.nextInt(); int value = rd.nextInt(); vmap.put(key, value); map.put(key, value); } } /** * description: * 测试结果:resize方法中 * <p>1. else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap > DEFAULT_INITIAL_CAPACITY) 忽略oldCap = Default_* * <p>2. float thr = newCap * loadFactor; newCap需要强转类型(float) * <p>3. ((newCap -1) & head.hash) rehash条件判断错误 * * @Author sovava * @Date 12/24/23 8:01 PM */ @Test public void testResize() { VaMap<String, String> vmap = new VaHashMap<>(); Map<String, String> map2 = new HashMap<>(); for (int i = 0; i < 100; i++) {
String key = RandomObject.getRandomString(10);
3
2023-12-17 13:29:10+00:00
16k
litongjava/next-jfinal
src/main/java/com/jfinal/core/JFinal.java
[ { "identifier": "Constants", "path": "src/main/java/com/jfinal/config/Constants.java", "snippet": "final public class Constants {\n\t\n\tprivate boolean devMode = Const.DEFAULT_DEV_MODE;\n\t\n\tprivate String baseUploadPath = Const.DEFAULT_BASE_UPLOAD_PATH;\n\tprivate String baseDownloadPath = Const.DEF...
import java.util.List; import com.jfinal.config.Constants; import com.jfinal.config.JFinalConfig; import com.jfinal.handler.Handler; import com.jfinal.handler.HandlerFactory; import com.jfinal.kit.LogKit; import com.jfinal.kit.PathKit; import com.jfinal.plugin.IPlugin; import com.jfinal.render.RenderManager; import com.jfinal.server.IServer; import com.jfinal.servlet.ServletContext; import com.jfinal.token.ITokenCache; import com.jfinal.token.TokenManager; import com.jfinal.upload.UploadConfig;
10,927
/** * Copyright (c) 2011-2023, James Zhan 詹波 (jfinal@126.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.jfinal.core; /** * JFinal */ public final class JFinal { private Constants constants; private ActionMapping actionMapping; private Handler handler; private ServletContext servletContext; private String contextPath = ""; private static IServer server; private static final JFinal me = new JFinal(); private JFinal() { } public static JFinal me() { return me; } public void init(JFinalConfig jfinalConfig, ServletContext servletContext) { this.servletContext = servletContext; this.contextPath = servletContext.getContextPath(); initPathKit(); Config.configJFinal(jfinalConfig); // start plugin, init log factory and init engine in this method constants = Config.getConstants(); initActionMapping(); initHandler(); initRender(); initUploadConfig(); initTokenManager(); } private void initTokenManager() {
/** * Copyright (c) 2011-2023, James Zhan 詹波 (jfinal@126.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.jfinal.core; /** * JFinal */ public final class JFinal { private Constants constants; private ActionMapping actionMapping; private Handler handler; private ServletContext servletContext; private String contextPath = ""; private static IServer server; private static final JFinal me = new JFinal(); private JFinal() { } public static JFinal me() { return me; } public void init(JFinalConfig jfinalConfig, ServletContext servletContext) { this.servletContext = servletContext; this.contextPath = servletContext.getContextPath(); initPathKit(); Config.configJFinal(jfinalConfig); // start plugin, init log factory and init engine in this method constants = Config.getConstants(); initActionMapping(); initHandler(); initRender(); initUploadConfig(); initTokenManager(); } private void initTokenManager() {
ITokenCache tokenCache = constants.getTokenCache();
10
2023-12-19 10:58:33+00:00
16k
HypixelSkyblockmod/ChromaHud
src/java/xyz/apfelmus/cheeto/client/modules/world/SecretAura.java
[ { "identifier": "CF4M", "path": "src/java/xyz/apfelmus/cf4m/CF4M.java", "snippet": "public enum CF4M {\n INSTANCE;\n\n public String packName;\n public String dir;\n public IConfiguration configuration;\n public ClassManager classManager;\n public EventManager eventManager;\n public...
import com.mojang.authlib.GameProfile; import java.util.ArrayList; import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.BlockChest; import net.minecraft.block.BlockLever; import net.minecraft.block.BlockSkull; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.inventory.GuiChest; import net.minecraft.init.Blocks; import net.minecraft.tileentity.TileEntityChest; import net.minecraft.tileentity.TileEntitySkull; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.util.MathHelper; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import xyz.apfelmus.cf4m.CF4M; import xyz.apfelmus.cf4m.annotation.Event; import xyz.apfelmus.cf4m.annotation.Setting; import xyz.apfelmus.cf4m.annotation.module.Enable; import xyz.apfelmus.cf4m.annotation.module.Module; import xyz.apfelmus.cf4m.module.Category; import xyz.apfelmus.cheeto.client.events.ClientChatReceivedEvent; import xyz.apfelmus.cheeto.client.events.ClientTickEvent; import xyz.apfelmus.cheeto.client.events.PlayerInteractEvent; import xyz.apfelmus.cheeto.client.events.Render3DEvent; import xyz.apfelmus.cheeto.client.events.WorldUnloadEvent; import xyz.apfelmus.cheeto.client.settings.BooleanSetting; import xyz.apfelmus.cheeto.client.settings.FloatSetting; import xyz.apfelmus.cheeto.client.settings.IntegerSetting; import xyz.apfelmus.cheeto.client.utils.client.RotationUtils; import xyz.apfelmus.cheeto.client.utils.render.Render3DUtils; import xyz.apfelmus.cheeto.client.utils.skyblock.SkyblockUtils;
12,934
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * com.mojang.authlib.GameProfile * net.minecraft.block.Block * net.minecraft.block.BlockChest * net.minecraft.block.BlockLever * net.minecraft.block.BlockSkull * net.minecraft.block.state.IBlockState * net.minecraft.client.Minecraft * net.minecraft.client.gui.inventory.GuiChest * net.minecraft.init.Blocks * net.minecraft.tileentity.TileEntityChest * net.minecraft.tileentity.TileEntitySkull * net.minecraft.util.BlockPos * net.minecraft.util.EnumFacing * net.minecraft.util.MathHelper * net.minecraft.util.MovingObjectPosition * net.minecraft.util.MovingObjectPosition$MovingObjectType * net.minecraft.util.Vec3 * net.minecraftforge.event.entity.player.PlayerInteractEvent$Action */ package xyz.apfelmus.cheeto.client.modules.world; @Module(name="SecretAura", category=Category.WORLD) public class SecretAura implements Runnable { @Setting(name="ScanRange") private IntegerSetting scanRange = new IntegerSetting(7, 0, 8); @Setting(name="ClickRange")
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * com.mojang.authlib.GameProfile * net.minecraft.block.Block * net.minecraft.block.BlockChest * net.minecraft.block.BlockLever * net.minecraft.block.BlockSkull * net.minecraft.block.state.IBlockState * net.minecraft.client.Minecraft * net.minecraft.client.gui.inventory.GuiChest * net.minecraft.init.Blocks * net.minecraft.tileentity.TileEntityChest * net.minecraft.tileentity.TileEntitySkull * net.minecraft.util.BlockPos * net.minecraft.util.EnumFacing * net.minecraft.util.MathHelper * net.minecraft.util.MovingObjectPosition * net.minecraft.util.MovingObjectPosition$MovingObjectType * net.minecraft.util.Vec3 * net.minecraftforge.event.entity.player.PlayerInteractEvent$Action */ package xyz.apfelmus.cheeto.client.modules.world; @Module(name="SecretAura", category=Category.WORLD) public class SecretAura implements Runnable { @Setting(name="ScanRange") private IntegerSetting scanRange = new IntegerSetting(7, 0, 8); @Setting(name="ClickRange")
private FloatSetting clickRange = new FloatSetting(Float.valueOf(5.0f), Float.valueOf(0.0f), Float.valueOf(8.0f));
8
2023-12-21 16:22:25+00:00
16k
emtee40/ApkSignatureKill-pc
app/src/main/java/org/jf/dexlib2/dexbacked/DexBackedMethodImplementation.java
[ { "identifier": "DexBackedInstruction", "path": "app/src/main/java/org/jf/dexlib2/dexbacked/instruction/DexBackedInstruction.java", "snippet": "public abstract class DexBackedInstruction implements Instruction {\n @NonNull\n public final DexBackedDexFile dexFile;\n @NonNull\n public final Op...
import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.common.collect.ImmutableList; import org.jf.dexlib2.dexbacked.instruction.DexBackedInstruction; import org.jf.dexlib2.dexbacked.raw.CodeItem; import org.jf.dexlib2.dexbacked.util.DebugInfo; import org.jf.dexlib2.dexbacked.util.FixedSizeList; import org.jf.dexlib2.dexbacked.util.VariableSizeListIterator; import org.jf.dexlib2.dexbacked.util.VariableSizeLookaheadIterator; import org.jf.dexlib2.iface.MethodImplementation; import org.jf.dexlib2.iface.debug.DebugItem; import org.jf.dexlib2.iface.instruction.Instruction; import org.jf.util.AlignmentUtils; import org.jf.util.ExceptionWithContext; import java.util.Iterator; import java.util.List;
10,970
/* * 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 DexBackedMethodImplementation implements MethodImplementation { @NonNull public final DexBackedDexFile dexFile; @NonNull public final DexBackedMethod method; private final int codeOffset; public DexBackedMethodImplementation(@NonNull DexBackedDexFile dexFile, @NonNull DexBackedMethod method, int codeOffset) { this.dexFile = dexFile; this.method = method; this.codeOffset = codeOffset; } @Override public int getRegisterCount() { return dexFile.readUshort(codeOffset); } @NonNull @Override
/* * 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 DexBackedMethodImplementation implements MethodImplementation { @NonNull public final DexBackedDexFile dexFile; @NonNull public final DexBackedMethod method; private final int codeOffset; public DexBackedMethodImplementation(@NonNull DexBackedDexFile dexFile, @NonNull DexBackedMethod method, int codeOffset) { this.dexFile = dexFile; this.method = method; this.codeOffset = codeOffset; } @Override public int getRegisterCount() { return dexFile.readUshort(codeOffset); } @NonNull @Override
public Iterable<? extends Instruction> getInstructions() {
8
2023-12-16 11:11:16+00:00
16k
123yyh123/xiaofanshu
xfs-modules-server/xfs-user-server/src/main/java/com/yyh/xfs/user/service/impl/UserServiceImpl.java
[ { "identifier": "Result", "path": "xfs-common/common-base/src/main/java/com/yyh/xfs/common/domain/Result.java", "snippet": "@Setter\n@Getter\n@ToString\n@AllArgsConstructor\n@NoArgsConstructor\npublic class Result<T> implements Serializable {\n private Integer code;\n private String msg;\n priv...
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.toolkit.support.SFunction; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.yyh.xfs.common.domain.Result; import com.yyh.xfs.common.myEnum.ExceptionMsgEnum; 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.common.utils.CodeUtil; import com.yyh.xfs.common.utils.Md5Util; import com.yyh.xfs.common.utils.ResultUtil; import com.yyh.xfs.common.utils.TimeUtil; import com.yyh.xfs.common.web.exception.BusinessException; import com.yyh.xfs.common.web.exception.SystemException; import com.yyh.xfs.common.web.properties.JwtProperties; import com.yyh.xfs.common.web.utils.IPUtils; import com.yyh.xfs.common.web.utils.JWTUtil; import com.yyh.xfs.user.domain.UserAttentionDO; import com.yyh.xfs.user.domain.UserDO; import com.yyh.xfs.user.mapper.UserAttentionMapper; import com.yyh.xfs.user.mapper.UserFansMapper; import com.yyh.xfs.user.service.UserService; import com.yyh.xfs.user.mapper.UserMapper; import com.yyh.xfs.user.vo.RegisterInfoVO; import com.yyh.xfs.user.vo.UserTrtcVO; import com.yyh.xfs.user.vo.UserVO; import com.yyh.xfs.user.vo.ViewUserVO; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import java.sql.Date; import java.util.HashMap; import java.util.Map; import java.util.Objects;
13,451
package com.yyh.xfs.user.service.impl; /** * @author yyh * @date 2023-12-11 * 用户服务实现 */ @Service @Slf4j public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService { private static final String DEFAULT_NICKNAME_PREFIX = "小番薯用户"; private final JwtProperties jwtProperties; private final RedisCache redisCache; private final HttpServletRequest request; private final UserAttentionMapper userAttentionMapper; private final UserFansMapper userFansMapper; public UserServiceImpl(RedisCache redisCache, JwtProperties jwtProperties, HttpServletRequest request, UserAttentionMapper userAttentionMapper, UserFansMapper userFansMapper) { this.redisCache = redisCache; this.jwtProperties = jwtProperties; this.request = request; this.userAttentionMapper = userAttentionMapper; this.userFansMapper = userFansMapper; } /** * 登录类型和数据库字段的映射 */ private static final Map<Integer, SFunction<UserDO, String>> LOGIN_TYPE_MAP = new HashMap<>(); /** * 初始化 */ @PostConstruct public void postConstruct() { LOGIN_TYPE_MAP.put(1, UserDO::getWxOpenId); LOGIN_TYPE_MAP.put(2, UserDO::getQqOpenId); LOGIN_TYPE_MAP.put(3, UserDO::getFacebookOpenId); } /** * 手机号登录 * * @param phoneNumber 手机号 * @param password 密码 * @return UserDO */ @Override
package com.yyh.xfs.user.service.impl; /** * @author yyh * @date 2023-12-11 * 用户服务实现 */ @Service @Slf4j public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService { private static final String DEFAULT_NICKNAME_PREFIX = "小番薯用户"; private final JwtProperties jwtProperties; private final RedisCache redisCache; private final HttpServletRequest request; private final UserAttentionMapper userAttentionMapper; private final UserFansMapper userFansMapper; public UserServiceImpl(RedisCache redisCache, JwtProperties jwtProperties, HttpServletRequest request, UserAttentionMapper userAttentionMapper, UserFansMapper userFansMapper) { this.redisCache = redisCache; this.jwtProperties = jwtProperties; this.request = request; this.userAttentionMapper = userAttentionMapper; this.userFansMapper = userFansMapper; } /** * 登录类型和数据库字段的映射 */ private static final Map<Integer, SFunction<UserDO, String>> LOGIN_TYPE_MAP = new HashMap<>(); /** * 初始化 */ @PostConstruct public void postConstruct() { LOGIN_TYPE_MAP.put(1, UserDO::getWxOpenId); LOGIN_TYPE_MAP.put(2, UserDO::getQqOpenId); LOGIN_TYPE_MAP.put(3, UserDO::getFacebookOpenId); } /** * 手机号登录 * * @param phoneNumber 手机号 * @param password 密码 * @return UserDO */ @Override
public Result<UserVO> login(String phoneNumber, String password) {
0
2023-12-15 08:13:42+00:00
16k
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;
12,000
@SuppressLint("SetJavaScriptEnabled") private static void prepareWebViewSettings(Context context, WebSettings settings) { ProfileManager.ensureInitialized(context); settings.setUserAgentString(Build.INSTANCE.generateWebViewUserAgentString(settings.getUserAgentString()) + MAGIC_USER_AGENT); settings.setJavaScriptEnabled(true); settings.setSupportMultipleWindows(false); settings.setSaveFormData(false); settings.setAllowFileAccess(false); settings.setDatabaseEnabled(false); settings.setNeedInitialFocus(false); settings.setUseWideViewPort(false); settings.setSupportZoom(false); settings.setJavaScriptCanOpenWindowsAutomatically(false); } private void start() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = cm.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { if (LastCheckinInfo.read(this).getAndroidId() == 0) { new Thread(() -> { Runnable next; next = checkin(false) ? this::loadLoginPage : () -> showError(R.string.auth_general_error_desc); LoginActivity.this.runOnUiThread(next); }).start(); } else { loadLoginPage(); } } else { showError(R.string.no_network_error_desc); } } private void showError(int errorRes) { setTitle(R.string.sorry); findViewById(R.id.progress_bar).setVisibility(View.INVISIBLE); setMessage(errorRes); } private void setMessage(@StringRes int res) { setMessage(getText(res)); } private void setMessage(CharSequence text) { ((TextView) findViewById(R.id.description_text)).setText(text); } private void loadLoginPage() { String tmpl = getIntent().hasExtra(EXTRA_TMPL) ? getIntent().getStringExtra(EXTRA_TMPL) : TMPL_NEW_ACCOUNT; webView.loadUrl(buildUrl(tmpl, Utils.getLocale(this))); } protected void runScript(String js) { runOnUiThread(() -> webView.loadUrl("javascript:" + js)); } private void closeWeb(boolean programmaticAuth) { setMessage(R.string.auth_finalize); runOnUiThread(() -> webView.setVisibility(INVISIBLE)); String cookies = CookieManager.getInstance().getCookie(programmaticAuth ? PROGRAMMATIC_AUTH_URL : EMBEDDED_SETUP_URL); String[] temp = cookies.split(";"); for (String ar1 : temp) { if (ar1.trim().startsWith(COOKIE_OAUTH_TOKEN + "=")) { String[] temp1 = ar1.split("="); retrieveRtToken(temp1[1]); return; } } showError(R.string.auth_general_error_desc); } private void retrieveRtToken(String oAuthToken) { new AuthRequest().fromContext(this) .appIsGms() .callerIsGms() .service("ac2dm") .token(oAuthToken).isAccessToken() .addAccount() .getAccountId() .getResponseAsync(new HttpFormClient.Callback<AuthResponse>() { @Override public void onResponse(AuthResponse response) { Account account = new Account(response.email, accountType); if (accountManager.addAccountExplicitly(account, response.token, null)) { accountManager.setAuthToken(account, "SID", response.Sid); accountManager.setAuthToken(account, "LSID", response.LSid); accountManager.setUserData(account, "flags", "1"); accountManager.setUserData(account, "services", response.services); accountManager.setUserData(account, "oauthAccessToken", "1"); accountManager.setUserData(account, "firstName", response.firstName); accountManager.setUserData(account, "lastName", response.lastName); if (!TextUtils.isEmpty(response.accountId)) accountManager.setUserData(account, "GoogleUserId", response.accountId); retrieveGmsToken(account); setResult(RESULT_OK); } else { Log.w(TAG, "Account NOT created!"); runOnUiThread(() -> { showError(R.string.auth_general_error_desc); setNextButtonText(android.R.string.ok); }); state = -2; } } @Override public void onException(Exception exception) { Log.w(TAG, "onException", exception); runOnUiThread(() -> { showError(R.string.auth_general_error_desc); setNextButtonText(android.R.string.ok); }); state = -2; } }); } private void retrieveGmsToken(final Account account) {
/* * 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; accountManager = AccountManager.get(LoginActivity.this); inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); webView = createWebView(this); webView.addJavascriptInterface(new JsBridge(), "mm"); authContent = (ViewGroup) findViewById(R.id.auth_content); ((ViewGroup) findViewById(R.id.auth_root)).addView(webView); webView.setWebViewClient(new WebViewClientCompat() { @Override public void onPageFinished(WebView view, String url) { Log.d(TAG, "pageFinished: " + view.getUrl()); Uri uri = Uri.parse(view.getUrl()); // Begin login. // Only required if client code does not invoke showView() via JSBridge if ("identifier".equals(uri.getFragment()) || uri.getPath().endsWith("/identifier")) runOnUiThread(() -> webView.setVisibility(VISIBLE)); // Normal login. if ("close".equals(uri.getFragment())) closeWeb(false); // Google Suite login. if (url.startsWith(GOOGLE_SUITE_URL)) closeWeb(false); // IDK when this is called. if (url.startsWith(PROGRAMMATIC_AUTH_URL)) closeWeb(true); } }); if (getIntent().hasExtra(EXTRA_TOKEN)) { if (getIntent().hasExtra(EXTRA_EMAIL)) { AccountManager accountManager = AccountManager.get(this); Account account = new Account(getIntent().getStringExtra(EXTRA_EMAIL), accountType); accountManager.addAccountExplicitly(account, getIntent().getStringExtra(EXTRA_TOKEN), null); if (isAuthVisible(this) && SDK_INT >= 26) { accountManager.setAccountVisibility(account, PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE, VISIBILITY_USER_MANAGED_VISIBLE); } retrieveGmsToken(account); } else { retrieveRtToken(getIntent().getStringExtra(EXTRA_TOKEN)); } } else if (android.os.Build.VERSION.SDK_INT < 21) { init(); } else { setMessage(R.string.auth_before_connect); setSpoofButtonText(R.string.brand_spoof_button); setNextButtonText(R.string.auth_sign_in); } } @Override protected void onNextButtonClicked() { super.onNextButtonClicked(); state++; if (state == 1) { if (isSpoofingEnabled(this)) { LastCheckinInfo.clear(this); setSpoofingEnabled(this, false); } init(); } else if (state == -1) { setResult(RESULT_CANCELED); finish(); } } @Override protected void onHuaweiButtonClicked() { super.onHuaweiButtonClicked(); state++; if (state == 1) { PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean("pref_hide_launcher_icon", false).apply(); if (!isSpoofingEnabled(this)) { LastCheckinInfo.clear(this); setSpoofingEnabled(this, true); } init(); } else if (state == -1) { setResult(RESULT_CANCELED); finish(); } } private void init() { setTitle(R.string.just_a_sec); setSpoofButtonText(null); setNextButtonText(null); View loading = getLayoutInflater().inflate(R.layout.login_assistant_loading, authContent, false); authContent.removeAllViews(); authContent.addView(loading); setMessage(R.string.auth_connecting); CookieManager.getInstance().setAcceptCookie(true); if (SDK_INT >= LOLLIPOP) { CookieManager.getInstance().removeAllCookies(value -> start()); } else { //noinspection deprecation CookieManager.getInstance().removeAllCookie(); start(); } } private static WebView createWebView(Context context) { WebView webView = new WebView(context); if (SDK_INT < LOLLIPOP) { webView.setVisibility(VISIBLE); } else { webView.setVisibility(INVISIBLE); } webView.setLayoutParams(new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); webView.setBackgroundColor(Color.TRANSPARENT); prepareWebViewSettings(context, webView.getSettings()); return webView; } @SuppressLint("SetJavaScriptEnabled") private static void prepareWebViewSettings(Context context, WebSettings settings) { ProfileManager.ensureInitialized(context); settings.setUserAgentString(Build.INSTANCE.generateWebViewUserAgentString(settings.getUserAgentString()) + MAGIC_USER_AGENT); settings.setJavaScriptEnabled(true); settings.setSupportMultipleWindows(false); settings.setSaveFormData(false); settings.setAllowFileAccess(false); settings.setDatabaseEnabled(false); settings.setNeedInitialFocus(false); settings.setUseWideViewPort(false); settings.setSupportZoom(false); settings.setJavaScriptCanOpenWindowsAutomatically(false); } private void start() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = cm.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { if (LastCheckinInfo.read(this).getAndroidId() == 0) { new Thread(() -> { Runnable next; next = checkin(false) ? this::loadLoginPage : () -> showError(R.string.auth_general_error_desc); LoginActivity.this.runOnUiThread(next); }).start(); } else { loadLoginPage(); } } else { showError(R.string.no_network_error_desc); } } private void showError(int errorRes) { setTitle(R.string.sorry); findViewById(R.id.progress_bar).setVisibility(View.INVISIBLE); setMessage(errorRes); } private void setMessage(@StringRes int res) { setMessage(getText(res)); } private void setMessage(CharSequence text) { ((TextView) findViewById(R.id.description_text)).setText(text); } private void loadLoginPage() { String tmpl = getIntent().hasExtra(EXTRA_TMPL) ? getIntent().getStringExtra(EXTRA_TMPL) : TMPL_NEW_ACCOUNT; webView.loadUrl(buildUrl(tmpl, Utils.getLocale(this))); } protected void runScript(String js) { runOnUiThread(() -> webView.loadUrl("javascript:" + js)); } private void closeWeb(boolean programmaticAuth) { setMessage(R.string.auth_finalize); runOnUiThread(() -> webView.setVisibility(INVISIBLE)); String cookies = CookieManager.getInstance().getCookie(programmaticAuth ? PROGRAMMATIC_AUTH_URL : EMBEDDED_SETUP_URL); String[] temp = cookies.split(";"); for (String ar1 : temp) { if (ar1.trim().startsWith(COOKIE_OAUTH_TOKEN + "=")) { String[] temp1 = ar1.split("="); retrieveRtToken(temp1[1]); return; } } showError(R.string.auth_general_error_desc); } private void retrieveRtToken(String oAuthToken) { new AuthRequest().fromContext(this) .appIsGms() .callerIsGms() .service("ac2dm") .token(oAuthToken).isAccessToken() .addAccount() .getAccountId() .getResponseAsync(new HttpFormClient.Callback<AuthResponse>() { @Override public void onResponse(AuthResponse response) { Account account = new Account(response.email, accountType); if (accountManager.addAccountExplicitly(account, response.token, null)) { accountManager.setAuthToken(account, "SID", response.Sid); accountManager.setAuthToken(account, "LSID", response.LSid); accountManager.setUserData(account, "flags", "1"); accountManager.setUserData(account, "services", response.services); accountManager.setUserData(account, "oauthAccessToken", "1"); accountManager.setUserData(account, "firstName", response.firstName); accountManager.setUserData(account, "lastName", response.lastName); if (!TextUtils.isEmpty(response.accountId)) accountManager.setUserData(account, "GoogleUserId", response.accountId); retrieveGmsToken(account); setResult(RESULT_OK); } else { Log.w(TAG, "Account NOT created!"); runOnUiThread(() -> { showError(R.string.auth_general_error_desc); setNextButtonText(android.R.string.ok); }); state = -2; } } @Override public void onException(Exception exception) { Log.w(TAG, "onException", exception); runOnUiThread(() -> { showError(R.string.auth_general_error_desc); setNextButtonText(android.R.string.ok); }); state = -2; } }); } private void retrieveGmsToken(final Account account) {
final AuthManager authManager = new AuthManager(this, account.name, GOOGLE_GMS_PACKAGE_NAME, "ac2dm");
10
2023-12-17 16:14:53+00:00
16k
Yolka5/FTC-Imu3
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/SampleMecanumDrive.java
[ { "identifier": "TrajectorySequence", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/trajectorysequence/TrajectorySequence.java", "snippet": "public class TrajectorySequence {\n private final List<SequenceSegment> sequenceList;\n\n public TrajectorySequence(List<SequenceSegment> se...
import androidx.annotation.NonNull; import com.acmerobotics.dashboard.config.Config; import com.acmerobotics.roadrunner.control.PIDCoefficients; import com.acmerobotics.roadrunner.drive.DriveSignal; import com.acmerobotics.roadrunner.drive.MecanumDrive; import com.acmerobotics.roadrunner.followers.HolonomicPIDVAFollower; import com.acmerobotics.roadrunner.followers.TrajectoryFollower; import com.acmerobotics.roadrunner.geometry.Pose2d; import com.acmerobotics.roadrunner.trajectory.Trajectory; import com.acmerobotics.roadrunner.trajectory.TrajectoryBuilder; import com.acmerobotics.roadrunner.trajectory.constraints.AngularVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MecanumVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MinVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.ProfileAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryVelocityConstraint; import com.qualcomm.hardware.bosch.BNO055IMU; import com.qualcomm.hardware.lynx.LynxModule; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorEx; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.PIDFCoefficients; import com.qualcomm.robotcore.hardware.VoltageSensor; import com.qualcomm.robotcore.hardware.configuration.typecontainers.MotorConfigurationType; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequence; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceBuilder; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceRunner; import org.firstinspires.ftc.teamcode.util.LynxModuleUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MOTOR_VELO_PID; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.RUN_USING_ENCODER; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.TRACK_WIDTH; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.encoderTicksToInches; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kA; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kStatic; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kV;
12,221
public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, boolean reversed) { return new TrajectoryBuilder(startPose, reversed, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, double startHeading) { return new TrajectoryBuilder(startPose, startHeading, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectorySequenceBuilder trajectorySequenceBuilder(Pose2d startPose) { return new TrajectorySequenceBuilder( startPose, VEL_CONSTRAINT, ACCEL_CONSTRAINT, MAX_ANG_VEL, MAX_ANG_ACCEL ); } public void turnAsync(double angle) { trajectorySequenceRunner.followTrajectorySequenceAsync( trajectorySequenceBuilder(getPoseEstimate()) .turn(angle) .build() ); } public void turn(double angle) { turnAsync(angle); waitForIdle(); } public void followTrajectoryAsync(Trajectory trajectory) { trajectorySequenceRunner.followTrajectorySequenceAsync( trajectorySequenceBuilder(trajectory.start()) .addTrajectory(trajectory) .build() ); } public void followTrajectory(Trajectory trajectory) { followTrajectoryAsync(trajectory); waitForIdle(); } public void followTrajectorySequenceAsync(TrajectorySequence trajectorySequence) { trajectorySequenceRunner.followTrajectorySequenceAsync(trajectorySequence); } public void followTrajectorySequence(TrajectorySequence trajectorySequence) { followTrajectorySequenceAsync(trajectorySequence); waitForIdle(); } public Pose2d getLastError() { return trajectorySequenceRunner.getLastPoseError(); } public void update() { updatePoseEstimate(); DriveSignal signal = trajectorySequenceRunner.update(getPoseEstimate(), getPoseVelocity()); if (signal != null) setDriveSignal(signal); } public void waitForIdle() { while (!Thread.currentThread().isInterrupted() && isBusy()) update(); } public boolean isBusy() { return trajectorySequenceRunner.isBusy(); } public void setMode(DcMotor.RunMode runMode) { for (DcMotorEx motor : motors) { motor.setMode(runMode); } } public void setZeroPowerBehavior(DcMotor.ZeroPowerBehavior zeroPowerBehavior) { for (DcMotorEx motor : motors) { motor.setZeroPowerBehavior(zeroPowerBehavior); } } public void setPIDFCoefficients(DcMotor.RunMode runMode, PIDFCoefficients coefficients) { PIDFCoefficients compensatedCoefficients = new PIDFCoefficients( coefficients.p, coefficients.i, coefficients.d, coefficients.f * 12 / batteryVoltageSensor.getVoltage() ); for (DcMotorEx motor : motors) { motor.setPIDFCoefficients(runMode, compensatedCoefficients); } } public void setWeightedDrivePower(Pose2d drivePower) { Pose2d vel = drivePower; if (Math.abs(drivePower.getX()) + Math.abs(drivePower.getY()) + Math.abs(drivePower.getHeading()) > 1) { // re-normalize the powers according to the weights double denom = VX_WEIGHT * Math.abs(drivePower.getX()) + VY_WEIGHT * Math.abs(drivePower.getY()) + OMEGA_WEIGHT * Math.abs(drivePower.getHeading()); vel = new Pose2d( VX_WEIGHT * drivePower.getX(), VY_WEIGHT * drivePower.getY(), OMEGA_WEIGHT * drivePower.getHeading() ).div(denom); } setDrivePower(vel); } @NonNull @Override public List<Double> getWheelPositions() { List<Double> wheelPositions = new ArrayList<>(); for (DcMotorEx motor : motors) {
package org.firstinspires.ftc.teamcode.drive; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config public class SampleMecanumDrive extends MecanumDrive { public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(2, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(1, 0, 0); public static double LATERAL_MULTIPLIER = 1; public static double VX_WEIGHT = 1; public static double VY_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner; private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(MAX_VEL, MAX_ANG_VEL, TRACK_WIDTH); private static final TrajectoryAccelerationConstraint ACCEL_CONSTRAINT = getAccelerationConstraint(MAX_ACCEL); private TrajectoryFollower follower; private DcMotorEx leftFront, leftRear, rightRear, rightFront; private List<DcMotorEx> motors; private BNO055IMU imu; private VoltageSensor batteryVoltageSensor; public SampleMecanumDrive(HardwareMap hardwareMap) { super(kV, kA, kStatic, TRACK_WIDTH, TRACK_WIDTH, LATERAL_MULTIPLIER); follower = new HolonomicPIDVAFollower(TRANSLATIONAL_PID, TRANSLATIONAL_PID, HEADING_PID, new Pose2d(0.5, 0.5, Math.toRadians(5.0)), 0.5); LynxModuleUtil.ensureMinimumFirmwareVersion(hardwareMap); batteryVoltageSensor = hardwareMap.voltageSensor.iterator().next(); for (LynxModule module : hardwareMap.getAll(LynxModule.class)) { module.setBulkCachingMode(LynxModule.BulkCachingMode.AUTO); } // TODO: adjust the names of the following hardware devices to match your configuration imu = hardwareMap.get(BNO055IMU.class, "imu"); BNO055IMU.Parameters parameters = new BNO055IMU.Parameters(); parameters.angleUnit = BNO055IMU.AngleUnit.RADIANS; imu.initialize(parameters); // TODO: If the hub containing the IMU you are using is mounted so that the "REV" logo does // not face up, remap the IMU axes so that the z-axis points upward (normal to the floor.) // // | +Z axis // | // | // | // _______|_____________ +Y axis // / |_____________/|__________ // / REV / EXPANSION // // / / HUB // // /_______/_____________// // |_______/_____________|/ // / // / +X axis // // This diagram is derived from the axes in section 3.4 https://www.bosch-sensortec.com/media/boschsensortec/downloads/datasheets/bst-bno055-ds000.pdf // and the placement of the dot/orientation from https://docs.revrobotics.com/rev-control-system/control-system-overview/dimensions#imu-location // // For example, if +Y in this diagram faces downwards, you would use AxisDirection.NEG_Y. // BNO055IMUUtil.remapZAxis(imu, AxisDirection.NEG_Y); leftFront = hardwareMap.get(DcMotorEx.class, "leftFront"); rightRear = hardwareMap.get(DcMotorEx.class, "rightRear"); leftRear = hardwareMap.get(DcMotorEx.class, "leftRear"); rightFront = hardwareMap.get(DcMotorEx.class, "rightFront"); motors = Arrays.asList(leftFront, leftRear, rightRear, rightFront); for (DcMotorEx motor : motors) { MotorConfigurationType motorConfigurationType = motor.getMotorType().clone(); motorConfigurationType.setAchieveableMaxRPMFraction(1.0); motor.setMotorType(motorConfigurationType); } if (RUN_USING_ENCODER) { setMode(DcMotor.RunMode.RUN_USING_ENCODER); } setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); if (RUN_USING_ENCODER && MOTOR_VELO_PID != null) { setPIDFCoefficients(DcMotor.RunMode.RUN_USING_ENCODER, MOTOR_VELO_PID); } // TODO: reverse any motors using DcMotor.setDirection() leftFront.setDirection(DcMotorSimple.Direction.REVERSE); leftRear.setDirection(DcMotorSimple.Direction.REVERSE); // TODO: if desired, use setLocalizer() to change the localization method // for instance, setLocalizer(new ThreeTrackingWheelLocalizer(...)); // for instance, setLocalizer(new ThreeTrackingWheelLocalizer(...)); trajectorySequenceRunner = new TrajectorySequenceRunner(follower, HEADING_PID); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose) { return new TrajectoryBuilder(startPose, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, boolean reversed) { return new TrajectoryBuilder(startPose, reversed, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, double startHeading) { return new TrajectoryBuilder(startPose, startHeading, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectorySequenceBuilder trajectorySequenceBuilder(Pose2d startPose) { return new TrajectorySequenceBuilder( startPose, VEL_CONSTRAINT, ACCEL_CONSTRAINT, MAX_ANG_VEL, MAX_ANG_ACCEL ); } public void turnAsync(double angle) { trajectorySequenceRunner.followTrajectorySequenceAsync( trajectorySequenceBuilder(getPoseEstimate()) .turn(angle) .build() ); } public void turn(double angle) { turnAsync(angle); waitForIdle(); } public void followTrajectoryAsync(Trajectory trajectory) { trajectorySequenceRunner.followTrajectorySequenceAsync( trajectorySequenceBuilder(trajectory.start()) .addTrajectory(trajectory) .build() ); } public void followTrajectory(Trajectory trajectory) { followTrajectoryAsync(trajectory); waitForIdle(); } public void followTrajectorySequenceAsync(TrajectorySequence trajectorySequence) { trajectorySequenceRunner.followTrajectorySequenceAsync(trajectorySequence); } public void followTrajectorySequence(TrajectorySequence trajectorySequence) { followTrajectorySequenceAsync(trajectorySequence); waitForIdle(); } public Pose2d getLastError() { return trajectorySequenceRunner.getLastPoseError(); } public void update() { updatePoseEstimate(); DriveSignal signal = trajectorySequenceRunner.update(getPoseEstimate(), getPoseVelocity()); if (signal != null) setDriveSignal(signal); } public void waitForIdle() { while (!Thread.currentThread().isInterrupted() && isBusy()) update(); } public boolean isBusy() { return trajectorySequenceRunner.isBusy(); } public void setMode(DcMotor.RunMode runMode) { for (DcMotorEx motor : motors) { motor.setMode(runMode); } } public void setZeroPowerBehavior(DcMotor.ZeroPowerBehavior zeroPowerBehavior) { for (DcMotorEx motor : motors) { motor.setZeroPowerBehavior(zeroPowerBehavior); } } public void setPIDFCoefficients(DcMotor.RunMode runMode, PIDFCoefficients coefficients) { PIDFCoefficients compensatedCoefficients = new PIDFCoefficients( coefficients.p, coefficients.i, coefficients.d, coefficients.f * 12 / batteryVoltageSensor.getVoltage() ); for (DcMotorEx motor : motors) { motor.setPIDFCoefficients(runMode, compensatedCoefficients); } } public void setWeightedDrivePower(Pose2d drivePower) { Pose2d vel = drivePower; if (Math.abs(drivePower.getX()) + Math.abs(drivePower.getY()) + Math.abs(drivePower.getHeading()) > 1) { // re-normalize the powers according to the weights double denom = VX_WEIGHT * Math.abs(drivePower.getX()) + VY_WEIGHT * Math.abs(drivePower.getY()) + OMEGA_WEIGHT * Math.abs(drivePower.getHeading()); vel = new Pose2d( VX_WEIGHT * drivePower.getX(), VY_WEIGHT * drivePower.getY(), OMEGA_WEIGHT * drivePower.getHeading() ).div(denom); } setDrivePower(vel); } @NonNull @Override public List<Double> getWheelPositions() { List<Double> wheelPositions = new ArrayList<>(); for (DcMotorEx motor : motors) {
wheelPositions.add(encoderTicksToInches(motor.getCurrentPosition()));
11
2023-12-15 16:57:19+00:00
16k
Frig00/Progetto-Ing-Software
src/main/java/it/unipv/po/aioobe/trenissimo/controller/AccountSettingsController.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.StoricoAcquistiEntity; import it.unipv.po.aioobe.trenissimo.model.persistence.entity.ViaggiPreferitiEntity; import it.unipv.po.aioobe.trenissimo.model.persistence.service.StoricoAcquistiService; import it.unipv.po.aioobe.trenissimo.model.persistence.service.ViaggiPreferitiService; import it.unipv.po.aioobe.trenissimo.model.user.Account; import it.unipv.po.aioobe.trenissimo.view.HomePage; import it.unipv.po.aioobe.trenissimo.view.ModificaPassword; import it.unipv.po.aioobe.trenissimo.view.StoricoAcquistoControl; import it.unipv.po.aioobe.trenissimo.view.ViaggioPreferitoControl; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.concurrent.Task; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.layout.VBox; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.net.URL; import java.time.LocalDate; import java.util.ResourceBundle;
13,703
package it.unipv.po.aioobe.trenissimo.controller; /** * Controller class per accountSettings-view.fxml * * @author ArrayIndexOutOfBoundsException * @see it.unipv.po.aioobe.trenissimo.view.accountSettingsView * @see javafx.fxml.Initializable */ public class AccountSettingsController implements Initializable { @FXML private Button btnModifica; @FXML private Button btnAnnulla; @FXML private Button btnSalva; @FXML private Button btnModificaPassword; @FXML private Label lblBenvenuto; @FXML private Label lblPunti; @FXML private Label lblDatiPersonali; @FXML private TextField txtNome; @FXML private TextField txtCognome; @FXML private DatePicker dtpDataNascita; @FXML private TextField txtEmail; @FXML private TextField txtVia; @FXML private TextField txtCivico; @FXML private TextField txtCitta; @FXML private TextField txtCAP; @FXML private Label lblErroreCAP; @FXML private Label lblErroreEmail; @FXML private Label lblErroreDataNascita; @FXML private Label lblErroreNome; @FXML private Label lblErroreCognome; @FXML private Label lblErroreVia; @FXML private Label lblErroreCivico; @FXML private Label lblErroreCitta; @FXML private VBox layout; @FXML private VBox layoutStorico; @FXML private TabPane tabPane; private ObservableList<ViaggiPreferitiEntity> viaggiPreferiti; private ObservableList<StoricoAcquistiEntity> acquisti; /** * Metodo d'Inizializzazione * * @param url * @param resourceBundle * @see #onStart() * @see #updateListViaggiPreferiti() * @see #updateListStoricoAcquisti() * @see ViaggiPreferitiEntity * @see StoricoAcquistiEntity */ @Override public void initialize(URL url, ResourceBundle resourceBundle) { onStart(); viaggiPreferiti = FXCollections.observableArrayList(); viaggiPreferiti.addListener((ListChangeListener<ViaggiPreferitiEntity>) c -> updateListViaggiPreferiti()); acquisti = FXCollections.observableArrayList(); acquisti.addListener((ListChangeListener<StoricoAcquistiEntity>) c -> updateListStoricoAcquisti()); } /** * Prende dati dal database e riempie i text-fields della view * * @see ViaggioPreferitoControl * @see Account */ @FXML protected void onStart() { if (ViaggioPreferitoControl.fromViaggioControl) tabPane.getSelectionModel().select(1); else tabPane.getSelectionModel().select(0); lblBenvenuto.setText("Ciao, " + Account.getInstance().getDatiPersonali().getNome()); lblPunti.setText(Account.getInstance().getPuntiFedelta()); lblDatiPersonali.setText("Dati Personali"); txtNome.setText(Account.getInstance().getDatiPersonali().getNome()); txtCognome.setText(Account.getInstance().getDatiPersonali().getCognome()); dtpDataNascita.setValue(Account.getInstance().getDatiPersonali().getDataNascita().toLocalDate()); txtEmail.setText(Account.getInstance().getDatiPersonali().getMail()); txtVia.setText(Account.getInstance().getDatiPersonali().getVia()); txtCivico.setText(Account.getInstance().getDatiPersonali().getCivico()); txtCitta.setText(Account.getInstance().getDatiPersonali().getCitta()); txtCAP.setText(Account.getInstance().getDatiPersonali().getCap().toString()); } /** * Ritorna alla Home Page * * @see HomePage */ @FXML protected void onGoToHomepage() {
package it.unipv.po.aioobe.trenissimo.controller; /** * Controller class per accountSettings-view.fxml * * @author ArrayIndexOutOfBoundsException * @see it.unipv.po.aioobe.trenissimo.view.accountSettingsView * @see javafx.fxml.Initializable */ public class AccountSettingsController implements Initializable { @FXML private Button btnModifica; @FXML private Button btnAnnulla; @FXML private Button btnSalva; @FXML private Button btnModificaPassword; @FXML private Label lblBenvenuto; @FXML private Label lblPunti; @FXML private Label lblDatiPersonali; @FXML private TextField txtNome; @FXML private TextField txtCognome; @FXML private DatePicker dtpDataNascita; @FXML private TextField txtEmail; @FXML private TextField txtVia; @FXML private TextField txtCivico; @FXML private TextField txtCitta; @FXML private TextField txtCAP; @FXML private Label lblErroreCAP; @FXML private Label lblErroreEmail; @FXML private Label lblErroreDataNascita; @FXML private Label lblErroreNome; @FXML private Label lblErroreCognome; @FXML private Label lblErroreVia; @FXML private Label lblErroreCivico; @FXML private Label lblErroreCitta; @FXML private VBox layout; @FXML private VBox layoutStorico; @FXML private TabPane tabPane; private ObservableList<ViaggiPreferitiEntity> viaggiPreferiti; private ObservableList<StoricoAcquistiEntity> acquisti; /** * Metodo d'Inizializzazione * * @param url * @param resourceBundle * @see #onStart() * @see #updateListViaggiPreferiti() * @see #updateListStoricoAcquisti() * @see ViaggiPreferitiEntity * @see StoricoAcquistiEntity */ @Override public void initialize(URL url, ResourceBundle resourceBundle) { onStart(); viaggiPreferiti = FXCollections.observableArrayList(); viaggiPreferiti.addListener((ListChangeListener<ViaggiPreferitiEntity>) c -> updateListViaggiPreferiti()); acquisti = FXCollections.observableArrayList(); acquisti.addListener((ListChangeListener<StoricoAcquistiEntity>) c -> updateListStoricoAcquisti()); } /** * Prende dati dal database e riempie i text-fields della view * * @see ViaggioPreferitoControl * @see Account */ @FXML protected void onStart() { if (ViaggioPreferitoControl.fromViaggioControl) tabPane.getSelectionModel().select(1); else tabPane.getSelectionModel().select(0); lblBenvenuto.setText("Ciao, " + Account.getInstance().getDatiPersonali().getNome()); lblPunti.setText(Account.getInstance().getPuntiFedelta()); lblDatiPersonali.setText("Dati Personali"); txtNome.setText(Account.getInstance().getDatiPersonali().getNome()); txtCognome.setText(Account.getInstance().getDatiPersonali().getCognome()); dtpDataNascita.setValue(Account.getInstance().getDatiPersonali().getDataNascita().toLocalDate()); txtEmail.setText(Account.getInstance().getDatiPersonali().getMail()); txtVia.setText(Account.getInstance().getDatiPersonali().getVia()); txtCivico.setText(Account.getInstance().getDatiPersonali().getCivico()); txtCitta.setText(Account.getInstance().getDatiPersonali().getCitta()); txtCAP.setText(Account.getInstance().getDatiPersonali().getCap().toString()); } /** * Ritorna alla Home Page * * @see HomePage */ @FXML protected void onGoToHomepage() {
HomePage.openScene(lblBenvenuto.getScene().getWindow());
6
2023-12-21 10:41:11+00:00
16k
pan2013e/ppt4j
framework/src/main/java/ppt4j/analysis/patch/PatchAnalyzer.java
[ { "identifier": "DatabaseType", "path": "framework/src/main/java/ppt4j/database/DatabaseType.java", "snippet": "public enum DatabaseType {\n\n PREPATCH, POSTPATCH;\n\n @Property(\"ppt4j.database.prepatch.name\")\n private static String PREPATCH_DIR;\n\n @Property(\"ppt4j.database.postpatch.n...
import ppt4j.annotation.MethodProfiler; import ppt4j.annotation.Property; import ppt4j.database.DatabaseType; import ppt4j.database.Vulnerability; import ppt4j.diff.BlockDiff; import ppt4j.diff.DiffParser; import ppt4j.diff.FileDiff; import ppt4j.factory.DatabaseFactory; import ppt4j.factory.ExtractorFactory; import ppt4j.feature.FeatureMatcher; import ppt4j.feature.Features; import ppt4j.feature.java.JavaExtractor; import ppt4j.feature.java.JavaFeatures; import ppt4j.util.StringUtils; import lombok.extern.log4j.Log4j; import java.io.IOException; import java.util.*;
13,880
package ppt4j.analysis.patch; @Log4j public class PatchAnalyzer { @Property("ppt4j.analysis.patch.presence_threshold") private static double PATCH_PRESENCE_THRESHOLD; @Property("ppt4j.features.similarity.threshold") private static double SIM_THRESHOLD; @Property("ppt4j.features.similarity.algorithm") private static String SIM_ALGORITHM; private final DiffParser diffParser; private final ExtractorFactory factory; private final Vulnerability cve; private final List<String> filterMatch = new ArrayList<>(); private final List<String> filterNotMatch = new ArrayList<>(); private int total = 0, found = 0; private final Set<Integer> preUsedLines = new HashSet<>(); private final Set<Integer> postUsedLines = new HashSet<>(); public PatchAnalyzer(Vulnerability cve, ExtractorFactory factory) throws IOException { this.cve = cve; this.diffParser = new DiffParser(cve.getDiffUrl()); this.factory = factory; this.filterIfMatch(cve.getRequiredFilePatterns()) .filterIfNotMatch(cve.getIgnoredFilePatterns()); } public PatchAnalyzer(Vulnerability cve, DatabaseType type) throws IOException { this(cve, ExtractorFactory.get(cve, type)); log.info("Ground truth binary type in dataset: " + type); } @SuppressWarnings("UnusedReturnValue") public PatchAnalyzer filterIfMatch(String... patterns) { filterMatch.addAll(Arrays.asList(patterns)); return this; } @SuppressWarnings("UnusedReturnValue") public PatchAnalyzer filterIfNotMatch(String... patterns) { filterNotMatch.addAll(Arrays.asList(patterns)); return this; } @MethodProfiler public boolean analyze() throws IOException { log.info(String.format("Analyzing patch for %s, " + "CVE ID: %s, Database ID: %d", cve.getProjectName(), cve.getCVEId(), cve.getDatabaseId())); total = 0; found = 0; for(int i = 0;i < diffParser.getNumOfDiffs();i++) { String fileName = diffParser.getFileName(i, true); if(filterNotMatch.stream().anyMatch(fileName::matches)) { continue; } if(!filterMatch.stream().allMatch(fileName::matches)) { continue; } if(!fileName.startsWith(cve.getJavaSrcTopLevelDir())) { continue; } String className = StringUtils.extractClassName( fileName, cve.getJavaSrcTopLevelDir() ); FileDiff fileDiff = diffParser.getFileDiff(i); for (BlockDiff block : fileDiff.getBlocks()) { if(block.isPureDeletion()) { for (Integer line : block.getDeletionLines()) { analyzeDeletion(className, line); } } else if(block.isPureAddition()) { for (Integer line : block.getAdditionLines()) { analyzeAddition(className, line); } } else { List<Integer> additions = block.getAdditionLines(); filterAddition(className, additions); List<Integer> deletions = block.getDeletionLines(); filterDeletion(className, deletions); int windowSize = Math.min(additions.size(), deletions.size()); List<Integer> candidate, window; Features windowFeatures; char type; if (additions.size() < deletions.size()) { candidate = deletions; window = additions; type = '+'; } else { candidate = additions; window = deletions; type = '-'; } windowFeatures = mergeFeatures(className, window, type); List<Integer> bestOverlap = null; double bestScore = 0; for(int j = 0; j < candidate.size() - windowSize + 1; j++) { List<Integer> overlap = candidate.subList(j, j + windowSize); Features overlapFeatures = mergeFeatures(className, overlap, type == '+' ? '-' : '+');
package ppt4j.analysis.patch; @Log4j public class PatchAnalyzer { @Property("ppt4j.analysis.patch.presence_threshold") private static double PATCH_PRESENCE_THRESHOLD; @Property("ppt4j.features.similarity.threshold") private static double SIM_THRESHOLD; @Property("ppt4j.features.similarity.algorithm") private static String SIM_ALGORITHM; private final DiffParser diffParser; private final ExtractorFactory factory; private final Vulnerability cve; private final List<String> filterMatch = new ArrayList<>(); private final List<String> filterNotMatch = new ArrayList<>(); private int total = 0, found = 0; private final Set<Integer> preUsedLines = new HashSet<>(); private final Set<Integer> postUsedLines = new HashSet<>(); public PatchAnalyzer(Vulnerability cve, ExtractorFactory factory) throws IOException { this.cve = cve; this.diffParser = new DiffParser(cve.getDiffUrl()); this.factory = factory; this.filterIfMatch(cve.getRequiredFilePatterns()) .filterIfNotMatch(cve.getIgnoredFilePatterns()); } public PatchAnalyzer(Vulnerability cve, DatabaseType type) throws IOException { this(cve, ExtractorFactory.get(cve, type)); log.info("Ground truth binary type in dataset: " + type); } @SuppressWarnings("UnusedReturnValue") public PatchAnalyzer filterIfMatch(String... patterns) { filterMatch.addAll(Arrays.asList(patterns)); return this; } @SuppressWarnings("UnusedReturnValue") public PatchAnalyzer filterIfNotMatch(String... patterns) { filterNotMatch.addAll(Arrays.asList(patterns)); return this; } @MethodProfiler public boolean analyze() throws IOException { log.info(String.format("Analyzing patch for %s, " + "CVE ID: %s, Database ID: %d", cve.getProjectName(), cve.getCVEId(), cve.getDatabaseId())); total = 0; found = 0; for(int i = 0;i < diffParser.getNumOfDiffs();i++) { String fileName = diffParser.getFileName(i, true); if(filterNotMatch.stream().anyMatch(fileName::matches)) { continue; } if(!filterMatch.stream().allMatch(fileName::matches)) { continue; } if(!fileName.startsWith(cve.getJavaSrcTopLevelDir())) { continue; } String className = StringUtils.extractClassName( fileName, cve.getJavaSrcTopLevelDir() ); FileDiff fileDiff = diffParser.getFileDiff(i); for (BlockDiff block : fileDiff.getBlocks()) { if(block.isPureDeletion()) { for (Integer line : block.getDeletionLines()) { analyzeDeletion(className, line); } } else if(block.isPureAddition()) { for (Integer line : block.getAdditionLines()) { analyzeAddition(className, line); } } else { List<Integer> additions = block.getAdditionLines(); filterAddition(className, additions); List<Integer> deletions = block.getDeletionLines(); filterDeletion(className, deletions); int windowSize = Math.min(additions.size(), deletions.size()); List<Integer> candidate, window; Features windowFeatures; char type; if (additions.size() < deletions.size()) { candidate = deletions; window = additions; type = '+'; } else { candidate = additions; window = deletions; type = '-'; } windowFeatures = mergeFeatures(className, window, type); List<Integer> bestOverlap = null; double bestScore = 0; for(int j = 0; j < candidate.size() - windowSize + 1; j++) { List<Integer> overlap = candidate.subList(j, j + windowSize); Features overlapFeatures = mergeFeatures(className, overlap, type == '+' ? '-' : '+');
FeatureMatcher alg = FeatureMatcher.get(SIM_ALGORITHM);
7
2023-12-14 15:33:50+00:00
16k
f1den/MrCrayfishGunMod
src/main/java/com/mrcrayfish/guns/client/GunRenderType.java
[ { "identifier": "Reference", "path": "src/main/java/com/mrcrayfish/guns/Reference.java", "snippet": "public class Reference\n{\n\tpublic static final String MOD_ID = \"cgm\";\n}" }, { "identifier": "GunRenderingHandler", "path": "src/main/java/com/mrcrayfish/guns/client/handler/GunRenderingH...
import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.VertexFormat; import com.mrcrayfish.guns.Reference; import com.mrcrayfish.guns.client.handler.GunRenderingHandler; import com.mrcrayfish.guns.client.render.ScreenTextureState; import net.minecraft.client.renderer.RenderStateShard; import net.minecraft.client.renderer.RenderType;
11,834
package com.mrcrayfish.guns.client; /** * Author: MrCrayfish */ public final class GunRenderType extends RenderType {
package com.mrcrayfish.guns.client; /** * Author: MrCrayfish */ public final class GunRenderType extends RenderType {
private static final RenderType BULLET_TRAIL = RenderType.create(Reference.MOD_ID + ":projectile_trail", DefaultVertexFormat.POSITION_COLOR_LIGHTMAP, VertexFormat.Mode.QUADS, 256, true, true, RenderType.CompositeState.builder().setShaderState(RenderStateShard.POSITION_COLOR_LIGHTMAP_SHADER).setCullState(NO_CULL).setTransparencyState(TRANSLUCENT_TRANSPARENCY).createCompositeState(false));
0
2023-12-18 15:04:35+00:00
16k
thebatmanfuture/fofa_search
src/main/java/org/fofaviewer/controllers/MainController.java
[ { "identifier": "SaveOptionCallback", "path": "src/main/java/org/fofaviewer/callback/SaveOptionCallback.java", "snippet": "public interface SaveOptionCallback{\n default void setProjectName(String name){}\n default String getProjectName(){\n return null;\n }\n}" }, { "identifier"...
import java.io.BufferedReader; import java.io.File; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.Alert; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.stage.FileChooser; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import javax.net.ssl.HttpsURLConnection; import java.io.BufferedWriter; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.ResourceBundle; import java.util.Set; import javafx.scene.control.Alert; import javafx.scene.control.Tab; import javafx.scene.control.TableView; import javafx.scene.layout.BorderPane; import javafx.stage.DirectoryChooser; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.ProgressBar; import javafx.scene.control.Alert.AlertType; import javafx.scene.layout.Region; import javafx.stage.FileChooser; import javafx.stage.StageStyle; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.concurrent.Task; import javafx.fxml.FXML; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.*; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.*; import javafx.scene.layout.*; import javafx.scene.text.Font; import org.controlsfx.control.StatusBar; import org.controlsfx.dialog.CommandLinksDialog; import org.controlsfx.dialog.ProgressDialog; import org.fofaviewer.bean.*; import org.fofaviewer.callback.SaveOptionCallback; import org.fofaviewer.controls.*; import org.fofaviewer.main.FofaConfig; import org.fofaviewer.callback.MainControllerCallback; import org.fofaviewer.request.Request; import org.fofaviewer.callback.RequestCallback; import org.fofaviewer.utils.DataUtil; import org.fofaviewer.utils.RequestUtil; import org.controlsfx.control.textfield.TextFields; import org.fofaviewer.utils.ResourceBundleUtil; import java.awt.*; import java.io.*; import java.math.BigInteger; import java.net.URI; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; import java.util.stream.Collectors; import org.fofaviewer.utils.SQLiteUtils; import org.tinylog.Logger;
11,961
package org.fofaviewer.controllers; public class MainController { private Map<String, Object> projectInfo; private AutoHintTextField decoratedField; private static final RequestUtil helper = RequestUtil.getInstance(); private FofaConfig client; private final ResourceBundle resourceBundle; private final HashMap<CheckBox, String> keyMap = new HashMap<>(); @FXML private Menu help; @FXML private Menu project; @FXML private Menu urlFunction; @FXML private Menu urlCombination; @FXML private Menu awvs; @FXML private Menu urlslice; @FXML private MenuItem importFile; @FXML private MenuItem urlslicein; @FXML private Menu no_repeat; @FXML private MenuItem no_repeat_id; @FXML private MenuItem urlCsettings; @FXML private MenuItem awvsTran; // @FXML // private MenuItem startOn; @FXML private Menu rule; @FXML private Menu config; // @FXML // private MenuItem query_api; // @FXML // private MenuItem ; // @FXML // private MenuItem exportRule; @FXML private MenuItem about; @FXML private MenuItem setConfig; @FXML private MenuItem openProject; @FXML private MenuItem saveProject; @FXML private Button exportDataBtn; @FXML private Button exportAll; @FXML private Button searchBtn; @FXML private Label queryString; @FXML private VBox rootLayout; @FXML private TextField queryTF; // @FXML // private CheckBox checkHoneyPot; // @FXML // private CheckBox withFid; // @FXML // private CheckBox hostOnly; // 仅host @FXML private CheckBox isAll; // @FXML // private CheckBox title; // @FXML // private CheckBox cert; @FXML private CloseableTabPane tabPane; public MainController(){ this.resourceBundle = ResourceBundleUtil.getResource(); } /** * 初始化 */ @FXML private void initialize() { SQLiteUtils.init(); // keyMap.put(withFid, "fid"); // keyMap.put(hostOnly, "123host"); // keyMap.put(cert, "cert"); // keyMap.put(title, "title"); projectInfo = new HashMap<>(); projectInfo.put("status", Boolean.FALSE); projectInfo.put("name", ""); // title.setText(resourceBundle.getString("TITLE")); // cert.setText(resourceBundle.getString("CERT")); about.setText(resourceBundle.getString("ABOUT")); help.setText(resourceBundle.getString("HELP")); project.setText(resourceBundle.getString("PROJECT")); urlFunction.setText(resourceBundle.getString("URLFUNCTION")); no_repeat_id.setText(resourceBundle.getString("no_repeat_id")); // @FXML // private Menu urlFunction; // // @FXML // private Menu importTxt; importFile.setText(resourceBundle.getString("IMPORTFILE")); // startOn.setText(resourceBundle.getString("STARTFILE")); //urlCombination urlCombination.setText(resourceBundle.getString("URLCOMBINATION")); urlCsettings.setText(resourceBundle.getString("URLCSETTINGS")); awvsTran.setText(resourceBundle.getString("AWVSTRAN")); urlslicein.setText(resourceBundle.getString("urlslicein")); awvs.setText(resourceBundle.getString("AWVS")); urlslice.setText(resourceBundle.getString("urlslice")); no_repeat.setText(resourceBundle.getString("no_repeat")); config.setText(resourceBundle.getString("CONFIG_PANEL")); // rule.setText(resourceBundle.getString("RULE")); // query_api.setText(resourceBundle.getString("QUERY_API")); setConfig.setText(resourceBundle.getString("SET_CONFIG")); // createRule.setText(resourceBundle.getString("CREATE_RULE")); // .setText(resourceBundle.getString("EXPORT_RULE")); saveProject.setText(resourceBundle.getString("SAVE_PROJECT")); openProject.setText(resourceBundle.getString("OPEN_PROJECT")); searchBtn.setText(resourceBundle.getString("SEARCH")); exportAll.setText(resourceBundle.getString("EXPORT_ALL")); /* * * * * */ exportDataBtn.setText(resourceBundle.getString("EXPORT_BUTTON")); queryString.setText(resourceBundle.getString("QUERY_CONTENT")); // checkHoneyPot.setText(resourceBundle.getString("REMOVE_HONEYPOTS")); // withFid.setText(resourceBundle.getString("WITH_FID")); // hostOnly.setText(resourceBundle.getString("HOST_ONLY")); isAll.setText(resourceBundle.getString("IS_ALL")); decoratedField = new AutoHintTextField(queryTF); this.client = DataUtil.loadConfigure();
package org.fofaviewer.controllers; public class MainController { private Map<String, Object> projectInfo; private AutoHintTextField decoratedField; private static final RequestUtil helper = RequestUtil.getInstance(); private FofaConfig client; private final ResourceBundle resourceBundle; private final HashMap<CheckBox, String> keyMap = new HashMap<>(); @FXML private Menu help; @FXML private Menu project; @FXML private Menu urlFunction; @FXML private Menu urlCombination; @FXML private Menu awvs; @FXML private Menu urlslice; @FXML private MenuItem importFile; @FXML private MenuItem urlslicein; @FXML private Menu no_repeat; @FXML private MenuItem no_repeat_id; @FXML private MenuItem urlCsettings; @FXML private MenuItem awvsTran; // @FXML // private MenuItem startOn; @FXML private Menu rule; @FXML private Menu config; // @FXML // private MenuItem query_api; // @FXML // private MenuItem ; // @FXML // private MenuItem exportRule; @FXML private MenuItem about; @FXML private MenuItem setConfig; @FXML private MenuItem openProject; @FXML private MenuItem saveProject; @FXML private Button exportDataBtn; @FXML private Button exportAll; @FXML private Button searchBtn; @FXML private Label queryString; @FXML private VBox rootLayout; @FXML private TextField queryTF; // @FXML // private CheckBox checkHoneyPot; // @FXML // private CheckBox withFid; // @FXML // private CheckBox hostOnly; // 仅host @FXML private CheckBox isAll; // @FXML // private CheckBox title; // @FXML // private CheckBox cert; @FXML private CloseableTabPane tabPane; public MainController(){ this.resourceBundle = ResourceBundleUtil.getResource(); } /** * 初始化 */ @FXML private void initialize() { SQLiteUtils.init(); // keyMap.put(withFid, "fid"); // keyMap.put(hostOnly, "123host"); // keyMap.put(cert, "cert"); // keyMap.put(title, "title"); projectInfo = new HashMap<>(); projectInfo.put("status", Boolean.FALSE); projectInfo.put("name", ""); // title.setText(resourceBundle.getString("TITLE")); // cert.setText(resourceBundle.getString("CERT")); about.setText(resourceBundle.getString("ABOUT")); help.setText(resourceBundle.getString("HELP")); project.setText(resourceBundle.getString("PROJECT")); urlFunction.setText(resourceBundle.getString("URLFUNCTION")); no_repeat_id.setText(resourceBundle.getString("no_repeat_id")); // @FXML // private Menu urlFunction; // // @FXML // private Menu importTxt; importFile.setText(resourceBundle.getString("IMPORTFILE")); // startOn.setText(resourceBundle.getString("STARTFILE")); //urlCombination urlCombination.setText(resourceBundle.getString("URLCOMBINATION")); urlCsettings.setText(resourceBundle.getString("URLCSETTINGS")); awvsTran.setText(resourceBundle.getString("AWVSTRAN")); urlslicein.setText(resourceBundle.getString("urlslicein")); awvs.setText(resourceBundle.getString("AWVS")); urlslice.setText(resourceBundle.getString("urlslice")); no_repeat.setText(resourceBundle.getString("no_repeat")); config.setText(resourceBundle.getString("CONFIG_PANEL")); // rule.setText(resourceBundle.getString("RULE")); // query_api.setText(resourceBundle.getString("QUERY_API")); setConfig.setText(resourceBundle.getString("SET_CONFIG")); // createRule.setText(resourceBundle.getString("CREATE_RULE")); // .setText(resourceBundle.getString("EXPORT_RULE")); saveProject.setText(resourceBundle.getString("SAVE_PROJECT")); openProject.setText(resourceBundle.getString("OPEN_PROJECT")); searchBtn.setText(resourceBundle.getString("SEARCH")); exportAll.setText(resourceBundle.getString("EXPORT_ALL")); /* * * * * */ exportDataBtn.setText(resourceBundle.getString("EXPORT_BUTTON")); queryString.setText(resourceBundle.getString("QUERY_CONTENT")); // checkHoneyPot.setText(resourceBundle.getString("REMOVE_HONEYPOTS")); // withFid.setText(resourceBundle.getString("WITH_FID")); // hostOnly.setText(resourceBundle.getString("HOST_ONLY")); isAll.setText(resourceBundle.getString("IS_ALL")); decoratedField = new AutoHintTextField(queryTF); this.client = DataUtil.loadConfigure();
this.tabPane.setCallback(new MainControllerCallback() {
2
2023-10-25 11:13:47+00:00
16k
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;
11,104
//获取验证码 File code = null; while ((code = com.cbq.yatori.core.action.canghui.LoginAction.getCode(user)) == null) ; accountCacheCangHui.setCode(VerificationCodeUtil.aiDiscern(code)); FileUtils.deleteFile(code);//删除验证码文件 //进行登录操作 while ((result = com.cbq.yatori.core.action.canghui.LoginAction.toLogin(user)) == null) ; } while (result.getCode()==-1002); //对结果进行判定 if (result.getCode()==0) { accountCacheCangHui.setToken(result.getData().getToken()); accountCacheCangHui.setStatus(1); log.info("{}登录成功!", user.getAccount()); } else { log.info("{}登录失败,服务器信息>>>{}", user.getAccount(), result.getMsg()); return; } //为账号维持登录状态----------------------------------- new Thread(() -> { while (true) { Map online; //避免超时 while ((online = com.cbq.yatori.core.action.canghui.LoginAction.online(user)) == null) { try { Thread.sleep(1000 * 5); } catch (InterruptedException e) { throw new RuntimeException(e); } } //如果含有登录超时字样 if (((String) online.get("msg")).contains("成功")) { accountCacheCangHui.setStatus(1); } else if (((String) online.get("msg")).contains("登录超时")) { accountCacheCangHui.setStatus(2);//设定登录状态为超时 log.info("{}登录超时,正在重新登录...", user.getAccount()); //进行登录 LoginResponseRequest map=null; do { //获取验证码 File code = com.cbq.yatori.core.action.canghui.LoginAction.getCode(user); ((AccountCacheYingHua) user.getCache()).setCode(VerificationCodeUtil.aiDiscern(code)); FileUtils.deleteFile(code);//删除验证码文件 //进行登录操作 while ((map=com.cbq.yatori.core.action.canghui.LoginAction.toLogin(user))==null); } while (map.getCode()==-1002); //对结果进行判定 if (map.getCode()==0) { accountCacheCangHui.setStatus(1); log.info("{}登录成功!", user.getAccount()); } else { log.info("{}登录失败,服务器信息>>>{}", user.getAccount(), map.getMsg()); } } try { Thread.sleep(1000 * 60); } catch (InterruptedException e) { throw new RuntimeException(e); } } }).start(); } //学习公社 case ENAEA -> { AccountCacheEnaea accountCacheEnaea = new AccountCacheEnaea(); user.setCache(accountCacheEnaea); //sS:101代表账号或密码错误, LoginAblesky loginAblesky = null; while((loginAblesky=com.cbq.yatori.core.action.enaea.LoginAction.toLogin(user))==null); //对结果进行判定 if (loginAblesky.getSS().equals("0")) { accountCacheEnaea.setStatus(1); log.info("{}登录成功!", user.getAccount()); } else { log.info("{}登录失败,服务器信息>>>{}", user.getAccount(), loginAblesky.getAlertMessage()); return; } } } } //刷课 for (User user : users) { switch (user.getAccountType()) { case YINGHUA -> { new Thread(()->{ //获取全部课程 CourseRequest allCourseList = null; while((allCourseList= CourseAction.getAllCourseRequest(user))==null); for (CourseInform courseInform : allCourseList.getResult().getList()) { //课程排除配置 if(user.getCoursesCostom()!=null) { if (user.getCoursesCostom().getExcludeCourses() != null) { if (user.getCoursesCostom().getExcludeCourses().size() != 0) if (user.getCoursesCostom().getExcludeCourses().contains(courseInform.getName())) continue; } //如果有指定课程包含设定,那么就执行 if (user.getCoursesCostom().getIncludeCourses() != null) { if (user.getCoursesCostom().getIncludeCourses().size() != 0) if (!user.getCoursesCostom().getIncludeCourses().contains(courseInform.getName())) continue; } } CourseStudyAction bulild = CourseStudyAction.builder() .user(user) .courseInform(courseInform) .newThread(true) .build(); bulild.toStudy(); } }).start(); } case CANGHUI -> { new Thread(()->{ //获取全部课程 // CourseRequest allCourseList = 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)); FileUtils.deleteFile(code);//删除验证码文件 //进行登录操作 while ((result = LoginAction.toLogin(user)) == null) ; } while (!(Boolean) result.get("status") && ((String) result.get("msg")).contains("验证码有误")); //对结果进行判定 if ((Boolean) result.get("status")) { accountCacheYingHua.setStatus(1); log.info("{}登录成功!", user.getAccount()); } else { log.info("{}登录失败,服务器信息>>>{}", user.getAccount(), ((String) result.get("msg"))); return; } //为账号维持登录状态----------------------------------- new Thread(() -> { while (true) { Map online; //避免超时 while ((online = LoginAction.online(user)) == null) { try { Thread.sleep(1000 * 5); } catch (InterruptedException e) { throw new RuntimeException(e); } } //如果含有登录超时字样 if (((String) online.get("msg")).contains("更新成功")) { accountCacheYingHua.setStatus(1); } else if (((String) online.get("msg")).contains("登录超时")) { accountCacheYingHua.setStatus(2);//设定登录状态为超时 log.info("{}登录超时,正在重新登录...", user.getAccount()); //进行登录 Map<String, Object> map; do { //获取验证码 File code = LoginAction.getCode(user); ((AccountCacheYingHua) user.getCache()).setCode(VerificationCodeUtil.aiDiscern(code)); FileUtils.deleteFile(code);//删除验证码文件 //进行登录操作 map = LoginAction.toLogin(user); } while (!(Boolean) map.get("status") && ((String) map.get("msg")).contains("验证码有误")); //对结果进行判定 if ((Boolean) map.get("status")) { accountCacheYingHua.setStatus(1); log.info("{}登录成功!", user.getAccount()); } else { log.info("{}登录失败,服务器信息>>>{}", user.getAccount(), ((String) map.get("msg"))); } } try { Thread.sleep(1000 * 60); } catch (InterruptedException e) { throw new RuntimeException(e); } } }).start(); } //仓辉 case CANGHUI -> { AccountCacheCangHui accountCacheCangHui = new AccountCacheCangHui(); user.setCache(accountCacheCangHui); //refresh_code:1代表密码错误, LoginResponseRequest result=null; do { //获取SESSION String session = null; while ((session = com.cbq.yatori.core.action.canghui.LoginAction.getSESSION(user)) == null) ; accountCacheCangHui.setSession(session); //获取验证码 File code = null; while ((code = com.cbq.yatori.core.action.canghui.LoginAction.getCode(user)) == null) ; accountCacheCangHui.setCode(VerificationCodeUtil.aiDiscern(code)); FileUtils.deleteFile(code);//删除验证码文件 //进行登录操作 while ((result = com.cbq.yatori.core.action.canghui.LoginAction.toLogin(user)) == null) ; } while (result.getCode()==-1002); //对结果进行判定 if (result.getCode()==0) { accountCacheCangHui.setToken(result.getData().getToken()); accountCacheCangHui.setStatus(1); log.info("{}登录成功!", user.getAccount()); } else { log.info("{}登录失败,服务器信息>>>{}", user.getAccount(), result.getMsg()); return; } //为账号维持登录状态----------------------------------- new Thread(() -> { while (true) { Map online; //避免超时 while ((online = com.cbq.yatori.core.action.canghui.LoginAction.online(user)) == null) { try { Thread.sleep(1000 * 5); } catch (InterruptedException e) { throw new RuntimeException(e); } } //如果含有登录超时字样 if (((String) online.get("msg")).contains("成功")) { accountCacheCangHui.setStatus(1); } else if (((String) online.get("msg")).contains("登录超时")) { accountCacheCangHui.setStatus(2);//设定登录状态为超时 log.info("{}登录超时,正在重新登录...", user.getAccount()); //进行登录 LoginResponseRequest map=null; do { //获取验证码 File code = com.cbq.yatori.core.action.canghui.LoginAction.getCode(user); ((AccountCacheYingHua) user.getCache()).setCode(VerificationCodeUtil.aiDiscern(code)); FileUtils.deleteFile(code);//删除验证码文件 //进行登录操作 while ((map=com.cbq.yatori.core.action.canghui.LoginAction.toLogin(user))==null); } while (map.getCode()==-1002); //对结果进行判定 if (map.getCode()==0) { accountCacheCangHui.setStatus(1); log.info("{}登录成功!", user.getAccount()); } else { log.info("{}登录失败,服务器信息>>>{}", user.getAccount(), map.getMsg()); } } try { Thread.sleep(1000 * 60); } catch (InterruptedException e) { throw new RuntimeException(e); } } }).start(); } //学习公社 case ENAEA -> { AccountCacheEnaea accountCacheEnaea = new AccountCacheEnaea(); user.setCache(accountCacheEnaea); //sS:101代表账号或密码错误, LoginAblesky loginAblesky = null; while((loginAblesky=com.cbq.yatori.core.action.enaea.LoginAction.toLogin(user))==null); //对结果进行判定 if (loginAblesky.getSS().equals("0")) { accountCacheEnaea.setStatus(1); log.info("{}登录成功!", user.getAccount()); } else { log.info("{}登录失败,服务器信息>>>{}", user.getAccount(), loginAblesky.getAlertMessage()); return; } } } } //刷课 for (User user : users) { switch (user.getAccountType()) { case YINGHUA -> { new Thread(()->{ //获取全部课程 CourseRequest allCourseList = null; while((allCourseList= CourseAction.getAllCourseRequest(user))==null); for (CourseInform courseInform : allCourseList.getResult().getList()) { //课程排除配置 if(user.getCoursesCostom()!=null) { if (user.getCoursesCostom().getExcludeCourses() != null) { if (user.getCoursesCostom().getExcludeCourses().size() != 0) if (user.getCoursesCostom().getExcludeCourses().contains(courseInform.getName())) continue; } //如果有指定课程包含设定,那么就执行 if (user.getCoursesCostom().getIncludeCourses() != null) { if (user.getCoursesCostom().getIncludeCourses().size() != 0) if (!user.getCoursesCostom().getIncludeCourses().contains(courseInform.getName())) continue; } } CourseStudyAction bulild = CourseStudyAction.builder() .user(user) .courseInform(courseInform) .newThread(true) .build(); bulild.toStudy(); } }).start(); } case CANGHUI -> { new Thread(()->{ //获取全部课程 // CourseRequest allCourseList = null;
MyCourseData myCourseData = null;
2
2023-10-30 04:15:41+00:00
16k
sgware/sabre
src/edu/uky/cs/nil/sabre/comp/CompiledTrigger.java
[ { "identifier": "Settings", "path": "src/edu/uky/cs/nil/sabre/Settings.java", "snippet": "public class Settings {\n\n\t/** The full name of this software library */\n\tpublic static final String TITLE = \"The Sabre Narrative Planner\";\n\t\n\t/** The list of primary authors */\n\tpublic static final Str...
import edu.uky.cs.nil.sabre.Settings; import edu.uky.cs.nil.sabre.Signature; import edu.uky.cs.nil.sabre.Trigger; import edu.uky.cs.nil.sabre.logic.Clause; import edu.uky.cs.nil.sabre.logic.Disjunction; import edu.uky.cs.nil.sabre.logic.Effect; import edu.uky.cs.nil.sabre.logic.Precondition;
11,314
package edu.uky.cs.nil.sabre.comp; /** * A compiled trigger is a {@link edu.uky.cs.nil.sabre.logic.Logical#isGround() * ground} {@link Trigger trigger} which defines a {@link * edu.uky.cs.nil.sabre.util.Unique unique} {@link #id ID number} that * corresponds to the trigger's index in its {@link CompiledProblem#events * compiled problem's set of events}, whose {@link #precondition precondition} * is in {@link edu.uky.cs.nil.sabre.logic.Expression#toPrecondition() * disjunctive normal form}, and whose {@link #effect effect} is {@link * edu.uky.cs.nil.sabre.logic.Expression#toEffect() a clause}. * * @author Stephen G. Ware */ public class CompiledTrigger extends Trigger implements CompiledEvent { /** Serial version ID */ private static final long serialVersionUID = Settings.VERSION_UID; /** * A unique ID number that corresponds to this trigger's index in {@link * CompiledProblem#events its compiled problem's set of events} */ public final int id; /** * The trigger's {@link edu.uky.cs.nil.sabre.Event#getPrecondition() * precondition} in {@link * edu.uky.cs.nil.sabre.logic.Expression#toPrecondition() in disjunctive * normal form} */
package edu.uky.cs.nil.sabre.comp; /** * A compiled trigger is a {@link edu.uky.cs.nil.sabre.logic.Logical#isGround() * ground} {@link Trigger trigger} which defines a {@link * edu.uky.cs.nil.sabre.util.Unique unique} {@link #id ID number} that * corresponds to the trigger's index in its {@link CompiledProblem#events * compiled problem's set of events}, whose {@link #precondition precondition} * is in {@link edu.uky.cs.nil.sabre.logic.Expression#toPrecondition() * disjunctive normal form}, and whose {@link #effect effect} is {@link * edu.uky.cs.nil.sabre.logic.Expression#toEffect() a clause}. * * @author Stephen G. Ware */ public class CompiledTrigger extends Trigger implements CompiledEvent { /** Serial version ID */ private static final long serialVersionUID = Settings.VERSION_UID; /** * A unique ID number that corresponds to this trigger's index in {@link * CompiledProblem#events its compiled problem's set of events} */ public final int id; /** * The trigger's {@link edu.uky.cs.nil.sabre.Event#getPrecondition() * precondition} in {@link * edu.uky.cs.nil.sabre.logic.Expression#toPrecondition() in disjunctive * normal form} */
public final Disjunction<Clause<Precondition>> precondition;
4
2023-10-26 18:14:19+00:00
16k
granny/Pl3xMap
core/src/main/java/net/pl3x/map/core/renderer/VanillaRenderer.java
[ { "identifier": "Pl3xMap", "path": "core/src/main/java/net/pl3x/map/core/Pl3xMap.java", "snippet": "public abstract class Pl3xMap {\n public static @NotNull Pl3xMap api() {\n return Provider.api();\n }\n\n private final boolean isBukkit;\n\n private final Attributes manifestAttributes...
import net.pl3x.map.core.world.Region; import org.jetbrains.annotations.NotNull; import net.pl3x.map.core.Pl3xMap; import net.pl3x.map.core.renderer.heightmap.Heightmap; import net.pl3x.map.core.renderer.task.RegionScanTask; import net.pl3x.map.core.util.Colors; import net.pl3x.map.core.world.BlockState; import net.pl3x.map.core.world.Chunk; import net.pl3x.map.core.world.EmptyChunk;
11,832
/* * 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.renderer; public class VanillaRenderer extends Renderer { private final Heightmap heightmap; public VanillaRenderer(@NotNull RegionScanTask task, @NotNull Builder builder) { super(task, builder);
/* * 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.renderer; public class VanillaRenderer extends Renderer { private final Heightmap heightmap; public VanillaRenderer(@NotNull RegionScanTask task, @NotNull Builder builder) { super(task, builder);
this.heightmap = Pl3xMap.api().getHeightmapRegistry().get("old_school");
0
2023-10-26 01:14:31+00:00
16k
d0ge/sessionless
src/main/java/one/d4d/sessionless/presenter/EditorPresenter.java
[ { "identifier": "SignerConfig", "path": "src/main/java/burp/config/SignerConfig.java", "snippet": "public class SignerConfig {\n @Expose\n private boolean enableDangerous;\n @Expose\n private boolean enableExpress;\n @Expose\n private boolean enableOAuth;\n @Expose\n private bool...
import burp.api.montoya.collaborator.CollaboratorPayloadGenerator; import burp.api.montoya.http.message.Cookie; import burp.api.montoya.http.message.params.ParsedHttpParameter; import burp.config.SignerConfig; import one.d4d.sessionless.forms.EditorTab; import one.d4d.sessionless.forms.MessageDialogFactory; import one.d4d.sessionless.forms.dialog.*; import one.d4d.sessionless.itsdangerous.Attack; import one.d4d.sessionless.itsdangerous.model.*; import one.d4d.sessionless.keys.Key; import one.d4d.sessionless.keys.SecretKey; import one.d4d.sessionless.utils.ErrorLoggingActionListenerFactory; import one.d4d.sessionless.utils.Utils; import java.net.URL; import java.util.Base64; import java.util.List; import static one.d4d.sessionless.itsdangerous.model.SignedTokenObjectFinder.containsSignedTokenObjects;
11,368
public void copyExpressSignature() { Utils.copyToClipboard(view.getExpressSignature()); } public void onSignClicked() { signingDialog(); } public void onAttackClicked() { attackDialog(); } private void attackDialog() { KeyPresenter keysPresenter = (KeyPresenter) presenters.get(KeyPresenter.class); MutableSignedToken mutableJoseObject = model.getSignedTokenObject(view.getSelectedSignedTokenObjectIndex()); SignedToken tokenObject = mutableJoseObject.getModified(); if (keysPresenter.getSigningKeys().size() == 0) { messageDialogFactory.showWarningDialog("error_title_no_signing_keys", "error_no_signing_keys"); return; } AttackDialog signDialog = new AttackDialog( view.window(), actionListenerFactory, keysPresenter.getSigningKeys(), targetURL, tokenObject ); signDialog.display(); SignedToken signed = signDialog.getToken(); if (signed != null) { if (signed instanceof DangerousSignedToken) { view.setDangerousMode(); setDangerous((DangerousSignedToken) signed); } else if (signed instanceof ExpressSignedToken) { view.setExpressMode(); setExpress((ExpressSignedToken) signed); } else if (signed instanceof OauthProxySignedToken) { view.setOAuthMode(); setOAuth((OauthProxySignedToken) signed); } else if (signed instanceof TornadoSignedToken) { view.setTornadoMode(); setTornado((TornadoSignedToken) signed); } else if (signed instanceof UnknownSignedToken) { view.setUnknownMode(); setUnknown((UnknownSignedToken) signed); } } } private void signingDialog() { KeyPresenter keysPresenter = (KeyPresenter) presenters.get(KeyPresenter.class); MutableSignedToken mutableJoseObject = model.getSignedTokenObject(view.getSelectedSignedTokenObjectIndex()); SignedToken tokenObject = mutableJoseObject.getModified(); if (keysPresenter.getSigningKeys().size() == 0) { messageDialogFactory.showWarningDialog("error_title_no_signing_keys", "error_no_signing_keys"); return; } SignDialog signDialog = new SignDialog( view.window(), actionListenerFactory, keysPresenter.getSigningKeys(), tokenObject ); signDialog.display(); SignedToken signed = signDialog.getToken(); if (signed != null) { if (signed instanceof DangerousSignedToken) { view.setDangerousMode(); setDangerous((DangerousSignedToken) signed); } else if (signed instanceof ExpressSignedToken) { view.setExpressMode(); setExpress((ExpressSignedToken) signed); } else if (signed instanceof OauthProxySignedToken) { view.setOAuthMode(); setOAuth((OauthProxySignedToken) signed); } else if (signed instanceof TornadoSignedToken) { view.setTornadoMode(); setTornado((TornadoSignedToken) signed); } else if (signed instanceof UnknownSignedToken) { view.setUnknownMode(); setUnknown((UnknownSignedToken) signed); } } } public void onAttackClicked(Attack mode) { KeyPresenter keysPresenter = (KeyPresenter) presenters.get(KeyPresenter.class); MutableSignedToken mutableJoseObject = model.getSignedTokenObject(view.getSelectedSignedTokenObjectIndex()); SignedToken tokenObject = mutableJoseObject.getModified(); List<String> attackKeys = keysPresenter.getSecrets(); List<String> attackSalts = keysPresenter.getSalts(); if (attackKeys.size() == 0) { messageDialogFactory.showWarningDialog("error_title_no_secrets", "error_no_secrets"); return; } if (attackSalts.size() == 0) { messageDialogFactory.showWarningDialog("error_title_no_salts", "error_no_salts"); return; } BruteForceAttackDialog bruteForceDialog = new BruteForceAttackDialog( view.window(), actionListenerFactory, attackKeys, attackSalts, keysPresenter.getSigningKeys(), mode, tokenObject); bruteForceDialog.display();
package one.d4d.sessionless.presenter; public class EditorPresenter extends Presenter { private final PresenterStore presenters; private final SignerConfig signerConfig; private final EditorModel model; private final EditorTab view; private final CollaboratorPayloadGenerator collaboratorPayloadGenerator; private final ErrorLoggingActionListenerFactory actionListenerFactory; private final MessageDialogFactory messageDialogFactory; private boolean selectionChanging; private URL targetURL; public EditorPresenter( EditorTab view, CollaboratorPayloadGenerator collaboratorPayloadGenerator, ErrorLoggingActionListenerFactory actionListenerFactory, PresenterStore presenters, SignerConfig signerConfig) { this.view = view; this.model = new EditorModel(signerConfig); this.collaboratorPayloadGenerator = collaboratorPayloadGenerator; this.actionListenerFactory = actionListenerFactory; this.presenters = presenters; messageDialogFactory = new MessageDialogFactory(view.uiComponent()); presenters.register(this); this.signerConfig = signerConfig; } public void setMessage(String content, URL targetURL, List<Cookie> cookies, List<ParsedHttpParameter> params) { this.targetURL = targetURL; model.setMessage(content, cookies, params); view.setSignedTokenObjects(model.getSerializedObjectStrings()); } private DangerousSignedToken getDangerous() { String payload; if (view.getDangerouseIsJSON()) { String json = Utils.compactJSON(view.getDangerousPayload()); if (view.getDangerouseIsCompressed()) { payload = Utils.compressBase64(json.getBytes()); } else { payload = Base64.getUrlEncoder().withoutPadding().encodeToString(json.getBytes()); } } else { payload = view.getDangerousPayload(); } String timestamp; String signature = Base64.getUrlEncoder().withoutPadding().encodeToString(view.getDangerousSignature()); byte[] separator = view.getDangerousSeparator().length == 0 ? new byte[]{46} : view.getDangerousSeparator(); if (view.getDangerouseIsDjangoFormatting()) { timestamp = Utils.encodeBase62TimestampFromDate(view.getDangerousTimestamp()); return new DjangoSignedToken( separator[0], payload, timestamp, signature); } else { timestamp = Utils.encodeBase64TimestampFromDate(view.getDangerousTimestamp()); return new DangerousSignedToken( separator[0], payload, timestamp, signature); } } private void setDangerous(DangerousSignedToken token) { view.setDangerouseIsCompressed(token.isCompressed()); try { String payload = new String(Utils.base64Decompress(token.getPayload().getBytes())); if (Utils.isValidJSON(payload)) { view.setDangerouseIsJSON(true); view.setDangerousPayload(Utils.prettyPrintJSON(payload)); } else { view.setDangerouseIsJSON(false); view.setDangerousPayload(token.getPayload()); } } catch (Exception e) { view.setDangerouseIsJSON(false); view.setDangerousPayload(token.getPayload()); } if (token instanceof DjangoSignedToken) { view.setDangerouseIsDjangoFormatting(true); view.setDangerousTimestamp(token.getTimestamp()); } else { view.setDangerouseIsDjangoFormatting(false); view.setDangerousTimestamp(token.getTimestamp()); } view.setDangerousSignature(token.getSignature()); view.setDangerousSeparator(token.getSeparator()); } private OauthProxySignedToken getOAuth() { String parameter = view.getOAuthParameter(); String payload = view.getOAuthPayload(); String timestamp = Utils.timestampFromDateInSeconds(view.getOAuthTimestamp()); String signature = Base64.getUrlEncoder().withoutPadding().encodeToString(view.getOAuthSignature()); return new OauthProxySignedToken( parameter, payload, timestamp, signature); } private void setOAuth(OauthProxySignedToken token) { view.setOAuthParameter(token.getParameter()); view.setOAuthPayload(token.getPayload()); view.setOAuthTimestamp(token.getTimestamp()); view.setOAuthSignature(token.getSignature()); } private ExpressSignedToken getExpress() { String parameter = view.getExpressParameter(); String payload = Base64.getUrlEncoder().encodeToString(view.getExpressPayload().getBytes()); String signature = view.getExpressSignature(); return new ExpressSignedToken(parameter, payload, signature); } private void setExpress(ExpressSignedToken token) { view.setExpressPayload(token.getPayload()); view.setExpressParameter(token.getParameter()); view.setExpressSignature(new String(token.getSignature())); } private TornadoSignedToken getTornado() { String name = view.getTornadoName(); String value = Base64.getUrlEncoder().encodeToString(view.getTornadoValue().getBytes()); String timestamp = Utils.timestampFromDateInSeconds(view.getTornadoTimestamp()); String signature = new String(view.getTornadoSignature()); return new TornadoSignedToken(timestamp, name, value, signature); } private void setTornado(TornadoSignedToken token) { view.setTornadoTimestamp(token.getTimestamp()); view.setTornadoName(token.getName()); view.setTornadoValue(token.getValue()); view.setTornadoSignature(token.getSignature()); } private UnknownSignedToken getUnknown() { String message = view.getUnknownMessage(); String signature = view.getUnknownSignature(); byte[] separator = view.getUnknownSeparator().length == 0 ? new byte[]{46} : view.getUnknownSeparator(); return new UnknownSignedToken(message,signature,separator[0]); } private void setUnknown(UnknownSignedToken token) { view.setUnknownMessage(token.getEncodedMessage()); view.setUnknownSignature(token.getEncodedSignature()); view.setUnknownSeparator(token.getSeparator()); } public void componentChanged() { MutableSignedToken mutableSignedTokenObject = model.getSignedTokenObject(view.getSelectedSignedTokenObjectIndex()); SignedToken tokenObject; switch (view.getMode()) { case EditorTab.TAB_DANGEROUSE -> tokenObject = getDangerous(); case EditorTab.TAB_EXPRESS -> tokenObject = getExpress(); case EditorTab.TAB_OAUTH -> tokenObject = getOAuth(); case EditorTab.TAB_TORNADO -> tokenObject = getTornado(); default -> tokenObject = getUnknown(); } mutableSignedTokenObject.setModified(tokenObject); view.setSignedToken(tokenObject.serialize(), mutableSignedTokenObject.changed() && !selectionChanging); } public void onSelectionChanged() { selectionChanging = true; MutableSignedToken mutableJoseObject = model.getSignedTokenObject(view.getSelectedSignedTokenObjectIndex()); SignedToken tokenObject = mutableJoseObject.getModified(); if (tokenObject instanceof DangerousSignedToken) { view.setDangerousMode(); setDangerous((DangerousSignedToken) tokenObject); } else if (tokenObject instanceof ExpressSignedToken) { view.setExpressMode(); setExpress((ExpressSignedToken) tokenObject); } else if (tokenObject instanceof OauthProxySignedToken) { view.setOAuthMode(); setOAuth((OauthProxySignedToken) tokenObject); } else if (tokenObject instanceof TornadoSignedToken) { view.setTornadoMode(); setTornado((TornadoSignedToken) tokenObject); } else if (tokenObject instanceof UnknownSignedToken) { view.setUnknownMode(); setUnknown((UnknownSignedToken) tokenObject); } selectionChanging = false; } public void copyExpressSignature() { Utils.copyToClipboard(view.getExpressSignature()); } public void onSignClicked() { signingDialog(); } public void onAttackClicked() { attackDialog(); } private void attackDialog() { KeyPresenter keysPresenter = (KeyPresenter) presenters.get(KeyPresenter.class); MutableSignedToken mutableJoseObject = model.getSignedTokenObject(view.getSelectedSignedTokenObjectIndex()); SignedToken tokenObject = mutableJoseObject.getModified(); if (keysPresenter.getSigningKeys().size() == 0) { messageDialogFactory.showWarningDialog("error_title_no_signing_keys", "error_no_signing_keys"); return; } AttackDialog signDialog = new AttackDialog( view.window(), actionListenerFactory, keysPresenter.getSigningKeys(), targetURL, tokenObject ); signDialog.display(); SignedToken signed = signDialog.getToken(); if (signed != null) { if (signed instanceof DangerousSignedToken) { view.setDangerousMode(); setDangerous((DangerousSignedToken) signed); } else if (signed instanceof ExpressSignedToken) { view.setExpressMode(); setExpress((ExpressSignedToken) signed); } else if (signed instanceof OauthProxySignedToken) { view.setOAuthMode(); setOAuth((OauthProxySignedToken) signed); } else if (signed instanceof TornadoSignedToken) { view.setTornadoMode(); setTornado((TornadoSignedToken) signed); } else if (signed instanceof UnknownSignedToken) { view.setUnknownMode(); setUnknown((UnknownSignedToken) signed); } } } private void signingDialog() { KeyPresenter keysPresenter = (KeyPresenter) presenters.get(KeyPresenter.class); MutableSignedToken mutableJoseObject = model.getSignedTokenObject(view.getSelectedSignedTokenObjectIndex()); SignedToken tokenObject = mutableJoseObject.getModified(); if (keysPresenter.getSigningKeys().size() == 0) { messageDialogFactory.showWarningDialog("error_title_no_signing_keys", "error_no_signing_keys"); return; } SignDialog signDialog = new SignDialog( view.window(), actionListenerFactory, keysPresenter.getSigningKeys(), tokenObject ); signDialog.display(); SignedToken signed = signDialog.getToken(); if (signed != null) { if (signed instanceof DangerousSignedToken) { view.setDangerousMode(); setDangerous((DangerousSignedToken) signed); } else if (signed instanceof ExpressSignedToken) { view.setExpressMode(); setExpress((ExpressSignedToken) signed); } else if (signed instanceof OauthProxySignedToken) { view.setOAuthMode(); setOAuth((OauthProxySignedToken) signed); } else if (signed instanceof TornadoSignedToken) { view.setTornadoMode(); setTornado((TornadoSignedToken) signed); } else if (signed instanceof UnknownSignedToken) { view.setUnknownMode(); setUnknown((UnknownSignedToken) signed); } } } public void onAttackClicked(Attack mode) { KeyPresenter keysPresenter = (KeyPresenter) presenters.get(KeyPresenter.class); MutableSignedToken mutableJoseObject = model.getSignedTokenObject(view.getSelectedSignedTokenObjectIndex()); SignedToken tokenObject = mutableJoseObject.getModified(); List<String> attackKeys = keysPresenter.getSecrets(); List<String> attackSalts = keysPresenter.getSalts(); if (attackKeys.size() == 0) { messageDialogFactory.showWarningDialog("error_title_no_secrets", "error_no_secrets"); return; } if (attackSalts.size() == 0) { messageDialogFactory.showWarningDialog("error_title_no_salts", "error_no_salts"); return; } BruteForceAttackDialog bruteForceDialog = new BruteForceAttackDialog( view.window(), actionListenerFactory, attackKeys, attackSalts, keysPresenter.getSigningKeys(), mode, tokenObject); bruteForceDialog.display();
SecretKey k = bruteForceDialog.getSecretKey();
5
2023-10-30 09:12:06+00:00
16k
LEAWIND/Third-Person
common/src/main/java/net/leawind/mc/thirdperson/event/ThirdPersonEvents.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 com.mojang.blaze3d.Blaze3D; import com.mojang.blaze3d.platform.Window; import dev.architectury.event.EventResult; import dev.architectury.event.events.client.ClientPlayerEvent; import dev.architectury.event.events.client.ClientRawInputEvent; import dev.architectury.event.events.client.ClientTickEvent; 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.api.cameraoffset.CameraOffsetScheme; import net.leawind.mc.thirdperson.core.CameraAgent; import net.leawind.mc.thirdperson.core.ModReferee; import net.leawind.mc.thirdperson.core.PlayerAgent; import net.leawind.mc.thirdperson.impl.config.Config; import net.leawind.mc.util.api.math.vector.Vector2d; import net.leawind.mc.util.math.LMath; import net.minecraft.client.CameraType; import net.minecraft.client.Minecraft; import net.minecraft.client.player.LocalPlayer; import net.minecraft.util.Mth; import net.minecraft.world.level.BlockGetter;
11,377
package net.leawind.mc.thirdperson.event; public interface ThirdPersonEvents { static void register () { ClientTickEvent.CLIENT_PRE.register(ThirdPersonEvents::onClientTickPre); ClientPlayerEvent.CLIENT_PLAYER_RESPAWN.register(ThirdPersonEvents::onClientPlayerRespawn); ClientPlayerEvent.CLIENT_PLAYER_JOIN.register(ThirdPersonEvents::onClientPlayerJoin); ClientRawInputEvent.MOUSE_SCROLLED.register(ThirdPersonEvents::onMouseScrolled); } private static void onClientTickPre (Minecraft mc) { if (mc.isPaused()) { return; } Config config = ThirdPerson.getConfig();
package net.leawind.mc.thirdperson.event; public interface ThirdPersonEvents { static void register () { ClientTickEvent.CLIENT_PRE.register(ThirdPersonEvents::onClientTickPre); ClientPlayerEvent.CLIENT_PLAYER_RESPAWN.register(ThirdPersonEvents::onClientPlayerRespawn); ClientPlayerEvent.CLIENT_PLAYER_JOIN.register(ThirdPersonEvents::onClientPlayerJoin); ClientRawInputEvent.MOUSE_SCROLLED.register(ThirdPersonEvents::onMouseScrolled); } private static void onClientTickPre (Minecraft mc) { if (mc.isPaused()) { return; } Config config = ThirdPerson.getConfig();
CameraAgent.updateSmoothEyePosition(0.05);
4
2023-10-31 05:52:36+00:00
16k
siam1026/siam-cloud
siam-user/user-provider/src/main/java/com/siam/package_user/service_impl/MemberBillingRecordServiceImpl.java
[ { "identifier": "StoneCustomerException", "path": "siam-common/src/main/java/com/siam/package_common/exception/StoneCustomerException.java", "snippet": "public class StoneCustomerException extends RuntimeException{\n // 结果码\n private Integer code = BasicResultCode.ERR;\n\n // 结果码描述\n private...
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.siam.package_common.exception.StoneCustomerException; import com.siam.package_user.auth.cache.MemberSessionManager; import com.siam.package_user.entity.Member; import com.siam.package_user.entity.MemberBillingRecord; import com.siam.package_user.mapper.MemberBillingRecordMapper; import com.siam.package_user.model.dto.MemberBillingRecordDto; import com.siam.package_user.model.example.MemberBillingRecordExample; import com.siam.package_user.model.param.MemberBillingRecordParam; import com.siam.package_user.service.MemberBillingRecordService; import com.siam.package_user.service.MemberService; import com.siam.package_user.util.TokenUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.util.Date; import java.util.List; import java.util.Map;
14,353
package com.siam.package_user.service_impl; @Service public class MemberBillingRecordServiceImpl implements MemberBillingRecordService { @Autowired private MemberBillingRecordMapper memberBillingRecordMapper; @Autowired private MemberService memberService; @Autowired private MemberSessionManager memberSessionManager; @Override public void deleteByPrimaryKey(Integer id) { memberBillingRecordMapper.deleteByPrimaryKey(id); } @Override public void insertSelective(MemberBillingRecord memberBillingRecord) { memberBillingRecordMapper.insertSelective(memberBillingRecord); } @Override public MemberBillingRecord selectByPrimaryKey(MemberBillingRecordParam param) { Member loginMember = memberSessionManager.getSession(TokenUtil.getToken()); MemberBillingRecord memberBillingRecord = memberBillingRecordMapper.selectByPrimaryKey(param.getId()); if(!memberBillingRecord.getMemberId().equals(loginMember.getId())){
package com.siam.package_user.service_impl; @Service public class MemberBillingRecordServiceImpl implements MemberBillingRecordService { @Autowired private MemberBillingRecordMapper memberBillingRecordMapper; @Autowired private MemberService memberService; @Autowired private MemberSessionManager memberSessionManager; @Override public void deleteByPrimaryKey(Integer id) { memberBillingRecordMapper.deleteByPrimaryKey(id); } @Override public void insertSelective(MemberBillingRecord memberBillingRecord) { memberBillingRecordMapper.insertSelective(memberBillingRecord); } @Override public MemberBillingRecord selectByPrimaryKey(MemberBillingRecordParam param) { Member loginMember = memberSessionManager.getSession(TokenUtil.getToken()); MemberBillingRecord memberBillingRecord = memberBillingRecordMapper.selectByPrimaryKey(param.getId()); if(!memberBillingRecord.getMemberId().equals(loginMember.getId())){
throw new StoneCustomerException("500, 该账单不是你的,不允许查看");
0
2023-10-26 10:45:10+00:00
16k
elizagamedev/android-libre-japanese-input
app/src/main/java/sh/eliza/japaneseinput/CandidateWordView.java
[ { "identifier": "BackgroundDrawableFactory", "path": "app/src/main/java/sh/eliza/japaneseinput/keyboard/BackgroundDrawableFactory.java", "snippet": "public class BackgroundDrawableFactory {\n /** Drawable to create. */\n public enum DrawableType {\n // Key background for twelvekeys layout.\n TWE...
import android.content.Context; import android.graphics.Canvas; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.MotionEvent; import android.view.View; import android.view.accessibility.AccessibilityManager; import android.widget.EdgeEffect; import androidx.core.view.ViewCompat; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import javax.annotation.Nullable; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCandidates.CandidateList; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCandidates.CandidateWord; import sh.eliza.japaneseinput.accessibility.CandidateWindowAccessibilityDelegate; import sh.eliza.japaneseinput.keyboard.BackgroundDrawableFactory; import sh.eliza.japaneseinput.keyboard.BackgroundDrawableFactory.DrawableType; import sh.eliza.japaneseinput.ui.CandidateLayout; import sh.eliza.japaneseinput.ui.CandidateLayout.Row; import sh.eliza.japaneseinput.ui.CandidateLayout.Span; import sh.eliza.japaneseinput.ui.CandidateLayoutRenderer; import sh.eliza.japaneseinput.ui.CandidateLayouter; import sh.eliza.japaneseinput.ui.SnapScroller; import sh.eliza.japaneseinput.view.Skin;
13,743
// 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; /** A view for candidate words. */ // TODO(matsuzakit): Optional is introduced partially. Complete introduction. abstract class CandidateWordView extends View implements MemoryManageable { /** Handles gestures to scroll candidate list and choose a candidate. */ class CandidateWordGestureDetector { class CandidateWordViewGestureListener extends SimpleOnGestureListener { @Override public boolean onFling( MotionEvent event1, MotionEvent event2, float velocityX, float velocityY) { float velocity = orientationTrait.projectVector(velocityX, velocityY); // As fling is started, current action is not tapping. // Reset pressing state so that candidate selection is not triggered at touch up event. reset(); // Fling makes scrolling. scroller.fling(-(int) velocity); invalidate(); return true; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { float distance = orientationTrait.projectVector(distanceX, distanceY); int oldScrollPosition = scroller.getScrollPosition(); int oldMaxScrollPosition = scroller.getMaxScrollPosition(); scroller.scrollBy((int) distance); orientationTrait.scrollTo(CandidateWordView.this, scroller.getScrollPosition()); // As scroll is started, current action is not tapping. // Reset pressing state so that candidate selection is not triggered at touch up event. reset(); // Edge effect. Now, in production, we only support vertical scroll. if (oldScrollPosition + distance < 0) { topEdgeEffect.onPull(distance / getHeight()); if (!bottomEdgeEffect.isFinished()) { bottomEdgeEffect.onRelease(); } } else if (oldScrollPosition + distance > oldMaxScrollPosition) { bottomEdgeEffect.onPull(distance / getHeight()); if (!topEdgeEffect.isFinished()) { topEdgeEffect.onRelease(); } } invalidate(); return true; } } // GestureDetector cannot handle all complex gestures which we need. // But we use GestureDetector for some gesture recognition // because implementing whole gesture detection logic by ourselves is a bit tedious. private final GestureDetector gestureDetector; /** * Points to an instance of currently pressed candidate word. Or {@code null} if any candidates * aren't pressed. */ @Nullable private CandidateWord pressedCandidate; private final RectF candidateRect = new RectF(); private Optional<Integer> pressedRowIndex = Optional.absent(); public CandidateWordGestureDetector(Context context) { gestureDetector = new GestureDetector(context, new CandidateWordViewGestureListener()); }
// 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; /** A view for candidate words. */ // TODO(matsuzakit): Optional is introduced partially. Complete introduction. abstract class CandidateWordView extends View implements MemoryManageable { /** Handles gestures to scroll candidate list and choose a candidate. */ class CandidateWordGestureDetector { class CandidateWordViewGestureListener extends SimpleOnGestureListener { @Override public boolean onFling( MotionEvent event1, MotionEvent event2, float velocityX, float velocityY) { float velocity = orientationTrait.projectVector(velocityX, velocityY); // As fling is started, current action is not tapping. // Reset pressing state so that candidate selection is not triggered at touch up event. reset(); // Fling makes scrolling. scroller.fling(-(int) velocity); invalidate(); return true; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { float distance = orientationTrait.projectVector(distanceX, distanceY); int oldScrollPosition = scroller.getScrollPosition(); int oldMaxScrollPosition = scroller.getMaxScrollPosition(); scroller.scrollBy((int) distance); orientationTrait.scrollTo(CandidateWordView.this, scroller.getScrollPosition()); // As scroll is started, current action is not tapping. // Reset pressing state so that candidate selection is not triggered at touch up event. reset(); // Edge effect. Now, in production, we only support vertical scroll. if (oldScrollPosition + distance < 0) { topEdgeEffect.onPull(distance / getHeight()); if (!bottomEdgeEffect.isFinished()) { bottomEdgeEffect.onRelease(); } } else if (oldScrollPosition + distance > oldMaxScrollPosition) { bottomEdgeEffect.onPull(distance / getHeight()); if (!topEdgeEffect.isFinished()) { topEdgeEffect.onRelease(); } } invalidate(); return true; } } // GestureDetector cannot handle all complex gestures which we need. // But we use GestureDetector for some gesture recognition // because implementing whole gesture detection logic by ourselves is a bit tedious. private final GestureDetector gestureDetector; /** * Points to an instance of currently pressed candidate word. Or {@code null} if any candidates * aren't pressed. */ @Nullable private CandidateWord pressedCandidate; private final RectF candidateRect = new RectF(); private Optional<Integer> pressedRowIndex = Optional.absent(); public CandidateWordGestureDetector(Context context) { gestureDetector = new GestureDetector(context, new CandidateWordViewGestureListener()); }
private void pressCandidate(int rowIndex, Span span) {
4
2023-10-25 07:33:25+00:00
16k
oghenevovwerho/yaa
src/main/java/yaa/semantic/passes/fs4/F4NEnum.java
[ { "identifier": "NewEnum", "path": "src/main/java/yaa/ast/NewEnum.java", "snippet": "public class NewEnum extends Stmt {\r\n public Map<String, YaaToken> options = new HashMap<>(1);\r\n public List<NewClass> classes;\r\n public List<NewEnum> enums;\r\n public List<RunBlock> runBlocks = new ArrayList...
import yaa.ast.NewEnum; import yaa.semantic.handlers.VDefOp; import yaa.pojos.YaaClz; import yaa.pojos.GlobalData; import static yaa.pojos.GlobalData.fs4; import static yaa.semantic.passes.fs4.F4NClass.checkObjectMtds;
12,552
package yaa.semantic.passes.fs4; public class F4NEnum { public static void newEnum(NewEnum newEnum) { fs4.pushTable(newEnum); var currentClz = (YaaClz) fs4.getSymbol(newEnum.placeOfUse());
package yaa.semantic.passes.fs4; public class F4NEnum { public static void newEnum(NewEnum newEnum) { fs4.pushTable(newEnum); var currentClz = (YaaClz) fs4.getSymbol(newEnum.placeOfUse());
GlobalData.topClz.push(currentClz);
3
2023-10-26 17:41:13+00:00
16k
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,976
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); private static <B extends Block> GameObject<B> blockWithItem(String name, Supplier<B> create) { return blockWithItem(name, create, b -> new BlockItem(b, new Item.Properties())); } private static <B extends Block, I extends Item> GameObject<B> blockWithItem(String name, Supplier<B> create, Function<Block, I> createItem) { GameObject<B> re = Platform.BLOCKS.register(name, create); item(name, () -> createItem.apply(re.get())); return re; } private static <I extends Item> GameObject<I> item(String name, Supplier<I> fact) { return Platform.ITEMS.register(name, () -> Platform.addItemToTab(fact.get())); } @SuppressWarnings("unchecked") @SafeVarargs
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); private static <B extends Block> GameObject<B> blockWithItem(String name, Supplier<B> create) { return blockWithItem(name, create, b -> new BlockItem(b, new Item.Properties())); } private static <B extends Block, I extends Item> GameObject<B> blockWithItem(String name, Supplier<B> create, Function<Block, I> createItem) { GameObject<B> re = Platform.BLOCKS.register(name, create); item(name, () -> createItem.apply(re.get())); return re; } private static <I extends Item> GameObject<I> item(String name, Supplier<I> fact) { return Platform.ITEMS.register(name, () -> Platform.addItemToTab(fact.get())); } @SuppressWarnings("unchecked") @SafeVarargs
private static <BE extends BlockEntity> GameObjectBlockEntity<BE> blockEntity(String name, BlockEntityFactory<? extends BE> create, GameObject<? extends Block>... blocks) {
10
2023-10-30 17:05:11+00:00
16k
quentin452/DangerRPG-Continuation
src/main/java/mixac1/dangerrpg/init/RPGConfig.java
[ { "identifier": "DangerRPG", "path": "src/main/java/mixac1/dangerrpg/DangerRPG.java", "snippet": "@Mod(\n modid = DangerRPG.MODID,\n name = DangerRPG.MODNAME,\n version = DangerRPG.VERSION,\n acceptedMinecraftVersions = DangerRPG.ACCEPTED_VERSION,\n dependencies = \"required-after:Forge\"...
import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.relauncher.FMLInjectionData; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import mixac1.dangerrpg.DangerRPG; import mixac1.dangerrpg.api.entity.EntityAttribute; import mixac1.dangerrpg.api.entity.LvlEAProvider; import mixac1.dangerrpg.api.item.GemType; import mixac1.dangerrpg.api.item.ItemAttribute; import mixac1.dangerrpg.capability.data.RPGEntityRegister.EntityAttrParams; import mixac1.dangerrpg.capability.data.RPGEntityRegister.RPGEntityData; import mixac1.dangerrpg.capability.data.RPGItemRegister.ItemAttrParams; import mixac1.dangerrpg.capability.data.RPGItemRegister.RPGItemData; import mixac1.dangerrpg.client.gui.GuiMode; import mixac1.dangerrpg.util.IMultiplier.MulType; import mixac1.dangerrpg.util.IMultiplier.Multiplier; import mixac1.dangerrpg.util.RPGHelper; import mixac1.dangerrpg.util.Tuple.Stub; import mixac1.dangerrpg.util.Utils; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.monster.EntityZombie; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraftforge.common.config.ConfigCategory; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; import java.io.File; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry;
13,367
@Override public void load() { d.isAllItemsRPGable = config.getBoolean( "isAllItemsRPGable", category.getName(), d.isAllItemsRPGable, "All weapons, tools , armors are RPGable (dangerous) (true/false)"); d.canUpInTable = config.getBoolean( "canUpInTable", category.getName(), d.canUpInTable, "Items can be upgrade in LevelUp Table without creative mode (true/false) \nLevelUp Table is invisible now"); d.maxLevel = config .getInt("maxLevel", category.getName(), d.maxLevel, 1, Integer.MAX_VALUE, "Set max level of RPG items"); d.startMaxExp = config.getInt( "startMaxExp", category.getName(), d.startMaxExp, 0, Integer.MAX_VALUE, "Set start needed expirience for RPG items"); d.expMul = config.getFloat( "expMul", category.getName(), d.expMul, 0f, Float.MAX_VALUE, "Set expirience multiplier for RPG items"); d.gemStartLvl = config.getInt( "gemStartLvl", category.getName(), d.gemStartLvl, 1, Integer.MAX_VALUE, "Set default start gem's level"); d.gemLvlUpStep = config.getInt( "gemLvlUpStep", category.getName(), d.gemLvlUpStep, 1, Integer.MAX_VALUE, "Set default level up gem's step"); save(); } @Override public void postLoadPre() { ArrayList<String> names = RPGHelper.getItemNames(RPGCapability.rpgItemRegistr.keySet(), true, false); Property prop = getPropertyStrings( "activeRPGItems", names.toArray(new String[names.size()]), "Set active RPG items (activated if 'isAllItemsRPGable' is false) (true/false)", false); if (!d.isAllItemsRPGable) { activeRPGItems = new HashSet<String>(Arrays.asList(prop.getStringList())); } save(); } @Override public void postLoadPost() { HashMap<Item, RPGItemData> map = (HashMap<Item, RPGItemData>) RPGCapability.rpgItemRegistr .getActiveElements(); customConfig(map); ArrayList<String> names = RPGHelper.getItemNames(map.keySet(), true, false); getPropertyStrings( "activeRPGItems", names.toArray(new String[names.size()]), "Set active RPG items (activated if 'isAllItemsRPGable' is false) (true/false)", true); names = RPGHelper.getItemNames(RPGCapability.rpgItemRegistr.keySet(), true, true); getPropertyStrings( "itemList", names.toArray(new String[names.size()]), "List of all items, which can be RPGable", true); save(); } protected void customConfig(HashMap<Item, RPGItemData> map) { String str = "customSetting"; Property prop = getPropertyStrings( "needCustomSetting", new String[] { Items.diamond_sword.delegate.name() }, "Set items, which needs customization", true); HashSet<String> needCustomSetting = new HashSet<String>(Arrays.asList(prop.getStringList())); if (!needCustomSetting.isEmpty()) { for (Entry<Item, RPGItemData> item : map.entrySet()) { if (needCustomSetting.contains(item.getKey().delegate.name())) { ConfigCategory cat = config .getCategory(Utils.toString(str, ".", item.getKey().delegate.name())); if (!item.getValue().isSupported) { cat.setComment("Warning: it isn't support from mod"); } for (Entry<ItemAttribute, ItemAttrParams> ia : item.getValue().attributes.entrySet()) { if (ia.getKey() .isConfigurable()) { ia.getValue().value = getIAValue(cat.getQualifiedName(), ia); if (ia.getValue().mul != null) { ia.getValue().mul = getIAMultiplier(cat.getQualifiedName(), ia); } } }
package mixac1.dangerrpg.init; public class RPGConfig { public static File dir; static { dir = new File((File) FMLInjectionData.data()[6], "config/".concat(DangerRPG.MODID)); if (dir.exists()) { if (!dir.isDirectory()) { dir.delete(); } } else { dir.mkdir(); } } @SideOnly(Side.CLIENT) public static ClientConfig clientConfig; public static MainConfig mainConfig = new MainConfig("MainConfig"); public static ItemConfig itemConfig = new ItemConfig("ItemConfig"); public static EntityConfig entityConfig = new EntityConfig("EntityConfig"); public static void load(FMLPreInitializationEvent e) { mainConfig.load(); itemConfig.load(); entityConfig.load(); if (MainConfig.d.mainEnableTransferConfig) { mainConfig.createTransferData(); itemConfig.createTransferData(); entityConfig.createTransferData(); } } @SideOnly(Side.CLIENT) public static void loadClient(FMLPreInitializationEvent e) { clientConfig = new ClientConfig("ClientConfig"); clientConfig.load(); } public static void postLoadPre(FMLPostInitializationEvent e) { mainConfig.postLoadPre(); itemConfig.postLoadPre(); entityConfig.postLoadPre(); } public static void postLoadPost(FMLPostInitializationEvent e) { mainConfig.postLoadPost(); itemConfig.postLoadPost(); entityConfig.postLoadPost(); } public static class MainConfig extends RPGConfigCommon { public static class Data implements Serializable { public boolean mainEnableInfoLog = true; public boolean mainEnableTransferConfig = false; public boolean mainEnableGemEventsToChat = true; } public static Data d = new Data(); public MainConfig(String fileName) { super(fileName); } @Override protected void init() { category.setComment( "GENERAL INFO:\n" + "\n" + "How do config multipliers ('.mul')\n" + "You can use three types of multiplier:\n" + "ADD 'value' - 'input parameter' + 'value'\n" + "MUL 'value' - 'input parameter' * 'value'\n" + "SQRT 'value' - 'input parameter' + sqrt('input parameter' * 'value')\n" + "HARD - not for using. There is a hard expression, but you can change it using other multipliers\n" + "\n"); save(); } @Override public void load() { d.mainEnableInfoLog = config.getBoolean( "mainEnableInfoLog", category.getName(), d.mainEnableInfoLog, "Enable printing info message to log (true/false)"); d.mainEnableTransferConfig = config.getBoolean( "mainEnableTransferConfig", category.getName(), d.mainEnableTransferConfig, "Enable transfer config data from server to client (true/false)\nCan be errors. Synchronize the configuration better by other means."); d.mainEnableGemEventsToChat = config.getBoolean( "mainEnableGemEventsToChat", category.getName(), d.mainEnableGemEventsToChat, "Enable printing gem's events to chat"); save(); } @Override public void createTransferData() { transferData = Utils.serialize(d); } @Override public void extractTransferData(byte[] transferData) { d = Utils.deserialize(transferData); } } @SideOnly(Side.CLIENT) public static class ClientConfig extends RPGConfigCommon { public static class Data implements Serializable { public boolean guiEnableHUD = true; public boolean guiEnableDefaultFoodBar = false; public int guiPlayerHUDOffsetX = 10; public int guiPlayerHUDOffsetY = 10; public boolean guiPlayerHUDIsInvert = false; public int guiEnemyHUDOffsetX = 10; public int guiEnemyHUDOffsetY = 10; public boolean guiEnemyHUDIsInvert = true; public int guiChargeOffsetX = 0; public int guiChargeOffsetY = 45; public boolean guiChargeIsCentered = true; public boolean guiTwiceHealthManaBar = false; public int guiDafaultHUDMode = 1; public int guiDamageForTestArmor = 25; public boolean neiShowShapedRecipe = false; private static final String[] acceptedColors = new String[]{"RED", "GREEN", "BLUE", "YELLOW", "ORANGE", "WHITE", "BLACK", "PURPLE"}; public static Configuration config; public static boolean showDamageParticles = true; public static boolean showAlways = false; public static Integer damageColor; public static Integer healColor; public static double size2 = 3.0; } public static Data d = new Data(); public ClientConfig(String fileName) { super(fileName); } @Override public void load() { d.guiEnableHUD = config .getBoolean("guiIsEnableHUD", category.getName(), d.guiEnableHUD, "Enable RPG HUD (true/false)"); d.guiEnableDefaultFoodBar = config.getBoolean( "guiEnableDefaultFoodBar", category.getName(), d.guiEnableDefaultFoodBar, "Enable default food bar (true/false)"); d.guiPlayerHUDOffsetX = config.getInt( "guiPlayerHUDOffsetX", category.getName(), d.guiPlayerHUDOffsetX, 0, Integer.MAX_VALUE, "Change X offset of player's HUD"); d.guiPlayerHUDOffsetY = config.getInt( "guiPlayerHUDOffsetY", category.getName(), d.guiPlayerHUDOffsetY, 0, Integer.MAX_VALUE, "Change Y offset of player's HUD"); d.guiPlayerHUDIsInvert = config.getBoolean( "guiPlayerHUDIsInvert", category.getName(), d.guiPlayerHUDIsInvert, "Change side of player's HUD (true/false)"); d.guiEnemyHUDOffsetX = config.getInt( "guiEnemyHUDOffsetX", category.getName(), d.guiEnemyHUDOffsetX, 0, Integer.MAX_VALUE, "Change X offset of enemy's HUD"); d.guiEnemyHUDOffsetY = config.getInt( "guiEnemyHUDOffsetY", category.getName(), d.guiEnemyHUDOffsetY, 0, Integer.MAX_VALUE, "Change Y offset of enemy's HUD"); d.guiEnemyHUDIsInvert = config.getBoolean( "guiEnemyHUDIsInvert", category.getName(), d.guiEnemyHUDIsInvert, "Change side of enemy's HUD (true/false)"); d.guiChargeOffsetX = config.getInt( "guiChargeOffsetX", category.getName(), d.guiChargeOffsetX, 0, Integer.MAX_VALUE, "Change X offset of charge bar"); d.guiChargeOffsetY = config.getInt( "guiChargeOffsetY", category.getName(), d.guiChargeOffsetY, 0, Integer.MAX_VALUE, "Change Y offset of charge bar"); d.guiChargeIsCentered = config.getBoolean( "guiChargeIsCentered", category.getName(), d.guiChargeIsCentered, "Charge bar need centering (true/false)"); d.guiTwiceHealthManaBar = config.getBoolean( "guiTwiceHealthManaBar", category.getName(), d.guiTwiceHealthManaBar, "Twice health-mana bar (true/false)"); d.guiDamageForTestArmor = config.getInt( "guiDamageForTestArmor", category.getName(), d.guiDamageForTestArmor, 0, Integer.MAX_VALUE, "Default damage value for calculate resistance in armor bar."); d.guiDafaultHUDMode = config.getInt( "guiDafaultHUDMode", category.getName(), d.guiDafaultHUDMode, 0, 3, "Set default HUD mode:\n[0] - normal\n[1] - normal digital\n[2] - simple\n[3] - simple digital\n"); GuiMode.set(d.guiDafaultHUDMode); d.neiShowShapedRecipe = config.getBoolean( "neiShowShapedRecipe", category.getName(), d.neiShowShapedRecipe, "Is show default recipes in RPG workbench (need NEI) (true/false)"); d.showDamageParticles = config.getBoolean("Show Damage Particles", Configuration.CATEGORY_GENERAL, true, "Show Damage Indicators"); d.showAlways = config.getBoolean("Show Always Particles", Configuration.CATEGORY_GENERAL, false, "Show Always The Damage Particles"); d.size2 = config.get(Configuration.CATEGORY_GENERAL, "Particles Size", d.size2, "Particles Size [default: 3.0]").getDouble(); d.healColor = mapColor(config.getString("Heal Color", Configuration.CATEGORY_GENERAL, "GREEN", "Heal Text Color", d.acceptedColors)); d.damageColor = mapColor(config.getString("Damage Color", Configuration.CATEGORY_GENERAL, "RED", "Damage Text Color", d.acceptedColors)); save(); } @Override public void createTransferData() { transferData = Utils.serialize(d); } @Override public void extractTransferData(byte[] transferData) { d = Utils.deserialize(transferData); } private static int mapColor(String color) { switch (color) { case "RED": return 0xff0000; case "GREEN": return 0x00ff00; case "BLUE": return 0x0000ff; case "YELLOW": return 0xffff00; case "ORANGE": return 0xffa500; case "BLACK": return 0x000000; case "PURPLE": return 0x960096; default: return 0xffffff; } } } public static class ItemConfig extends RPGConfigCommon { public static class Data implements Serializable { public boolean isAllItemsRPGable = true; public boolean canUpInTable = true; public int maxLevel = 15; public int startMaxExp = 100; public float expMul = 1.20f; public int gemStartLvl = 5; public int gemLvlUpStep = 5; } public static Data d = new Data(); public static HashSet<String> activeRPGItems = new HashSet<String>(); public ItemConfig(String fileName) { super(fileName); } @Override protected void init() { category.setComment( "FAQ:\n" + "Q: How do activate RPG item?\n" + "A: Take name of item frome the 'itemList' and put it to the 'activeRPGItems' list.\n" + "Or you can enable flag 'isAllItemsRPGable' for active all items.\n" + "\n" + "Q: How do congigure any item?\n" + "A: Take name of item frome the 'itemList' and put it to the 'needCustomSetting' list.\n" + "After this, run the game, exit from game and reopen this config.\n" + "You be able find generated element for configure that item."); save(); } @Override public void load() { d.isAllItemsRPGable = config.getBoolean( "isAllItemsRPGable", category.getName(), d.isAllItemsRPGable, "All weapons, tools , armors are RPGable (dangerous) (true/false)"); d.canUpInTable = config.getBoolean( "canUpInTable", category.getName(), d.canUpInTable, "Items can be upgrade in LevelUp Table without creative mode (true/false) \nLevelUp Table is invisible now"); d.maxLevel = config .getInt("maxLevel", category.getName(), d.maxLevel, 1, Integer.MAX_VALUE, "Set max level of RPG items"); d.startMaxExp = config.getInt( "startMaxExp", category.getName(), d.startMaxExp, 0, Integer.MAX_VALUE, "Set start needed expirience for RPG items"); d.expMul = config.getFloat( "expMul", category.getName(), d.expMul, 0f, Float.MAX_VALUE, "Set expirience multiplier for RPG items"); d.gemStartLvl = config.getInt( "gemStartLvl", category.getName(), d.gemStartLvl, 1, Integer.MAX_VALUE, "Set default start gem's level"); d.gemLvlUpStep = config.getInt( "gemLvlUpStep", category.getName(), d.gemLvlUpStep, 1, Integer.MAX_VALUE, "Set default level up gem's step"); save(); } @Override public void postLoadPre() { ArrayList<String> names = RPGHelper.getItemNames(RPGCapability.rpgItemRegistr.keySet(), true, false); Property prop = getPropertyStrings( "activeRPGItems", names.toArray(new String[names.size()]), "Set active RPG items (activated if 'isAllItemsRPGable' is false) (true/false)", false); if (!d.isAllItemsRPGable) { activeRPGItems = new HashSet<String>(Arrays.asList(prop.getStringList())); } save(); } @Override public void postLoadPost() { HashMap<Item, RPGItemData> map = (HashMap<Item, RPGItemData>) RPGCapability.rpgItemRegistr .getActiveElements(); customConfig(map); ArrayList<String> names = RPGHelper.getItemNames(map.keySet(), true, false); getPropertyStrings( "activeRPGItems", names.toArray(new String[names.size()]), "Set active RPG items (activated if 'isAllItemsRPGable' is false) (true/false)", true); names = RPGHelper.getItemNames(RPGCapability.rpgItemRegistr.keySet(), true, true); getPropertyStrings( "itemList", names.toArray(new String[names.size()]), "List of all items, which can be RPGable", true); save(); } protected void customConfig(HashMap<Item, RPGItemData> map) { String str = "customSetting"; Property prop = getPropertyStrings( "needCustomSetting", new String[] { Items.diamond_sword.delegate.name() }, "Set items, which needs customization", true); HashSet<String> needCustomSetting = new HashSet<String>(Arrays.asList(prop.getStringList())); if (!needCustomSetting.isEmpty()) { for (Entry<Item, RPGItemData> item : map.entrySet()) { if (needCustomSetting.contains(item.getKey().delegate.name())) { ConfigCategory cat = config .getCategory(Utils.toString(str, ".", item.getKey().delegate.name())); if (!item.getValue().isSupported) { cat.setComment("Warning: it isn't support from mod"); } for (Entry<ItemAttribute, ItemAttrParams> ia : item.getValue().attributes.entrySet()) { if (ia.getKey() .isConfigurable()) { ia.getValue().value = getIAValue(cat.getQualifiedName(), ia); if (ia.getValue().mul != null) { ia.getValue().mul = getIAMultiplier(cat.getQualifiedName(), ia); } } }
for (Entry<GemType, Stub<Integer>> gt : item.getValue().gems.entrySet()) {
13
2023-10-31 21:00:14+00:00
16k
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,994
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(); try { field.set(object, fieldValue); } catch (IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException("inject field value fail : " + field.getName() + ", field type must be String when objectId!"); } } if (idType == IdType.ASSIGN_ID) { Class<?> type = field.getType(); Object fieldValue = (type == java.lang.String.class) ? IdUtils.nextId() : IdUtils.nextLongId(); try { field.set(object, fieldValue); } catch (IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException("inject field value fail : " + field.getName() + ", field type must be String or Long when assignId!"); } } if (idType == IdType.UUID) { Object fieldValue = IdUtils.simpleUUID(); try { field.set(object, fieldValue); } catch (IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException("inject field value fail : " + field.getName() + ", field type must be String when uuid!"); } } } Object fieldValue = null; try { fieldValue = field.get(object); } catch (IllegalArgumentException | IllegalAccessException e) { e.printStackTrace(); } // 是否忽略null if (ignoreNulls && fieldValue == null) { continue; } columns.append(column).append(","); values.append("?").append(","); parameters.add(fieldValue); } String tableColumns = columns.subSequence(0, columns.length() - 1).toString(); String tableValues = values.subSequence(0, values.length() - 1).toString(); sql.append("INSERT INTO ").append(tableAnnotation.value()); sql.append(" (").append(tableColumns).append(")"); sql.append(" VALUES (").append(tableValues).append(")"); SqlProvider so = new SqlProvider(); so.setSql(sql.toString()); so.setParameters(parameters); return so; } /** * 构建更新SQL * * @param object 入参 * @return 组装完毕的SqlProvider */ public static SqlProvider updateByIdSql(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 whereColumns = new StringBuilder(); Object whereValues = new Object(); for (Field field : fields) { ReflectUtils.makeAccessible(field); Column columnAnnotation = field.getAnnotation(Column.class); if (columnAnnotation == null) { continue; } String column = columnAnnotation.value(); if (StringUtils.isEmpty(column)) { continue; } Object filedValue = null; try { filedValue = field.get(object); } catch (IllegalArgumentException | IllegalAccessException e) { e.printStackTrace(); } boolean primaryKey = columnAnnotation.primaryKey(); if (primaryKey) { whereColumns.append(column); whereValues = filedValue; continue; } // 是否忽略null if (ignoreNulls && filedValue == null) { continue; } columns.append(column).append("=?,"); parameters.add(filedValue); } if (whereValues == null) {
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(); try { field.set(object, fieldValue); } catch (IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException("inject field value fail : " + field.getName() + ", field type must be String when objectId!"); } } if (idType == IdType.ASSIGN_ID) { Class<?> type = field.getType(); Object fieldValue = (type == java.lang.String.class) ? IdUtils.nextId() : IdUtils.nextLongId(); try { field.set(object, fieldValue); } catch (IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException("inject field value fail : " + field.getName() + ", field type must be String or Long when assignId!"); } } if (idType == IdType.UUID) { Object fieldValue = IdUtils.simpleUUID(); try { field.set(object, fieldValue); } catch (IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException("inject field value fail : " + field.getName() + ", field type must be String when uuid!"); } } } Object fieldValue = null; try { fieldValue = field.get(object); } catch (IllegalArgumentException | IllegalAccessException e) { e.printStackTrace(); } // 是否忽略null if (ignoreNulls && fieldValue == null) { continue; } columns.append(column).append(","); values.append("?").append(","); parameters.add(fieldValue); } String tableColumns = columns.subSequence(0, columns.length() - 1).toString(); String tableValues = values.subSequence(0, values.length() - 1).toString(); sql.append("INSERT INTO ").append(tableAnnotation.value()); sql.append(" (").append(tableColumns).append(")"); sql.append(" VALUES (").append(tableValues).append(")"); SqlProvider so = new SqlProvider(); so.setSql(sql.toString()); so.setParameters(parameters); return so; } /** * 构建更新SQL * * @param object 入参 * @return 组装完毕的SqlProvider */ public static SqlProvider updateByIdSql(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 whereColumns = new StringBuilder(); Object whereValues = new Object(); for (Field field : fields) { ReflectUtils.makeAccessible(field); Column columnAnnotation = field.getAnnotation(Column.class); if (columnAnnotation == null) { continue; } String column = columnAnnotation.value(); if (StringUtils.isEmpty(column)) { continue; } Object filedValue = null; try { filedValue = field.get(object); } catch (IllegalArgumentException | IllegalAccessException e) { e.printStackTrace(); } boolean primaryKey = columnAnnotation.primaryKey(); if (primaryKey) { whereColumns.append(column); whereValues = filedValue; continue; } // 是否忽略null if (ignoreNulls && filedValue == null) { continue; } columns.append(column).append("=?,"); parameters.add(filedValue); } if (whereValues == null) {
throw new JdbcException("SqlGenerator updateByIdSql primaryKeyId can not null!");
2
2023-10-25 14:44:59+00:00
16k
ansforge/SAMU-Hub-Modeles
src/main/java/com/hubsante/model/cisu/CreateCase.java
[ { "identifier": "AdditionalInformation", "path": "src/main/java/com/hubsante/model/cisu/AdditionalInformation.java", "snippet": "@JsonPropertyOrder({AdditionalInformation.JSON_PROPERTY_CUSTOM_MAP})\n@JsonTypeName(\"additionalInformation\")\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\n\npublic class Add...
import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.dataformat.xml.annotation.*; import com.hubsante.model.cisu.AdditionalInformation; import com.hubsante.model.cisu.Alert; import com.hubsante.model.cisu.Location; import com.hubsante.model.cisu.Qualification; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Arrays; import java.util.List; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty;
10,923
/** * 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. */ /* * * * * * * * NOTE: This class is auto generated by OpenAPI Generator * (https://openapi-generator.tech). https://openapi-generator.tech Do not edit * the class manually. */ package com.hubsante.model.cisu; /** * CreateCase */ @JsonPropertyOrder( {CreateCase.JSON_PROPERTY_CASE_ID, CreateCase.JSON_PROPERTY_SENDER_CASE_ID, CreateCase.JSON_PROPERTY_CREATION, CreateCase.JSON_PROPERTY_REFERENCE_VERSION, CreateCase.JSON_PROPERTY_QUALIFICATION, CreateCase.JSON_PROPERTY_LOCATION, CreateCase.JSON_PROPERTY_INITIAL_ALERT, CreateCase.JSON_PROPERTY_NEW_ALERT, CreateCase.JSON_PROPERTY_ADDITIONAL_INFORMATION, CreateCase.JSON_PROPERTY_FREETEXT}) @JsonTypeName("createCase") @JsonInclude(JsonInclude.Include.NON_EMPTY) public class CreateCase { public static final String JSON_PROPERTY_CASE_ID = "caseId"; private String caseId; public static final String JSON_PROPERTY_SENDER_CASE_ID = "senderCaseId"; private String senderCaseId; public static final String JSON_PROPERTY_CREATION = "creation"; private OffsetDateTime creation; public static final String JSON_PROPERTY_REFERENCE_VERSION = "referenceVersion"; private String referenceVersion; public static final String JSON_PROPERTY_QUALIFICATION = "qualification"; private Qualification qualification; public static final String JSON_PROPERTY_LOCATION = "location";
/** * 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. */ /* * * * * * * * NOTE: This class is auto generated by OpenAPI Generator * (https://openapi-generator.tech). https://openapi-generator.tech Do not edit * the class manually. */ package com.hubsante.model.cisu; /** * CreateCase */ @JsonPropertyOrder( {CreateCase.JSON_PROPERTY_CASE_ID, CreateCase.JSON_PROPERTY_SENDER_CASE_ID, CreateCase.JSON_PROPERTY_CREATION, CreateCase.JSON_PROPERTY_REFERENCE_VERSION, CreateCase.JSON_PROPERTY_QUALIFICATION, CreateCase.JSON_PROPERTY_LOCATION, CreateCase.JSON_PROPERTY_INITIAL_ALERT, CreateCase.JSON_PROPERTY_NEW_ALERT, CreateCase.JSON_PROPERTY_ADDITIONAL_INFORMATION, CreateCase.JSON_PROPERTY_FREETEXT}) @JsonTypeName("createCase") @JsonInclude(JsonInclude.Include.NON_EMPTY) public class CreateCase { public static final String JSON_PROPERTY_CASE_ID = "caseId"; private String caseId; public static final String JSON_PROPERTY_SENDER_CASE_ID = "senderCaseId"; private String senderCaseId; public static final String JSON_PROPERTY_CREATION = "creation"; private OffsetDateTime creation; public static final String JSON_PROPERTY_REFERENCE_VERSION = "referenceVersion"; private String referenceVersion; public static final String JSON_PROPERTY_QUALIFICATION = "qualification"; private Qualification qualification; public static final String JSON_PROPERTY_LOCATION = "location";
private Location location;
2
2023-10-25 14:24:31+00:00
16k
sschr15/rgml-quilt
client/src/main/risugami/org/duvetmc/rgml/mixin/CrashScreenMixin.java
[ { "identifier": "Constants", "path": "client/src/main/java/org/duvetmc/mods/rgmlquilt/util/Constants.java", "snippet": "public class Constants {\n\tpublic static final String MOD_ID = \"rgml-quilt\";\n\tpublic static final String VERSION = QuiltLoader.getModContainer(MOD_ID).get().metadata().version().t...
import net.minecraft.unmapped.C_6406257; import org.duvetmc.mods.rgmlquilt.util.Constants; import org.duvetmc.rgml.BaseMod; import org.duvetmc.rgml.ModLoader; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.Constant; import org.spongepowered.asm.mixin.injection.ModifyConstant; import java.util.ArrayList; import java.util.List;
12,323
package org.duvetmc.rgml.mixin; @Mixin(C_6406257.class) public class CrashScreenMixin { @ModifyConstant(method = "<init>", constant = @Constant(stringValue = "OS: ")) private String rgml$injectRgmlMods(String os) { List<String> lines = new ArrayList<>(); lines.add("ModLoader Beta 1.8.1"); lines.add("RGML-Quilt " + Constants.VERSION); lines.add("Mods loaded: " + ModLoader.getLoadedMods().size());
package org.duvetmc.rgml.mixin; @Mixin(C_6406257.class) public class CrashScreenMixin { @ModifyConstant(method = "<init>", constant = @Constant(stringValue = "OS: ")) private String rgml$injectRgmlMods(String os) { List<String> lines = new ArrayList<>(); lines.add("ModLoader Beta 1.8.1"); lines.add("RGML-Quilt " + Constants.VERSION); lines.add("Mods loaded: " + ModLoader.getLoadedMods().size());
for (BaseMod mod : ModLoader.getLoadedMods()) {
1
2023-10-31 14:17:42+00:00
16k
simply-kel/AlinLib
src/main/java/ru/kelcuprum/alinlib/gui/screens/AlinaDemoScreen.java
[ { "identifier": "AlinLib", "path": "src/main/java/ru/kelcuprum/alinlib/AlinLib.java", "snippet": "public class AlinLib implements ClientModInitializer {\r\n public static final Logger LOG = LogManager.getLogger(\"AlinaLib\");\r\n public static Config bariumConfig = new Config(\"config/AlibLib/conf...
import net.minecraft.Util; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.AbstractWidget; import net.minecraft.client.gui.screens.*; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import ru.kelcuprum.alinlib.AlinLib; import ru.kelcuprum.alinlib.Colors; import ru.kelcuprum.alinlib.config.Localization; import ru.kelcuprum.alinlib.gui.InterfaceUtils; import ru.kelcuprum.alinlib.gui.components.buttons.ButtonSprite; import ru.kelcuprum.alinlib.gui.components.editbox.EditBoxString; import ru.kelcuprum.alinlib.gui.components.sliders.SliderInteger; import ru.kelcuprum.alinlib.gui.components.sliders.SliderPercent; import ru.kelcuprum.alinlib.gui.components.text.TextBox; import ru.kelcuprum.alinlib.gui.components.buttons.ButtonBoolean; import ru.kelcuprum.alinlib.gui.components.buttons.Button; import ru.kelcuprum.alinlib.gui.components.editbox.EditBoxColor; import ru.kelcuprum.alinlib.gui.components.selector.SelectorStringButton; import ru.kelcuprum.alinlib.gui.toast.AlinaToast; import java.util.ArrayList; import java.util.List;
14,038
package ru.kelcuprum.alinlib.gui.screens; public class AlinaDemoScreen extends Screen { private final Screen parent; private static final ResourceLocation icon = new ResourceLocation("alinlib", "textures/gui/widget/test/well.png"); private static final Component TITLE = Component.literal("AlinLib"); private static final Component CATEGORY = Component.literal("Example page"); private static final Component EDIT_BOX = Component.literal("Edit Box"); private static final Component SECRET_EDIT_BOX = Component.literal("Secret Edit Box"); private static final Component COLOR_EDIT_BOX = Component.literal("Color Edit Box"); private static final Component SLIDER_PERCENT = Component.literal("Slider Percent"); private static final Component SLIDER_INTEGER = Component.literal("Slider Integer"); private static final Component SOMETHING = Component.translatable("alinlib.something"); private static final Component GITHUB = Component.literal("GitHub"); private static final Component EXIT = Component.literal("Exit"); // private int scrolled = 0; // private InterfaceUtils.DesignType type = InterfaceUtils.DesignType.ALINA; // private List<AbstractWidget> widgetList = new ArrayList<AbstractWidget>(); private TextBox titleBox; private EditBoxString stringEditBox; private EditBoxString stringEditBoxSecret; private ButtonBoolean booleanButton; String[] hell = { "Hello", ",", "World", "!", "No...", "Welcome to Hell :)" }; private SelectorStringButton selectorStringButton; private EditBoxColor colorEditBox; private SliderPercent sliderPercent; private SliderInteger sliderInt; // private TextBox something; public AlinaDemoScreen(Screen parent) { super(CATEGORY); this.parent = parent; } public void tick() { for(int i=0; i<widgetList.size();i++){ if(i==0) widgetList.get(i).setY(15-scrolled); else widgetList.get(i).setY(40 + (25*(i-1))-scrolled); } super.tick(); } @Override public void init() { scrolled = 0; initButton(); initButtonsCategory(); } private void initButtonsCategory(){ this.widgetList = new ArrayList<AbstractWidget>(); titleBox = new TextBox(140, 15, this.width - 150, this.font.lineHeight, CATEGORY, true); titleBox.setTooltip(Localization.toText("Hello, world!")); addRenderableWidget(titleBox); widgetList.add(titleBox); // booleanButton = new ButtonBoolean(140, 40, this.width - 150, 20, type, AlinLib.bariumConfig, "Boolean", true, Component.literal("Boolean")); addRenderableWidget(booleanButton); widgetList.add(booleanButton); // stringEditBox = new EditBoxString(140, 40+(25*2), width-150, 20, AlinLib.bariumConfig.getString("HELLO", "Hello, world!"), type, EDIT_BOX, (string) -> AlinLib.bariumConfig.setString("HELLO", string)); addRenderableWidget(stringEditBox); widgetList.add(stringEditBox); // stringEditBoxSecret = new EditBoxString(140, 40+(25*2), width-150, 20, true, AlinLib.bariumConfig.getString("SECRET", "Alina doesn't have a boyfriend"), type, SECRET_EDIT_BOX, (string) -> AlinLib.bariumConfig.setString("SECRET", string)); addRenderableWidget(stringEditBoxSecret); widgetList.add(stringEditBoxSecret); // selectorStringButton = new SelectorStringButton(140, 40+(25*3), this.width - 150, 20, type, hell, AlinLib.bariumConfig, "selector", hell[0], Component.literal("Selector")); addRenderableWidget(selectorStringButton); widgetList.add(selectorStringButton); // colorEditBox = new EditBoxColor(140, 40+(25*4), width-150, 20, type, AlinLib.bariumConfig, "Color", 0xFFFFFF, COLOR_EDIT_BOX); addRenderableWidget(colorEditBox); widgetList.add(colorEditBox); // sliderPercent = new SliderPercent(140, 40+(25*5), width-150, 20, type, AlinLib.bariumConfig, "Slider_percent", 0, SLIDER_PERCENT); addRenderableWidget(sliderPercent); widgetList.add(sliderPercent); // sliderInt = new SliderInteger(140, 40+(25*6), width-150, 20, type, AlinLib.bariumConfig, "Slider_int", 30, 30, 110, SLIDER_INTEGER); sliderInt.setTypeInteger(" Coffee"); addRenderableWidget(sliderInt); widgetList.add(sliderInt); // something = new TextBox(140, 40+(25*7), this.width - 150, 20, SOMETHING, true, (OnPress) -> { OnPress.setActive(false); AlinLib.log(Component.translatable("alinlib.something.oops")); this.minecraft.stop(); }); addRenderableWidget(something); widgetList.add(something); } private void initButton(){ // line 0 addRenderableWidget(new Button(10, 40, 110, 20, InterfaceUtils.DesignType.VANILLA, Colors.KENNY, Component.literal("DesignType.VANILLA"), (OnPress) -> {
package ru.kelcuprum.alinlib.gui.screens; public class AlinaDemoScreen extends Screen { private final Screen parent; private static final ResourceLocation icon = new ResourceLocation("alinlib", "textures/gui/widget/test/well.png"); private static final Component TITLE = Component.literal("AlinLib"); private static final Component CATEGORY = Component.literal("Example page"); private static final Component EDIT_BOX = Component.literal("Edit Box"); private static final Component SECRET_EDIT_BOX = Component.literal("Secret Edit Box"); private static final Component COLOR_EDIT_BOX = Component.literal("Color Edit Box"); private static final Component SLIDER_PERCENT = Component.literal("Slider Percent"); private static final Component SLIDER_INTEGER = Component.literal("Slider Integer"); private static final Component SOMETHING = Component.translatable("alinlib.something"); private static final Component GITHUB = Component.literal("GitHub"); private static final Component EXIT = Component.literal("Exit"); // private int scrolled = 0; // private InterfaceUtils.DesignType type = InterfaceUtils.DesignType.ALINA; // private List<AbstractWidget> widgetList = new ArrayList<AbstractWidget>(); private TextBox titleBox; private EditBoxString stringEditBox; private EditBoxString stringEditBoxSecret; private ButtonBoolean booleanButton; String[] hell = { "Hello", ",", "World", "!", "No...", "Welcome to Hell :)" }; private SelectorStringButton selectorStringButton; private EditBoxColor colorEditBox; private SliderPercent sliderPercent; private SliderInteger sliderInt; // private TextBox something; public AlinaDemoScreen(Screen parent) { super(CATEGORY); this.parent = parent; } public void tick() { for(int i=0; i<widgetList.size();i++){ if(i==0) widgetList.get(i).setY(15-scrolled); else widgetList.get(i).setY(40 + (25*(i-1))-scrolled); } super.tick(); } @Override public void init() { scrolled = 0; initButton(); initButtonsCategory(); } private void initButtonsCategory(){ this.widgetList = new ArrayList<AbstractWidget>(); titleBox = new TextBox(140, 15, this.width - 150, this.font.lineHeight, CATEGORY, true); titleBox.setTooltip(Localization.toText("Hello, world!")); addRenderableWidget(titleBox); widgetList.add(titleBox); // booleanButton = new ButtonBoolean(140, 40, this.width - 150, 20, type, AlinLib.bariumConfig, "Boolean", true, Component.literal("Boolean")); addRenderableWidget(booleanButton); widgetList.add(booleanButton); // stringEditBox = new EditBoxString(140, 40+(25*2), width-150, 20, AlinLib.bariumConfig.getString("HELLO", "Hello, world!"), type, EDIT_BOX, (string) -> AlinLib.bariumConfig.setString("HELLO", string)); addRenderableWidget(stringEditBox); widgetList.add(stringEditBox); // stringEditBoxSecret = new EditBoxString(140, 40+(25*2), width-150, 20, true, AlinLib.bariumConfig.getString("SECRET", "Alina doesn't have a boyfriend"), type, SECRET_EDIT_BOX, (string) -> AlinLib.bariumConfig.setString("SECRET", string)); addRenderableWidget(stringEditBoxSecret); widgetList.add(stringEditBoxSecret); // selectorStringButton = new SelectorStringButton(140, 40+(25*3), this.width - 150, 20, type, hell, AlinLib.bariumConfig, "selector", hell[0], Component.literal("Selector")); addRenderableWidget(selectorStringButton); widgetList.add(selectorStringButton); // colorEditBox = new EditBoxColor(140, 40+(25*4), width-150, 20, type, AlinLib.bariumConfig, "Color", 0xFFFFFF, COLOR_EDIT_BOX); addRenderableWidget(colorEditBox); widgetList.add(colorEditBox); // sliderPercent = new SliderPercent(140, 40+(25*5), width-150, 20, type, AlinLib.bariumConfig, "Slider_percent", 0, SLIDER_PERCENT); addRenderableWidget(sliderPercent); widgetList.add(sliderPercent); // sliderInt = new SliderInteger(140, 40+(25*6), width-150, 20, type, AlinLib.bariumConfig, "Slider_int", 30, 30, 110, SLIDER_INTEGER); sliderInt.setTypeInteger(" Coffee"); addRenderableWidget(sliderInt); widgetList.add(sliderInt); // something = new TextBox(140, 40+(25*7), this.width - 150, 20, SOMETHING, true, (OnPress) -> { OnPress.setActive(false); AlinLib.log(Component.translatable("alinlib.something.oops")); this.minecraft.stop(); }); addRenderableWidget(something); widgetList.add(something); } private void initButton(){ // line 0 addRenderableWidget(new Button(10, 40, 110, 20, InterfaceUtils.DesignType.VANILLA, Colors.KENNY, Component.literal("DesignType.VANILLA"), (OnPress) -> {
this.minecraft.getToasts().addToast(new AlinaToast(Component.literal("AlinLib"), Component.literal("Set DesignType.VANILLA"), AlinaToast.Type.DEBUG));
13
2023-10-29 13:30:26+00:00
16k
LeoK99/swtw45WS21_reupload
src/main/java/com/buschmais/frontend/components/CreateNewGroupDialog.java
[ { "identifier": "AccessGroup", "path": "src/main/java/com/buschmais/backend/adrAccess/AccessGroup.java", "snippet": "@Document\n@Data\npublic class AccessGroup implements Comparable<AccessGroup> {\n\n\t@Setter(AccessLevel.PRIVATE)\n\t@EqualsAndHashCode.Exclude\n\t@Id\n\tprivate String id;\n\n\t@Indexed\...
import com.buschmais.backend.adrAccess.AccessGroup; import com.buschmais.backend.adrAccess.AccessRights; import com.buschmais.backend.adrAccess.dataAccess.ADRAccessDao; 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.vars.StringConstantsFrontend; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.checkbox.CheckboxGroup; import com.vaadin.flow.component.checkbox.CheckboxGroupVariant; import com.vaadin.flow.component.combobox.ComboBox; import com.vaadin.flow.component.dependency.CssImport; import com.vaadin.flow.component.dialog.Dialog; import com.vaadin.flow.component.html.Div; import com.vaadin.flow.component.html.Span; import com.vaadin.flow.component.icon.Icon; import com.vaadin.flow.component.icon.VaadinIcon; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.textfield.TextField; import lombok.NonNull; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import static com.buschmais.frontend.vars.StringConstantsFrontend.*;
12,292
package com.buschmais.frontend.components; @CssImport(value = "./themes/adr-workbench/vaadin-components/buttons.css") @CssImport(value = "./themes/adr-workbench/vaadin-components/vaadin-checkbox-group-styles.css", themeFor = "vaadin-checkbox-group") @CssImport(value = "./themes/adr-workbench/vaadin-components/vaadin-checkbox-styles.css", themeFor = "vaadin-checkbox") public class CreateNewGroupDialog extends Dialog { private final UserDao userDao; private final ADRAccessDao adrAccessDao; private VerticalLayout mainLayout; private HorizontalLayout manageLayout; private VerticalLayout boxandrightsLayout; private HorizontalLayout buttonsLayout; private Div membersDiv; private TextField groupname; private Button createButton; private Button cancelButton; private ComboBox<User> users; private CheckboxGroup<String> rightsbox; private Set<User> choosedUsers, selectUser; private Set<String> choosedRights; private List<String> rightsList; public CreateNewGroupDialog(@NonNull UserDao userDao, @NonNull ADRAccessDao adrAccessDao) { super(); this.userDao = userDao; this.adrAccessDao = adrAccessDao; this.setModal(true); this.setSizeUndefined(); this.setCloseOnEsc(true); this.setCloseOnOutsideClick(true); this.setResizable(true); this.setDraggable(true); this.setMinWidth("min-content"); this.setMinHeight("min-content"); this.setWidth("initial"); this.setMaxWidth("40%"); this.setHeight("initial"); this.setMaxHeight("90%"); mainLayout = new VerticalLayout(); manageLayout = new HorizontalLayout(); boxandrightsLayout = new VerticalLayout(); buttonsLayout = new HorizontalLayout(); membersDiv = new Div(); groupname = new TextField(); groupname.setLabel(StringConstantsFrontend.CREATENEWGROUP_NAME); groupname.setClearButtonVisible(true); manageLayout.add(membersDiv, boxandrightsLayout); mainLayout.add(groupname); mainLayout.add(manageLayout, buttonsLayout); this.add(mainLayout); selectUser = new HashSet<>(); choosedUsers = new HashSet<>(); usersboxConfigure(); rightsbox = new CheckboxGroup<>(); choosedRights = new HashSet<>(); rightsboxConfigure(); createButton = new Button(GENERAL_DIALOG_BUTTON_SAVE); createButton.addClassName("confirm-button"); cancelButton = new Button(GENERAL_DIALOG_BUTTON_CANCEL); cancelButton.addClassName("cancel-button"); buttonsLayout.add(createButton, cancelButton); buttonsConfigure(); } private void usersboxConfigure(){ selectUser.addAll(this.userDao.findAll()); users = new ComboBox<>(StringConstantsFrontend.CREATENEWGROUP_USERS); ComboBox.ItemFilter<User> filter = (user, filterString) -> user.getUserName().toLowerCase().startsWith(filterString.toLowerCase()); users.setItems(filter, selectUser); users.setItemLabelGenerator(User::getUserName); users.addValueChangeListener(event -> { if (event.getValue() != null) { User u = event.getValue(); Span userSpan = new Span(new Icon(VaadinIcon.CLOSE), new Span(u.getUserName())); userSpan.getElement().getThemeList().add("badge primary"); choosedUsers.add(u); membersDiv.add(userSpan); userSpan.addClickListener(e -> { choosedUsers.remove(u); membersDiv.remove(userSpan); selectUser.add(u); users.setItems(filter, selectUser); }); selectUser.remove(u); users.setItems(filter, selectUser); } }); boxandrightsLayout.add(users); } private void rightsboxConfigure(){ rightsbox.setLabel(StringConstantsFrontend.CREATENEWGROUP_RIGHTS); rightsbox.addThemeVariants(CheckboxGroupVariant.LUMO_VERTICAL); rightsList = new ArrayList<>(); rightsList.add(GROUP_READABLE); rightsList.add(GROUP_WRITABLE); rightsList.add(GROUP_VOTABLE); rightsbox.setItems(rightsList); boxandrightsLayout.add(rightsbox); } private void buttonsConfigure(){ createButton.addClickListener(event -> { synchronized (adrAccessDao) { if(!groupname.isEmpty()){ AccessRights ar = new AccessRights(false,false,false); choosedRights = rightsbox.getValue(); if(choosedRights.contains(GROUP_READABLE)){ ar.setReadable(true); } if(choosedRights.contains(GROUP_WRITABLE)){ ar.setWritable(true); } if(choosedRights.contains(GROUP_VOTABLE)){ ar.setVotable(true); } AccessGroup ag = new AccessGroup(groupname.getValue(),ar); ag.addUsers(choosedUsers); ag = adrAccessDao.save(ag); this.close();
package com.buschmais.frontend.components; @CssImport(value = "./themes/adr-workbench/vaadin-components/buttons.css") @CssImport(value = "./themes/adr-workbench/vaadin-components/vaadin-checkbox-group-styles.css", themeFor = "vaadin-checkbox-group") @CssImport(value = "./themes/adr-workbench/vaadin-components/vaadin-checkbox-styles.css", themeFor = "vaadin-checkbox") public class CreateNewGroupDialog extends Dialog { private final UserDao userDao; private final ADRAccessDao adrAccessDao; private VerticalLayout mainLayout; private HorizontalLayout manageLayout; private VerticalLayout boxandrightsLayout; private HorizontalLayout buttonsLayout; private Div membersDiv; private TextField groupname; private Button createButton; private Button cancelButton; private ComboBox<User> users; private CheckboxGroup<String> rightsbox; private Set<User> choosedUsers, selectUser; private Set<String> choosedRights; private List<String> rightsList; public CreateNewGroupDialog(@NonNull UserDao userDao, @NonNull ADRAccessDao adrAccessDao) { super(); this.userDao = userDao; this.adrAccessDao = adrAccessDao; this.setModal(true); this.setSizeUndefined(); this.setCloseOnEsc(true); this.setCloseOnOutsideClick(true); this.setResizable(true); this.setDraggable(true); this.setMinWidth("min-content"); this.setMinHeight("min-content"); this.setWidth("initial"); this.setMaxWidth("40%"); this.setHeight("initial"); this.setMaxHeight("90%"); mainLayout = new VerticalLayout(); manageLayout = new HorizontalLayout(); boxandrightsLayout = new VerticalLayout(); buttonsLayout = new HorizontalLayout(); membersDiv = new Div(); groupname = new TextField(); groupname.setLabel(StringConstantsFrontend.CREATENEWGROUP_NAME); groupname.setClearButtonVisible(true); manageLayout.add(membersDiv, boxandrightsLayout); mainLayout.add(groupname); mainLayout.add(manageLayout, buttonsLayout); this.add(mainLayout); selectUser = new HashSet<>(); choosedUsers = new HashSet<>(); usersboxConfigure(); rightsbox = new CheckboxGroup<>(); choosedRights = new HashSet<>(); rightsboxConfigure(); createButton = new Button(GENERAL_DIALOG_BUTTON_SAVE); createButton.addClassName("confirm-button"); cancelButton = new Button(GENERAL_DIALOG_BUTTON_CANCEL); cancelButton.addClassName("cancel-button"); buttonsLayout.add(createButton, cancelButton); buttonsConfigure(); } private void usersboxConfigure(){ selectUser.addAll(this.userDao.findAll()); users = new ComboBox<>(StringConstantsFrontend.CREATENEWGROUP_USERS); ComboBox.ItemFilter<User> filter = (user, filterString) -> user.getUserName().toLowerCase().startsWith(filterString.toLowerCase()); users.setItems(filter, selectUser); users.setItemLabelGenerator(User::getUserName); users.addValueChangeListener(event -> { if (event.getValue() != null) { User u = event.getValue(); Span userSpan = new Span(new Icon(VaadinIcon.CLOSE), new Span(u.getUserName())); userSpan.getElement().getThemeList().add("badge primary"); choosedUsers.add(u); membersDiv.add(userSpan); userSpan.addClickListener(e -> { choosedUsers.remove(u); membersDiv.remove(userSpan); selectUser.add(u); users.setItems(filter, selectUser); }); selectUser.remove(u); users.setItems(filter, selectUser); } }); boxandrightsLayout.add(users); } private void rightsboxConfigure(){ rightsbox.setLabel(StringConstantsFrontend.CREATENEWGROUP_RIGHTS); rightsbox.addThemeVariants(CheckboxGroupVariant.LUMO_VERTICAL); rightsList = new ArrayList<>(); rightsList.add(GROUP_READABLE); rightsList.add(GROUP_WRITABLE); rightsList.add(GROUP_VOTABLE); rightsbox.setItems(rightsList); boxandrightsLayout.add(rightsbox); } private void buttonsConfigure(){ createButton.addClickListener(event -> { synchronized (adrAccessDao) { if(!groupname.isEmpty()){ AccessRights ar = new AccessRights(false,false,false); choosedRights = rightsbox.getValue(); if(choosedRights.contains(GROUP_READABLE)){ ar.setReadable(true); } if(choosedRights.contains(GROUP_WRITABLE)){ ar.setWritable(true); } if(choosedRights.contains(GROUP_VOTABLE)){ ar.setVotable(true); } AccessGroup ag = new AccessGroup(groupname.getValue(),ar); ag.addUsers(choosedUsers); ag = adrAccessDao.save(ag); this.close();
Broadcaster.broadcastMessage(BroadcastListener.Event.GROUP_CHANGED, ag.getId(), this);
6
2023-10-25 15:18:06+00:00
16k
Java-Game-Engine-Merger/Libgdx-Processing
framework0004/framework0004-terminal/src/main/java/com/jediterm/app/JediTerm.java
[ { "identifier": "Platform", "path": "framework0004/framework0004-terminal/src/main/java/com/jediterm/core/Platform.java", "snippet": "public enum Platform{\n Windows,\n OS2,\n Mac,\n Linux,\n Other;\n private static @NotNull String getOsNameLowerCase() {\n return System.getProperty(\"os.name\")...
import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.function.Function; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import com.jediterm.core.Platform; import com.jediterm.core.compatibility.Charsets; import com.jediterm.pty.PtyProcessTtyConnector; import com.jediterm.terminal.LoggingTtyConnector; import com.jediterm.terminal.TtyConnector; import com.jediterm.terminal.model.LinesBuffer; import com.jediterm.terminal.model.TerminalTextBuffer; import com.jediterm.terminal.model.hyperlinks.HyperlinkFilter; import com.jediterm.terminal.ui.JediTermWidget; import com.jediterm.terminal.ui.TerminalWidget; import com.jediterm.terminal.ui.UIUtil; import com.jediterm.terminal.ui.settings.DefaultTabbedSettingsProvider; import com.jediterm.terminal.ui.settings.SettingsProvider; import com.jediterm.terminal.ui.settings.TabbedSettingsProvider; import com.jediterm.terminal.util.Pair; import com.jediterm.ui.AbstractTerminalFrame; import com.pty4j.PtyProcess; import com.pty4j.PtyProcessBuilder;
14,397
// JediTerm.java package com.jediterm.app; public final class JediTerm extends AbstractTerminalFrame{ @NotNull protected JediTabbedTerminalWidget createTabbedTerminalWidget() { return (JediTabbedTerminalWidget)(new JediTabbedTerminalWidget((TabbedSettingsProvider)(new DefaultTabbedSettingsProvider()),(Function)(new Function() { // $FF: synthetic method // $FF: bridge method public Object apply(Object var1) { return this.apply((Pair)var1); } public final JediTerminalWidget apply(Pair pair) {
// JediTerm.java package com.jediterm.app; public final class JediTerm extends AbstractTerminalFrame{ @NotNull protected JediTabbedTerminalWidget createTabbedTerminalWidget() { return (JediTabbedTerminalWidget)(new JediTabbedTerminalWidget((TabbedSettingsProvider)(new DefaultTabbedSettingsProvider()),(Function)(new Function() { // $FF: synthetic method // $FF: bridge method public Object apply(Object var1) { return this.apply((Pair)var1); } public final JediTerminalWidget apply(Pair pair) {
JediTermWidget var10000=JediTerm.this.openSession(pair!=null?(TerminalWidget)pair.getFirst():null);
8
2023-10-27 05:47:39+00:00
16k
llllllxy/tinycloud
tinycloud-user/src/main/java/org/tinycloud/user/service/impl/UcUserServiceImpl.java
[ { "identifier": "UcUser", "path": "tinycloud-bean/src/main/java/org/tinycloud/bean/entity/UcUser.java", "snippet": "@TableName(\"t_uc_user\")\n@ApiModel(value = \"UcUser对象\", description = \"系统用户信息表\")\npublic class UcUser implements Serializable {\n private static final long serialVersionUID = 1L;\n...
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.tinycloud.bean.entity.UcUser; import org.tinycloud.bean.param.UcUserPageQuery; import org.tinycloud.bean.vo.UcUserVo; import org.tinycloud.common.consts.GlobalConstant; import org.tinycloud.common.model.PageModel; import org.tinycloud.common.utils.LambdaUtils; import org.tinycloud.common.utils.StringUtils; import org.tinycloud.common.utils.bean.BeanUtils; import org.tinycloud.user.mapper.UcUserMapper; import org.tinycloud.user.service.UcUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import java.util.stream.Collectors;
12,004
package org.tinycloud.user.service.impl; @Service public class UcUserServiceImpl implements UcUserService { @Autowired private UcUserMapper ucUserMapper; /** * 根据id查询详情 * @param userId * @return */ @Override public UcUserVo detail(String userId) { UcUser ucUser = this.ucUserMapper.selectOne(Wrappers.<UcUser>lambdaQuery() .eq(UcUser::getUserId, userId) .eq(UcUser::getDelFlag, GlobalConstant.NOT_DELETED)); if (ucUser != null) { return BeanUtils.transformBean(ucUser, UcUserVo.class); } return null; } /** * 第二种动态排序的方法 * @param pageQuery UcUserPageQuery * @return PageModel<UcUserVo> */ @Override public PageModel<UcUserVo> query(UcUserPageQuery pageQuery) { PageModel<UcUserVo> responsePage = new PageModel<>(pageQuery.getPageNo(), pageQuery.getPageSize()); LambdaQueryWrapper<UcUser> wrapper = new LambdaQueryWrapper<>(); boolean isAsc = false; if (GlobalConstant.ASC.equalsIgnoreCase(pageQuery.getSortType())) { isAsc = true; }
package org.tinycloud.user.service.impl; @Service public class UcUserServiceImpl implements UcUserService { @Autowired private UcUserMapper ucUserMapper; /** * 根据id查询详情 * @param userId * @return */ @Override public UcUserVo detail(String userId) { UcUser ucUser = this.ucUserMapper.selectOne(Wrappers.<UcUser>lambdaQuery() .eq(UcUser::getUserId, userId) .eq(UcUser::getDelFlag, GlobalConstant.NOT_DELETED)); if (ucUser != null) { return BeanUtils.transformBean(ucUser, UcUserVo.class); } return null; } /** * 第二种动态排序的方法 * @param pageQuery UcUserPageQuery * @return PageModel<UcUserVo> */ @Override public PageModel<UcUserVo> query(UcUserPageQuery pageQuery) { PageModel<UcUserVo> responsePage = new PageModel<>(pageQuery.getPageNo(), pageQuery.getPageSize()); LambdaQueryWrapper<UcUser> wrapper = new LambdaQueryWrapper<>(); boolean isAsc = false; if (GlobalConstant.ASC.equalsIgnoreCase(pageQuery.getSortType())) { isAsc = true; }
wrapper.like(StringUtils.isNotEmpty(pageQuery.getUsername()), UcUser::getUsername, pageQuery.getUsername());
6
2023-10-28 02:05:15+00:00
16k
llllllxy/bluewind-base
src/main/java/com/bluewind/base/module/system/auth/controller/AuthController.java
[ { "identifier": "BaseController", "path": "src/main/java/com/bluewind/base/common/base/BaseController.java", "snippet": "public abstract class BaseController {\n private static final Logger logger = LoggerFactory.getLogger(BaseController.class);\n public static final String RESULT_ROWS = \"rows\";...
import com.bluewind.base.common.base.BaseController; import com.bluewind.base.common.base.Result; import com.bluewind.base.common.config.auth.constant.AuthConstant; import com.bluewind.base.common.config.auth.util.AuthUtil; import com.bluewind.base.common.config.auth.util.PasswordUtils; import com.bluewind.base.common.config.auth.util.UserInfoUtil; import com.bluewind.base.common.util.redis.RedisUtils; import com.bluewind.base.common.util.web.CookieUtils; import com.bluewind.base.module.system.auth.service.AuthService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; import org.apache.shiro.subject.Subject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.UUID;
11,605
package com.bluewind.base.module.system.auth.controller; /** * @author liuxingyu01 * @date 2022-08-26 15:05 * @description 本地后台登录管理 **/ @RestController @Api(value = "本地后台登录管理", tags = "本地后台登录管理") public class AuthController extends BaseController { final static Logger logger = LoggerFactory.getLogger(AuthController.class); @Autowired private RedisUtils redisUtils; @Autowired
package com.bluewind.base.module.system.auth.controller; /** * @author liuxingyu01 * @date 2022-08-26 15:05 * @description 本地后台登录管理 **/ @RestController @Api(value = "本地后台登录管理", tags = "本地后台登录管理") public class AuthController extends BaseController { final static Logger logger = LoggerFactory.getLogger(AuthController.class); @Autowired private RedisUtils redisUtils; @Autowired
private AuthService authService;
8
2023-10-26 10:02:07+00:00
16k
danielbatres/orthodontic-dentistry-clinical-management
src/com/view/readPct/ModificarControlFields.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.model.ControlMensualModel; import com.utils.Styles; import com.utils.Tools; import com.view.createPacient.NewContext; import static com.view.createPacient.NewContext.dateTimeFormatter; import java.time.LocalDateTime;
11,034
package com.view.readPct; /** * * @author Daniel Batres */ public class ModificarControlFields extends Styles { /** * Creates new form NuevoControlFields */ public ModificarControlFields() { initComponents(); styleMyComponentBaby(); } public ControlMensualModel getData() { ControlMensualModel controlMensual = new ControlMensualModel();
package com.view.readPct; /** * * @author Daniel Batres */ public class ModificarControlFields extends Styles { /** * Creates new form NuevoControlFields */ public ModificarControlFields() { initComponents(); styleMyComponentBaby(); } public ControlMensualModel getData() { ControlMensualModel controlMensual = new ControlMensualModel();
controlMensual.setId(ApplicationContext.selectedControlMensual.getId());
0
2023-10-26 19:35:40+00:00
16k
dawex/sigourney
trust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/v2310/serialization/JacksonModuleFactory.java
[ { "identifier": "FormatProvider", "path": "trust-framework/verifiable-credentials-core/src/main/java/com/dawex/sigourney/trustframework/vc/core/jsonld/serialization/FormatProvider.java", "snippet": "public interface FormatProvider {\n\n\t/**\n\t * Returns the format matching the specified format name\n\...
import com.dawex.sigourney.trustframework.vc.core.Proof; import com.dawex.sigourney.trustframework.vc.core.SignedObject; import com.dawex.sigourney.trustframework.vc.core.jsonld.annotation.JsonLdContexts; import com.dawex.sigourney.trustframework.vc.core.jsonld.serialization.FormatProvider; import com.dawex.sigourney.trustframework.vc.core.jsonld.serialization.JsonLdContextsSerializer; import com.dawex.sigourney.trustframework.vc.core.jsonld.serialization.JsonLdSerializer; import com.dawex.sigourney.trustframework.vc.core.jsonld.serialization.SignedObjectJsonLdSerializer; import com.dawex.sigourney.trustframework.vc.model.shared.Did; import com.dawex.sigourney.trustframework.vc.model.shared.JsonWebKey2020; import com.dawex.sigourney.trustframework.vc.model.v2310.common.Address; import com.dawex.sigourney.trustframework.vc.model.v2310.dataproduct.AggregationOf; import com.dawex.sigourney.trustframework.vc.model.v2310.dataproduct.DataProductCredentialSubject; import com.dawex.sigourney.trustframework.vc.model.v2310.dataproduct.DataProductVerifiableCredential; import com.dawex.sigourney.trustframework.vc.model.v2310.dataproduct.Distribution; import com.dawex.sigourney.trustframework.vc.model.v2310.dataproduct.Location; import com.dawex.sigourney.trustframework.vc.model.v2310.organisation.OrganisationCredentialSubject; import com.dawex.sigourney.trustframework.vc.model.v2310.organisation.OrganisationVerifiableCredential; import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.module.SimpleModule; import java.util.function.Supplier;
12,939
package com.dawex.sigourney.trustframework.vc.model.v2310.serialization; public class JacksonModuleFactory { /** * Create a configured Jackson module for serializing organisation verifiable credentials */ public static Module organisationSerializationModule(FormatProvider formatProvider, Supplier<String> baseIriSupplier) { final SimpleModule module = new SimpleModule(); module.addSerializer(Address.class, new JsonLdSerializer<>(Address.class, formatProvider)); module.addSerializer(OrganisationCredentialSubject.class, new JsonLdSerializer<>(OrganisationCredentialSubject.class, formatProvider)); module.addSerializer(JsonLdContexts.class, new JsonLdContextsSerializer(baseIriSupplier));
package com.dawex.sigourney.trustframework.vc.model.v2310.serialization; public class JacksonModuleFactory { /** * Create a configured Jackson module for serializing organisation verifiable credentials */ public static Module organisationSerializationModule(FormatProvider formatProvider, Supplier<String> baseIriSupplier) { final SimpleModule module = new SimpleModule(); module.addSerializer(Address.class, new JsonLdSerializer<>(Address.class, formatProvider)); module.addSerializer(OrganisationCredentialSubject.class, new JsonLdSerializer<>(OrganisationCredentialSubject.class, formatProvider)); module.addSerializer(JsonLdContexts.class, new JsonLdContextsSerializer(baseIriSupplier));
module.addSerializer(OrganisationVerifiableCredential.class, new JsonLdSerializer<>(OrganisationVerifiableCredential.class,
13
2023-10-25 16:10:40+00:00
16k
inceptive-tech/ENTSOEDataRetrieval
src/test/java/tech/inceptive/ai4czc/entsoedataretrieval/fetcher/TestENTSOEDataFetcher.java
[ { "identifier": "DataRetrievalRuntimeException", "path": "src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/exceptions/DataRetrievalRuntimeException.java", "snippet": "public class DataRetrievalRuntimeException extends RuntimeException{\n private static final Logger LOGGER = LogManager.getLogge...
import java.time.LocalDateTime; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import static org.mockito.Mockito.*; import org.mockito.junit.MockitoJUnitRunner; import tech.inceptive.ai4czc.entsoedataretrieval.exceptions.DataRetrievalRuntimeException; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.Area; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.GLMarketDocument; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.PublicationMarketDocument; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.UnavailabilityMarketDocument;
11,583
@Test public void testFetchPhysicalFlowsNonAvailable() { //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2023, 1, 1, 0, 0); when(checker.checkAvailability(eq("12.1.G"), eq(periodStart), any())) .thenAnswer(a -> { LocalDateTime start = LocalDateTime.of(2024, 1, 1, 0, 0); return start; }); //when Optional<PublicationMarketDocument> doc = dataFetcher.fetchPhysicalFlows(Area.MONTENEGRO, Area.BOSNIA, periodStart, periodEnd); //then verify(mockBridge, times(0)).doGetOperation(any(), any(), any()); assertEquals(true, doc.isEmpty()); } @Test public void testFetchPhysicalFlowsPartiallyAvailable() { //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2023, 1, 1, 0, 0); when(checker.checkAvailability(eq("12.1.G"), eq(periodStart), any())) .thenAnswer(a -> { LocalDateTime start = LocalDateTime.of(2022, 6, 1, 0, 0); return start; }); //when Optional<PublicationMarketDocument> doc = dataFetcher.fetchPhysicalFlows(Area.MONTENEGRO, Area.BOSNIA, periodStart, periodEnd); //then Map<String, String> expectedParams = Map.of("securityToken", authToken, "documentType", "A11", "in_Domain", "10YCS-CG-TSO---S", "out_Domain", "10YBA-JPCC-----D", "periodStart", "202206010000", "periodEnd", "202301010000"); verify(mockBridge, times(1)).doGetOperation(eq(expectedParams), eq(ENTSOEDataFetcher.BASE_URL), any()); } @Test public void testFetchPhysicalFlowsOneSidePartiallyAvailable() { // The physical flows are only available on kosovo from 1-6-2022 and it is the out domain. The out domain should // also be consider //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2023, 1, 1, 0, 0); when(checker.checkAvailability(eq("12.1.G"), eq(periodStart), eq(Area.KOSOVO))) .thenAnswer(a -> { LocalDateTime start = LocalDateTime.of(2022, 6, 1, 0, 0); return start; }); when(checker.checkAvailability(eq("12.1.G"), eq(periodStart), eq(Area.MONTENEGRO))) .thenAnswer(a -> { LocalDateTime start = LocalDateTime.of(2017, 1, 1, 0, 0); return start; }); //when Optional<PublicationMarketDocument> doc = dataFetcher.fetchPhysicalFlows(Area.MONTENEGRO, Area.KOSOVO, periodStart, periodEnd); //then Map<String, String> expectedParams = Map.of("securityToken", authToken, "documentType", "A11", "in_Domain", "10YCS-CG-TSO---S", "out_Domain", "10Y1001C--00100H", "periodStart", "202206010000", "periodEnd", "202301010000"); verify(mockBridge, times(1)).doGetOperation(eq(expectedParams), eq(ENTSOEDataFetcher.BASE_URL), any()); } @Test public void testFetchTransmissionGridOutages() { //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2023, 1, 1, 0, 0); Map<String, String> params = Map.of("securityToken", authToken, "documentType", "A78", "in_Domain", "10YCS-CG-TSO---S", "out_Domain", "10YCS-SERBIATSOV", "periodStart", "202201010000", "periodEnd", "202301010000"); List<UnavailabilityMarketDocument> mockDocs = Mockito.mock(List.class); when(mockBridge.doZipGetOperation(eq(params), any(), eq(UnavailabilityMarketDocument.class))).thenReturn(mockDocs); //when List<UnavailabilityMarketDocument> doc = dataFetcher.fetchTransmissionGridOutages(Area.MONTENEGRO, Area.SERBIA, periodStart, periodEnd); //then assertEquals(true, Objects.equals(doc, mockDocs)); verify(mockBridge, times(1)).doZipGetOperation(eq(params), any(), any()); } @Test public void testFetchTransmissionGridOutagesOneYearLimit() { //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2023, 4, 1, 0, 0); //when List<UnavailabilityMarketDocument> res = dataFetcher.fetchTransmissionGridOutages(Area.BOSNIA, Area.MONTENEGRO, periodStart, periodEnd); //then assertEquals(true, res.isEmpty()); verify(mockBridge, times(0)).doZipGetOperation(any(), any(), any()); } @Test public void testFetchTransmissionGridOutagesHandleError() { //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2023, 1, 1, 0, 0);
/* * 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.fetcher; /** * * @author Andres Bel Alonso */ @RunWith(MockitoJUnitRunner.class) public class TestENTSOEDataFetcher { private static final Logger LOGGER = LogManager.getLogger(TestENTSOEDataFetcher.class); private String authToken = "test_auth_token"; @Mock private HttpBridge mockBridge; @Mock private DisponibilityChecker checker; @InjectMocks private ENTSOEDataFetcher dataFetcher = new ENTSOEDataFetcher(authToken, false); @Before public void setUp() { // disponibility checker always available when(checker.checkAvailability(any(), any(), any())).thenAnswer(a -> { LocalDateTime entryDate = a.getArgument(1); return entryDate; }); } // do not think a test is needed @Test public void testFetchActualLoad() { // Verify that the HttpBridge is correctly call during fech load operation //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2023, 1, 1, 0, 0); Map<String, String> parameters = Map.of("securityToken", authToken, "documentType", "A65", "processType", "A16", "outBiddingZone_Domain", "10YCS-CG-TSO---S", "periodStart", "202201010000", "periodEnd", "202301010000"); GLMarketDocument mockDoc = mock(GLMarketDocument.class); when(mockBridge.doGetOperation(eq(parameters), eq(ENTSOEDataFetcher.BASE_URL), any())). thenReturn(mockDoc); //when Optional<GLMarketDocument> doc = dataFetcher.fetchActualLoad(Area.MONTENEGRO, periodStart, periodEnd); //then //verify correct calls verify(mockBridge, times(1)).doGetOperation(eq(parameters), eq(ENTSOEDataFetcher.BASE_URL), any()); //verify correct outputs assertEquals(true, doc.isPresent()); assertEquals(mockDoc, doc.get()); } // @Test public void testFetchActualLoadBigGap() { } // @Test public void testFetchActualLoadSmallGap() { } // @Test public void testFetchActualLoadHandleDataRetrieval() { } @Test public void testFetchActualLoadDataNonAvailable() { //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2023, 1, 1, 0, 0); when(checker.checkAvailability(eq("6.1.A"), eq(periodStart), eq(Area.MONTENEGRO))).thenAnswer(a -> { LocalDateTime start = LocalDateTime.of(2024, 1, 1, 0, 0); return start; }); //when Optional<GLMarketDocument> doc = dataFetcher.fetchActualLoad(Area.MONTENEGRO, periodStart, periodEnd); //then verify(checker, times(1)).checkAvailability(eq("6.1.A"), eq(periodStart), eq(Area.MONTENEGRO)); assertEquals(true, doc.isEmpty()); } @Test public void testFetchActualLoadDataPartiallyAvailable() { // the data is available only from 1st hune 2023, ask only this data //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2023, 1, 1, 0, 0); when(checker.checkAvailability(eq("6.1.A"), eq(periodStart), eq(Area.MONTENEGRO))).thenAnswer(a -> { LocalDateTime start = LocalDateTime.of(2022, 6, 1, 0, 0); return start; }); //when dataFetcher.fetchActualLoad(Area.MONTENEGRO, periodStart, periodEnd); //then Map<String, String> extectedParams = Map.of("securityToken", authToken, "documentType", "A65", "processType", "A16", "outBiddingZone_Domain", "10YCS-CG-TSO---S", "periodStart", "202206010000", "periodEnd", "202301010000"); verify(mockBridge, times(1)).doGetOperation(eq(extectedParams), eq(ENTSOEDataFetcher.BASE_URL), any()); } @Test public void testFetchDayAheadLoadForecast() { //verify the input parameters //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2023, 1, 1, 0, 0); Map<String, String> params = Map.of("securityToken", authToken, "documentType", "A65", "processType", "A01", "outBiddingZone_Domain", "10YCS-CG-TSO---S", "periodStart", "202201010000", "periodEnd", "202301010000"); GLMarketDocument mockDoc = mock(GLMarketDocument.class); when(mockBridge.doGetOperation(eq(params), eq(ENTSOEDataFetcher.BASE_URL), any())). thenReturn(mockDoc); //when Optional<GLMarketDocument> doc = dataFetcher.fetchDayAheadLoadForecast(Area.MONTENEGRO, periodStart, periodEnd); //then //verify correct calls verify(mockBridge, times(1)).doGetOperation(eq(params), eq(ENTSOEDataFetcher.BASE_URL), any()); //verify correct outputs assertEquals(true, doc.isPresent()); assertEquals(mockDoc, doc.get()); } @Test public void testFetchDayAheadLoadForecastOneYearLimit() { //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2023, 2, 1, 0, 0); //when Optional<GLMarketDocument> doc = dataFetcher.fetchDayAheadLoadForecast(Area.MONTENEGRO, periodStart, periodEnd); //then verify(mockBridge, times(0)).doGetOperation(any(), any(), any()); assertEquals(true, doc.isEmpty()); } @Test public void testFetchDayAheadLoadForecastMinimunOneDayInterval() { //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2022, 1, 1, 23, 0); //when Optional<GLMarketDocument> doc = dataFetcher.fetchDayAheadLoadForecast(Area.MONTENEGRO, periodStart, periodEnd); //then verify(mockBridge, times(0)).doGetOperation(any(), any(), any()); assertEquals(true, doc.isEmpty()); } @Test public void testFetchDayAheadLoadForecastDataNonAvailable() { //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2023, 1, 1, 0, 0); when(checker.checkAvailability(eq("6.1.B"), eq(periodStart), eq(Area.MONTENEGRO))) .thenAnswer(a -> { LocalDateTime start = LocalDateTime.of(2024, 1, 1, 0, 0); return start; }); //when Optional<GLMarketDocument> doc = dataFetcher.fetchDayAheadLoadForecast(Area.MONTENEGRO, periodStart, periodEnd); //then verify(checker, times(1)).checkAvailability(eq("6.1.B"), eq(periodStart), eq(Area.MONTENEGRO)); assertEquals(true, doc.isEmpty()); } @Test public void testFetchDayAheadLoadForecastDataPartiallyAvailable() { // the data is available only from 1st hune 2023, ask only this data //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2023, 1, 1, 0, 0); when(checker.checkAvailability(eq("6.1.B"), eq(periodStart), eq(Area.MONTENEGRO))).thenAnswer(a -> { LocalDateTime start = LocalDateTime.of(2022, 6, 1, 0, 0); return start; }); //when dataFetcher.fetchDayAheadLoadForecast(Area.MONTENEGRO, periodStart, periodEnd); //then Map<String, String> extectedParams = Map.of("securityToken", authToken, "documentType", "A65", "processType", "A01", "outBiddingZone_Domain", "10YCS-CG-TSO---S", "periodStart", "202206010000", "periodEnd", "202301010000"); verify(mockBridge, times(1)).doGetOperation(eq(extectedParams), eq(ENTSOEDataFetcher.BASE_URL), any()); } @Test public void testfetchWeekAheadLoadForecast() { //verify the input parameters //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2023, 1, 1, 0, 0); Map<String, String> params = Map.of("securityToken", authToken, "documentType", "A65", "processType", "A31", "outBiddingZone_Domain", "10YCS-CG-TSO---S", "periodStart", "202201010000", "periodEnd", "202301010000"); GLMarketDocument mockDoc = mock(GLMarketDocument.class); when(mockBridge.doGetOperation(eq(params), eq(ENTSOEDataFetcher.BASE_URL), any())). thenReturn(mockDoc); //when Optional<GLMarketDocument> doc = dataFetcher.fetchWeekAheadLoadForecast(Area.MONTENEGRO, periodStart, periodEnd); //then //verify correct calls verify(mockBridge, times(1)).doGetOperation(eq(params), eq(ENTSOEDataFetcher.BASE_URL), any()); //verify correct outputs assertEquals(true, doc.isPresent()); assertEquals(mockDoc, doc.get()); } @Test public void testFechWeekAheadLoadForecastOneYearLimit() { //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2023, 2, 1, 0, 0); //when Optional<GLMarketDocument> doc = dataFetcher.fetchWeekAheadLoadForecast(Area.MONTENEGRO, periodStart, periodEnd); //then verify(mockBridge, times(0)).doGetOperation(any(), any(), any()); assertEquals(true, doc.isEmpty()); } @Test public void testFechWeekAheadLoadForecastMinimunOneWeek() { //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2022, 1, 3, 0, 0); //when Optional<GLMarketDocument> doc = dataFetcher.fetchWeekAheadLoadForecast(Area.MONTENEGRO, periodStart, periodEnd); //then verify(mockBridge, times(0)).doGetOperation(any(), any(), any()); assertEquals(true, doc.isEmpty()); } @Test public void testFechWeekAheadLoadForecastDataNonAvailable() { //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2023, 1, 1, 0, 0); when(checker.checkAvailability(eq("6.1.C"), eq(periodStart), eq(Area.MONTENEGRO))) .thenAnswer(a -> { LocalDateTime start = LocalDateTime.of(2024, 1, 1, 0, 0); return start; }); //when Optional<GLMarketDocument> doc = dataFetcher.fetchWeekAheadLoadForecast(Area.MONTENEGRO, periodStart, periodEnd); //then verify(checker, times(1)).checkAvailability(eq("6.1.C"), eq(periodStart), eq(Area.MONTENEGRO)); assertEquals(true, doc.isEmpty()); } @Test public void testFechWeekAheadLoadForecastDataPartiallyAvailable() { // the data is available only from 1st hune 2023, ask only this data //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2023, 1, 1, 0, 0); when(checker.checkAvailability(eq("6.1.C"), eq(periodStart), eq(Area.MONTENEGRO))).thenAnswer(a -> { LocalDateTime start = LocalDateTime.of(2022, 6, 1, 0, 0); return start; }); //when dataFetcher.fetchWeekAheadLoadForecast(Area.MONTENEGRO, periodStart, periodEnd); //then Map<String, String> extectedParams = Map.of("securityToken", authToken, "documentType", "A65", "processType", "A31", "outBiddingZone_Domain", "10YCS-CG-TSO---S", "periodStart", "202206010000", "periodEnd", "202301010000"); verify(mockBridge, times(1)).doGetOperation(eq(extectedParams), eq(ENTSOEDataFetcher.BASE_URL), any()); } @Test public void testFetchAggregatedGenerationType() { //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2023, 1, 1, 0, 0); Map<String, String> params = Map.of("securityToken", authToken, "documentType", "A75", "processType", "A16", "in_Domain", "10YCS-SERBIATSOV", "periodStart", "202201010000", "periodEnd", "202301010000"); GLMarketDocument mockDoc = mock(GLMarketDocument.class); when(mockBridge.doGetOperation(eq(params), eq(ENTSOEDataFetcher.BASE_URL), any())). thenReturn(mockDoc); //when Optional<GLMarketDocument> doc = dataFetcher.fetchAggregatedGenerationType(Area.SERBIA, periodStart, periodEnd); //then verify(mockBridge, times(1)).doGetOperation(eq(params), eq(ENTSOEDataFetcher.BASE_URL), any()); //verify correct outputs assertEquals(true, doc.isPresent()); assertEquals(mockDoc, doc.get()); } @Test public void testFetchAggregatedGenerationTypeOneYearLimit() { //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2023, 2, 1, 0, 0); //when Optional<GLMarketDocument> doc = dataFetcher.fetchAggregatedGenerationType(Area.MONTENEGRO, periodStart, periodEnd); //then verify(mockBridge, times(0)).doGetOperation(any(), any(), any()); assertEquals(true, doc.isEmpty()); } @Test public void testFetchAggregatedGenerationTypeMinimal24hLimit() { //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2022, 1, 1, 12, 0); //when Optional<GLMarketDocument> doc = dataFetcher.fetchAggregatedGenerationType(Area.MONTENEGRO, periodStart, periodEnd); //then verify(mockBridge, times(0)).doGetOperation(any(), any(), any()); assertEquals(true, doc.isEmpty()); } @Test public void testFetchAggregatedGenerationTypeDataNonAvailable() { //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2023, 1, 1, 0, 0); when(checker.checkAvailability(eq("16.1.B&C"), eq(periodStart), eq(Area.MONTENEGRO))) .thenAnswer(a -> { LocalDateTime start = LocalDateTime.of(2024, 1, 1, 0, 0); return start; }); //when Optional<GLMarketDocument> doc = dataFetcher.fetchAggregatedGenerationType(Area.MONTENEGRO, periodStart, periodEnd); //then verify(mockBridge, times(0)).doGetOperation(any(), any(), any()); assertEquals(true, doc.isEmpty()); } @Test public void testFetchAggregatedGenerationTypeDataPartiallyAvailable() { //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2023, 1, 1, 0, 0); when(checker.checkAvailability(eq("16.1.B&C"), eq(periodStart), eq(Area.MONTENEGRO))) .thenAnswer(a -> { LocalDateTime start = LocalDateTime.of(2022, 6, 1, 0, 0); return start; }); //when Optional<GLMarketDocument> doc = dataFetcher.fetchAggregatedGenerationType(Area.MONTENEGRO, periodStart, periodEnd); //then Map<String, String> expectedParams = Map.of("securityToken", authToken, "documentType", "A75", "processType", "A16", "in_Domain", "10YCS-CG-TSO---S", "periodStart", "202206010000", "periodEnd", "202301010000"); verify(mockBridge, times(1)).doGetOperation(eq(expectedParams), eq(ENTSOEDataFetcher.BASE_URL), any()); } @Test public void testFetchPhysicalFlows() { //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2023, 1, 1, 0, 0); Map<String, String> params = Map.of("securityToken", authToken, "documentType", "A11", "in_Domain", "10YCS-CG-TSO---S", "out_Domain", "10YBA-JPCC-----D", "periodStart", "202201010000", "periodEnd", "202301010000"); PublicationMarketDocument mockDoc = mock(PublicationMarketDocument.class); when(mockBridge.doGetOperation(eq(params), eq(ENTSOEDataFetcher.BASE_URL), any())). thenReturn(mockDoc); //when Optional<PublicationMarketDocument> doc = dataFetcher.fetchPhysicalFlows(Area.MONTENEGRO, Area.BOSNIA, periodStart, periodEnd); //then verify(mockBridge, times(1)).doGetOperation(eq(params), eq(ENTSOEDataFetcher.BASE_URL), any()); //verify correct outputs assertEquals(true, doc.isPresent()); assertEquals(mockDoc, doc.get()); } @Test public void testFetchPhysicalFlowsOneYearLimit() { //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2023, 2, 1, 0, 0); //when Optional<PublicationMarketDocument> doc = dataFetcher.fetchPhysicalFlows(Area.MONTENEGRO, Area.BOSNIA, periodStart, periodEnd); //then verify(mockBridge, times(0)).doGetOperation(any(), any(), any()); assertEquals(true, doc.isEmpty()); } @Test public void testFetchPhysicalFlowsOneHourMinimun() { //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 14, 15, 0); LocalDateTime periodEnd = LocalDateTime.of(2022, 1, 14, 15, 45); //when Optional<PublicationMarketDocument> doc = dataFetcher.fetchPhysicalFlows(Area.MONTENEGRO, Area.BOSNIA, periodStart, periodEnd); //then verify(mockBridge, times(0)).doGetOperation(any(), any(), any()); assertEquals(true, doc.isEmpty()); } @Test public void testFetchPhysicalFlowsNonAvailable() { //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2023, 1, 1, 0, 0); when(checker.checkAvailability(eq("12.1.G"), eq(periodStart), any())) .thenAnswer(a -> { LocalDateTime start = LocalDateTime.of(2024, 1, 1, 0, 0); return start; }); //when Optional<PublicationMarketDocument> doc = dataFetcher.fetchPhysicalFlows(Area.MONTENEGRO, Area.BOSNIA, periodStart, periodEnd); //then verify(mockBridge, times(0)).doGetOperation(any(), any(), any()); assertEquals(true, doc.isEmpty()); } @Test public void testFetchPhysicalFlowsPartiallyAvailable() { //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2023, 1, 1, 0, 0); when(checker.checkAvailability(eq("12.1.G"), eq(periodStart), any())) .thenAnswer(a -> { LocalDateTime start = LocalDateTime.of(2022, 6, 1, 0, 0); return start; }); //when Optional<PublicationMarketDocument> doc = dataFetcher.fetchPhysicalFlows(Area.MONTENEGRO, Area.BOSNIA, periodStart, periodEnd); //then Map<String, String> expectedParams = Map.of("securityToken", authToken, "documentType", "A11", "in_Domain", "10YCS-CG-TSO---S", "out_Domain", "10YBA-JPCC-----D", "periodStart", "202206010000", "periodEnd", "202301010000"); verify(mockBridge, times(1)).doGetOperation(eq(expectedParams), eq(ENTSOEDataFetcher.BASE_URL), any()); } @Test public void testFetchPhysicalFlowsOneSidePartiallyAvailable() { // The physical flows are only available on kosovo from 1-6-2022 and it is the out domain. The out domain should // also be consider //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2023, 1, 1, 0, 0); when(checker.checkAvailability(eq("12.1.G"), eq(periodStart), eq(Area.KOSOVO))) .thenAnswer(a -> { LocalDateTime start = LocalDateTime.of(2022, 6, 1, 0, 0); return start; }); when(checker.checkAvailability(eq("12.1.G"), eq(periodStart), eq(Area.MONTENEGRO))) .thenAnswer(a -> { LocalDateTime start = LocalDateTime.of(2017, 1, 1, 0, 0); return start; }); //when Optional<PublicationMarketDocument> doc = dataFetcher.fetchPhysicalFlows(Area.MONTENEGRO, Area.KOSOVO, periodStart, periodEnd); //then Map<String, String> expectedParams = Map.of("securityToken", authToken, "documentType", "A11", "in_Domain", "10YCS-CG-TSO---S", "out_Domain", "10Y1001C--00100H", "periodStart", "202206010000", "periodEnd", "202301010000"); verify(mockBridge, times(1)).doGetOperation(eq(expectedParams), eq(ENTSOEDataFetcher.BASE_URL), any()); } @Test public void testFetchTransmissionGridOutages() { //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2023, 1, 1, 0, 0); Map<String, String> params = Map.of("securityToken", authToken, "documentType", "A78", "in_Domain", "10YCS-CG-TSO---S", "out_Domain", "10YCS-SERBIATSOV", "periodStart", "202201010000", "periodEnd", "202301010000"); List<UnavailabilityMarketDocument> mockDocs = Mockito.mock(List.class); when(mockBridge.doZipGetOperation(eq(params), any(), eq(UnavailabilityMarketDocument.class))).thenReturn(mockDocs); //when List<UnavailabilityMarketDocument> doc = dataFetcher.fetchTransmissionGridOutages(Area.MONTENEGRO, Area.SERBIA, periodStart, periodEnd); //then assertEquals(true, Objects.equals(doc, mockDocs)); verify(mockBridge, times(1)).doZipGetOperation(eq(params), any(), any()); } @Test public void testFetchTransmissionGridOutagesOneYearLimit() { //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2023, 4, 1, 0, 0); //when List<UnavailabilityMarketDocument> res = dataFetcher.fetchTransmissionGridOutages(Area.BOSNIA, Area.MONTENEGRO, periodStart, periodEnd); //then assertEquals(true, res.isEmpty()); verify(mockBridge, times(0)).doZipGetOperation(any(), any(), any()); } @Test public void testFetchTransmissionGridOutagesHandleError() { //given LocalDateTime periodStart = LocalDateTime.of(2022, 1, 1, 0, 0); LocalDateTime periodEnd = LocalDateTime.of(2023, 1, 1, 0, 0);
when(mockBridge.doZipGetOperation(any(), any(), any())).thenThrow(DataRetrievalRuntimeException.class);
0
2023-10-30 09:09:53+00:00
16k
EricFan2002/SC2002
src/app/ui/camp/suggestionview/OverlayCampSuggestionCommitteeView.java
[ { "identifier": "RepositoryCollection", "path": "src/app/entity/RepositoryCollection.java", "snippet": "public class RepositoryCollection {\n\n /**\n * The repository for user objects.\n */\n private static UserList userRepository;\n\n /**\n * The repository for camp objects.\n ...
import app.entity.RepositoryCollection; import app.entity.camp.Camp; import app.entity.suggestion.Suggestion; import app.entity.suggestion.SuggestionList; import app.entity.suggestion.SuggestionStatus; import app.entity.user.Student; import app.ui.overlayactions.OverlayChooseBox; import app.ui.widgets.*; import app.ui.windows.ICallBack; import app.ui.windows.Window; import app.ui.windows.WindowOverlayClass; import java.util.ArrayList;
11,936
package app.ui.camp.suggestionview; /** * Represents an overlay view displaying camp suggestions for the committee. * Extends the WindowOverlayClass and implements ICallBack interface. */ public class OverlayCampSuggestionCommitteeView extends WindowOverlayClass implements ICallBack { Camp camp; Student student; protected WidgetPageSelection allSuggestions; protected WidgetButton exitButton; protected WidgetButton createSuggestionButton; protected Window mainWindow;
package app.ui.camp.suggestionview; /** * Represents an overlay view displaying camp suggestions for the committee. * Extends the WindowOverlayClass and implements ICallBack interface. */ public class OverlayCampSuggestionCommitteeView extends WindowOverlayClass implements ICallBack { Camp camp; Student student; protected WidgetPageSelection allSuggestions; protected WidgetButton exitButton; protected WidgetButton createSuggestionButton; protected Window mainWindow;
protected ArrayList<Suggestion> suggestionArrayList;
2
2023-11-01 05:18:29+00:00
16k
TNO/PPS
plugins/nl.esi.pps.tmsc.analysis.prototypes.ui/src/nl/esi/pps/tmsc/analysis/prototypes/ui/handlers/ActivitySeparationHandler.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.prototypes.ui.Activator.getPluginID; import static org.eclipse.core.runtime.IStatus.ERROR; 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 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 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 nl.esi.pps.common.ide.ui.jobs.StatusReportingJob; import org.eclipse.lsat.common.queries.QueryableIterable; import nl.esi.pps.preferences.PPSPreferences; import nl.esi.pps.tmsc.FullScopeTMSC; import nl.esi.pps.tmsc.TmscPlugin; import nl.esi.pps.tmsc.analysis.prototypes.ActivitySeparation; import nl.esi.pps.tmsc.rendering.RenderingProperties; import nl.esi.pps.tmsc.rendering.plot.ScopesRenderingStrategy;
12,656
/* * 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.prototypes.ui.handlers; public class ActivitySeparationHandler { @Evaluate @CanExecute public boolean canExecute(@Named(IServiceConstants.ACTIVE_SELECTION) @Optional IStructuredSelection selection) { if (!PPSPreferences.isAdvancedFeaturesEnabled() || selection == null || selection.size() != 1) { return false; } Object selectedElement = selection.getFirstElement(); return selectedElement instanceof IFile && TmscPlugin.isTmscFile((IFile) selectedElement); } @Execute public void execute(@Named(IServiceConstants.ACTIVE_SELECTION) IStructuredSelection selection) { IFile modelIFile = (IFile) selection.getFirstElement(); IStatusJobFunction jobFunction = monitor -> doJob(modelIFile, monitor); String jobName = "Activity separation"; Job job = new StatusReportingJob(jobName, jobFunction, getPluginID(), DEFAULT_LOG_SEVERITIES, DEFAULT_LOG_SEVERITIES); job.setUser(true); job.schedule(); } public static IStatus doJob(IFile modelIFile, IProgressMonitor monitor) throws ErrorStatusException { SubMonitor subMonitor = SubMonitor.convert(monitor, 101); subMonitor.setTaskName("Activity separation.");
/* * 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.prototypes.ui.handlers; public class ActivitySeparationHandler { @Evaluate @CanExecute public boolean canExecute(@Named(IServiceConstants.ACTIVE_SELECTION) @Optional IStructuredSelection selection) { if (!PPSPreferences.isAdvancedFeaturesEnabled() || selection == null || selection.size() != 1) { return false; } Object selectedElement = selection.getFirstElement(); return selectedElement instanceof IFile && TmscPlugin.isTmscFile((IFile) selectedElement); } @Execute public void execute(@Named(IServiceConstants.ACTIVE_SELECTION) IStructuredSelection selection) { IFile modelIFile = (IFile) selection.getFirstElement(); IStatusJobFunction jobFunction = monitor -> doJob(modelIFile, monitor); String jobName = "Activity separation"; Job job = new StatusReportingJob(jobName, jobFunction, getPluginID(), DEFAULT_LOG_SEVERITIES, DEFAULT_LOG_SEVERITIES); job.setUser(true); job.schedule(); } public static IStatus doJob(IFile modelIFile, IProgressMonitor monitor) throws ErrorStatusException { SubMonitor subMonitor = SubMonitor.convert(monitor, 101); subMonitor.setTaskName("Activity separation.");
FailOnErrorStatus result = new FailOnErrorStatus(getPluginID(), "Activity separation");
3
2023-10-30 16:00:25+00:00
16k
CERBON-MODS/Bosses-of-Mass-Destruction-FORGE
src/main/java/com/cerbon/bosses_of_mass_destruction/BossesOfMassDestruction.java
[ { "identifier": "BMDBlockEntities", "path": "src/main/java/com/cerbon/bosses_of_mass_destruction/block/BMDBlockEntities.java", "snippet": "public class BMDBlockEntities {\n public static final DeferredRegister<BlockEntityType<?>> BLOCKS_ENTITIES =\n DeferredRegister.create(ForgeRegistries....
import com.cerbon.bosses_of_mass_destruction.block.BMDBlockEntities; import com.cerbon.bosses_of_mass_destruction.block.BMDBlocks; import com.cerbon.bosses_of_mass_destruction.config.BMDConfig; import com.cerbon.bosses_of_mass_destruction.entity.BMDEntities; import com.cerbon.bosses_of_mass_destruction.item.BMDCreativeModeTabs; import com.cerbon.bosses_of_mass_destruction.item.BMDItems; import com.cerbon.bosses_of_mass_destruction.particle.BMDParticles; import com.cerbon.bosses_of_mass_destruction.sound.BMDSounds; import com.cerbon.bosses_of_mass_destruction.util.BMDConstants; import com.cerbon.bosses_of_mass_destruction.structure.BMDStructures; import com.mojang.logging.LogUtils; import me.shedaniel.autoconfig.AutoConfig; import me.shedaniel.autoconfig.serializer.JanksonConfigSerializer; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import org.slf4j.Logger;
13,931
package com.cerbon.bosses_of_mass_destruction; @Mod(BMDConstants.MOD_ID) public class BossesOfMassDestruction { public static final Logger LOGGER = LogUtils.getLogger(); public BossesOfMassDestruction() { AutoConfig.register(BMDConfig.class, JanksonConfigSerializer::new); AutoConfig.getConfigHolder(BMDConfig.class).getConfig().postInit(); AutoConfig.getConfigHolder(BMDConfig.class).save(); IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus(); BMDCreativeModeTabs.register(modEventBus); BMDBlocks.register(modEventBus); BMDItems.register(modEventBus);
package com.cerbon.bosses_of_mass_destruction; @Mod(BMDConstants.MOD_ID) public class BossesOfMassDestruction { public static final Logger LOGGER = LogUtils.getLogger(); public BossesOfMassDestruction() { AutoConfig.register(BMDConfig.class, JanksonConfigSerializer::new); AutoConfig.getConfigHolder(BMDConfig.class).getConfig().postInit(); AutoConfig.getConfigHolder(BMDConfig.class).save(); IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus(); BMDCreativeModeTabs.register(modEventBus); BMDBlocks.register(modEventBus); BMDItems.register(modEventBus);
BMDEntities.register(modEventBus);
3
2023-10-25 16:28:17+00:00
16k
SmartGecko44/Spigot-Admin-Toys
src/main/java/org/gecko/wauh/logic/Scale.java
[ { "identifier": "Main", "path": "src/main/java/org/gecko/wauh/Main.java", "snippet": "public final class Main extends JavaPlugin {\n\n ConfigurationManager configManager;\n FileConfiguration config;\n private int playerRadiusLimit;\n private int tntRadiusLimit;\n private int creeperRadius...
import org.bukkit.block.Block; import org.gecko.wauh.Main; import org.gecko.wauh.listeners.BarrierListener; import org.gecko.wauh.listeners.BedrockListener; import org.gecko.wauh.listeners.BucketListener; import org.gecko.wauh.listeners.WaterBucketListener; import java.util.*;
13,856
package org.gecko.wauh.logic; public class Scale { public void ScaleReverseLogic(int totalRemovedCount, int radiusLimit, Set<Block> markedBlocks, String source) {
package org.gecko.wauh.logic; public class Scale { public void ScaleReverseLogic(int totalRemovedCount, int radiusLimit, Set<Block> markedBlocks, String source) {
Main mainPlugin = Main.getPlugin(Main.class);
0
2023-10-28 11:26:45+00:00
16k
sinch/sinch-sdk-java
client/src/test/java/com/sinch/sdk/domains/verification/adapters/converters/VerificationsDtoConverterTest.java
[ { "identifier": "BaseTest", "path": "test-resources/src/test/java/com/sinch/sdk/BaseTest.java", "snippet": "@ExtendWith(MockitoExtension.class)\npublic class BaseTest {\n\n @WithJacksonMapper protected ObjectMapper objectMapper = Mapper.getInstance();\n\n @BeforeEach\n void init_mocks() {\n Mockit...
import com.sinch.sdk.BaseTest; import com.sinch.sdk.domains.verification.models.NumberIdentity; import com.sinch.sdk.domains.verification.models.Price; import com.sinch.sdk.domains.verification.models.VerificationId; import com.sinch.sdk.domains.verification.models.VerificationMethodType; import com.sinch.sdk.domains.verification.models.VerificationReference; import com.sinch.sdk.domains.verification.models.VerificationReportCallout; import com.sinch.sdk.domains.verification.models.VerificationReportFlashCall; import com.sinch.sdk.domains.verification.models.VerificationReportReasonType; import com.sinch.sdk.domains.verification.models.VerificationReportSMS; import com.sinch.sdk.domains.verification.models.VerificationReportStatusType; import com.sinch.sdk.domains.verification.models.VerificationSourceType; import com.sinch.sdk.domains.verification.models.dto.v1.StartVerificationRequestDtoTest; import com.sinch.sdk.domains.verification.models.dto.v1.StartVerificationResponseDtoTest; import com.sinch.sdk.domains.verification.models.dto.v1.VerificationReportDtoTest; import com.sinch.sdk.domains.verification.models.dto.v1.VerificationReportRequestDtoTest; import com.sinch.sdk.domains.verification.models.requests.StartVerificationFlashCallRequestParameters; import com.sinch.sdk.domains.verification.models.requests.StartVerificationRequestParameters; import com.sinch.sdk.domains.verification.models.requests.VerificationReportCalloutRequestParameters; import com.sinch.sdk.domains.verification.models.requests.VerificationReportFlashCallRequestParameters; import com.sinch.sdk.domains.verification.models.requests.VerificationReportSMSRequestParameters; import com.sinch.sdk.domains.verification.models.response.StartVerificationResponseCallout; import com.sinch.sdk.domains.verification.models.response.StartVerificationResponseFlashCall; import com.sinch.sdk.domains.verification.models.response.StartVerificationResponseSMS; import com.sinch.sdk.domains.verification.models.response.StartVerificationResponseSeamless; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test;
12,768
package com.sinch.sdk.domains.verification.adapters.converters; public class VerificationsDtoConverterTest extends BaseTest { public static StartVerificationRequestParameters startVerificationCalloutRequest =
package com.sinch.sdk.domains.verification.adapters.converters; public class VerificationsDtoConverterTest extends BaseTest { public static StartVerificationRequestParameters startVerificationCalloutRequest =
StartVerificationRequestParameters.builder(VerificationMethodType.CALLOUT)
4
2023-10-31 08:32:59+00:00
16k
SpCoGov/SpCoBot
src/main/java/top/spco/service/command/commands/DashscopeCommand.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 java.util.List; import com.alibaba.dashscope.exception.ApiException; import com.alibaba.dashscope.utils.Constants; import top.spco.SpCoBot; import top.spco.api.Bot; import top.spco.api.Interactive; import top.spco.api.User; import top.spco.api.message.Message; import top.spco.core.config.DashScopeSettings; import top.spco.service.command.AbstractCommand; import top.spco.service.command.CommandMeta; import top.spco.service.command.CommandParam; import top.spco.service.command.CommandUsage; import top.spco.service.dashscope.DashScope; import top.spco.user.BotUser;
10,820
/* * 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; /** * @author SpCo * @version 1.0.0 * @since 0.2.1 */ public class DashscopeCommand extends AbstractCommand { @Override public String[] getLabels() { return new String[]{"dashscope"}; } @Override public String getDescriptions() { return "调用一次DashScope模型"; } @Override public List<CommandUsage> getUsages() { return List.of(new CommandUsage(getLabels()[0], getDescriptions(), new CommandParam("内容", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT))); } @Override public void init() { Constants.apiKey = SpCoBot.getInstance().getSettings().getProperty(DashScopeSettings.API_KET).toString(); } @Override
/* * 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; /** * @author SpCo * @version 1.0.0 * @since 0.2.1 */ public class DashscopeCommand extends AbstractCommand { @Override public String[] getLabels() { return new String[]{"dashscope"}; } @Override public String getDescriptions() { return "调用一次DashScope模型"; } @Override public List<CommandUsage> getUsages() { return List.of(new CommandUsage(getLabels()[0], getDescriptions(), new CommandParam("内容", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT))); } @Override public void init() { Constants.apiKey = SpCoBot.getInstance().getSettings().getProperty(DashScopeSettings.API_KET).toString(); } @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) {
7
2023-10-26 10:27:47+00:00
16k
zxzf1234/jimmer-ruoyivuepro
backend/yudao-service/yudao-service-biz/src/main/java/cn/iocoder/yudao/service/service/infra/codegen/inner/CodegenEngine.java
[ { "identifier": "ServiceExceptionUtil", "path": "backend/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/exception/util/ServiceExceptionUtil.java", "snippet": "@Slf4j\npublic class ServiceExceptionUtil {\n\n /**\n * 错误码提示模板\n */\n private static final Concurren...
import cn.hutool.core.convert.Convert; import cn.hutool.core.date.DateUtil; import cn.hutool.core.io.FileUtil; import cn.hutool.core.map.MapUtil; import cn.hutool.core.util.RuntimeUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.extra.template.TemplateConfig; import cn.hutool.extra.template.TemplateEngine; import cn.hutool.extra.template.engine.velocity.VelocityEngine; import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil; import cn.iocoder.yudao.framework.common.pojo.CommonResult; import cn.iocoder.yudao.framework.common.pojo.PageParam; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.util.date.DateUtils; import cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils; import cn.iocoder.yudao.framework.common.util.object.ObjectUtils; import cn.iocoder.yudao.framework.excel.core.annotations.DictFormat; import cn.iocoder.yudao.framework.excel.core.convert.DictConvert; import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils; import cn.iocoder.yudao.framework.mybatis.core.dataobject.BaseDO; import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX; import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX; import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog; import cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum; import cn.iocoder.yudao.service.convert.infra.codegen.CodegenConvert; import cn.iocoder.yudao.service.enums.codegen.CodegenSceneEnum; import cn.iocoder.yudao.service.framework.codegen.config.CodegenProperties; import cn.iocoder.yudao.service.framework.codegen.config.SchemaHistory; import cn.iocoder.yudao.service.model.infra.codegen.*; import cn.iocoder.yudao.service.repository.infra.codegen.*; import cn.iocoder.yudao.service.vo.infra.codegen.database.DatabaseUpdateReq; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.RequestParam; import javax.annotation.PostConstruct; import javax.annotation.Resource; import java.io.File; import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.util.*; import static cn.hutool.core.map.MapUtil.getStr; import static cn.hutool.core.text.CharSequenceUtil.*;
12,189
package cn.iocoder.yudao.service.service.infra.codegen.inner; /** * 代码生成的引擎,用于具体生成代码 * 目前基于 {@link org.apache.velocity.app.Velocity} 模板引擎实现 * * 考虑到 Java 模板引擎的框架非常多,Freemarker、Velocity、Thymeleaf 等等,所以我们采用 hutool 封装的 {@link cn.hutool.extra.template.Template} 抽象 * * @author 芋道源码 */ @Component public class CodegenEngine { /** * 后端的模板配置 * * key:模板在 resources 的地址 * value:生成的路径 */ private static final Map<String, String> TABLE_INSERT_TEMPLATES = MapUtil.<String, String>builder(new LinkedHashMap<>()) // 有序 // Java module-biz Main .put(javaTemplatePath("vo/baseVO"), javaBaseVOFilePath("Base")) .put(javaTemplatePath("repository/repository"), javaTableFilePath("repository","${classNameHump}Repository")) .put(javaTemplatePath("model/model"), javaTableFilePath("model","${classNameHump}")) .build(); private static final Map<String, String> TABLE_UPDATE_TEMPLATES = MapUtil.<String, String>builder(new LinkedHashMap<>()) // 有序 // Java module-biz Main .put(javaTemplatePath("vo/baseVO"), javaBaseVOFilePath("Base")) .put(javaTemplatePath("model/model"), javaTableFilePath("model","${classNameHump}")) .build(); private static final Map<String, String> MODULE_TEMPLATES = MapUtil.<String, String>builder(new LinkedHashMap<>()) // 有序 .put(javaTemplatePath("controller/controller"), javaControllerFilePath()) .put(javaTemplatePath("convert/convert"), javaModuleFilePath("convert", "${nameHumpUp}Convert")) .put(javaTemplatePath("service/serviceImpl"), javaModuleFilePath("service", "${nameHumpUp}ServiceImpl")) .put(javaTemplatePath("service/service"), javaModuleFilePath("service", "${nameHumpUp}Service")) .build(); private static final Map<String, String> INTERFACE_TEMPLATES = MapUtil.<String, String>builder(new LinkedHashMap<>()) // 有序 .put(javaTemplatePath("controller/controllerInterface"), javaFilePath("controller/${sceneEnum.basePackage}/${modulePath}/${moduleNameHump}Controller")+ ".java") .put(javaTemplatePath("convert/convertInterface"), javaModuleFilePath("convert", "${moduleNameHump}Convert")) .put(javaTemplatePath("service/serviceImplInterface"), javaModuleFilePath("service", "${moduleNameHump}ServiceImpl")) .put(javaTemplatePath("service/serviceInterface"), javaModuleFilePath("service", "${moduleNameHump}Service")) .put(javaTemplatePath("vo/VOInput"), javaModuleFilePath("vo", "${moduleNameHump}/${moduleNameHumpUp}${interfaceNameHumpUp}Input")) .put(javaTemplatePath("vo/VOOutput"), javaModuleFilePath("vo", "${moduleNameHump}/${moduleNameHumpUp}${interfaceNameHumpUp}Output")) .build(); /* private static final Table<Integer, String, String> FRONT_TEMPLATES = ImmutableTable.<Integer, String, String>builder() // Vue2 标准模版 .put(CodegenFrontTypeEnum.VUE2.getType(), vueTemplatePath("views/index.vue"), vueFilePath("views/${table.moduleName}/${classNameVar}/index.vue")) .put(CodegenFrontTypeEnum.VUE2.getType(), vueTemplatePath("api/api.js"), vueFilePath("api/${table.moduleName}/${classNameVar}.js")) // Vue3 标准模版 .put(CodegenFrontTypeEnum.VUE3.getType(), vue3TemplatePath("views/index.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/index.vue")) .put(CodegenFrontTypeEnum.VUE3.getType(), vue3TemplatePath("views/form.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${simpleClassName}Form.vue")) .put(CodegenFrontTypeEnum.VUE3.getType(), vue3TemplatePath("api/api.ts"), vue3FilePath("api/${table.moduleName}/${classNameVar}/index.ts")) // Vue3 Schema 模版 .put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath("views/data.ts"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${classNameVar}.data.ts")) .put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath("views/index.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/index.vue")) .put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath("views/form.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${simpleClassName}Form.vue")) .put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath("api/api.ts"), vue3FilePath("api/${table.moduleName}/${classNameVar}/index.ts")) // Vue3 vben 模版 .put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath("views/data.ts"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${classNameVar}.data.ts")) .put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath("views/index.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/index.vue")) .put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath("views/form.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${simpleClassName}Modal.vue")) .put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath("api/api.ts"), vue3FilePath("api/${table.moduleName}/${classNameVar}/index.ts")) .build();*/ @Resource private CodegenProperties codegenProperties; @Resource private InfraDatabaseTableRepository infraDatabaseTableRepository; @Resource private InfraInterfaceModuleRepository infraInterfaceModuleRepository; @Resource private InfraInterfaceRepository infraInterfaceRepository; @Resource private InfraInterfaceVoClassRepository infraInterfaceVoClassRepository; @Resource private InfraInterfaceSubclassRepository infraInterfaceSubclassRepository; @Resource private SchemaHistory schemaHistory; /** * 模板引擎,由 hutool 实现 */ private final TemplateEngine templateEngine; /** * 全局通用变量映射 */ private final Map<String, Object> globalBindingMap = new HashMap<>(); public CodegenEngine() { // 初始化 TemplateEngine 属性 TemplateConfig config = new TemplateConfig(); config.setResourceMode(TemplateConfig.ResourceMode.CLASSPATH); this.templateEngine = new VelocityEngine(config); } @PostConstruct private void initGlobalBindingMap() { // 全局配置 globalBindingMap.put("basePackage", codegenProperties.getBasePackage()); globalBindingMap.put("baseFrameworkPackage", codegenProperties.getBasePackage() + '.' + "framework"); // 用于后续获取测试类的 package 地址 // 全局 Java Bean globalBindingMap.put("CommonResultClassName", CommonResult.class.getName()); globalBindingMap.put("PageResultClassName", PageResult.class.getName()); // VO 类,独有字段 globalBindingMap.put("PageParamClassName", PageParam.class.getName()); globalBindingMap.put("DictFormatClassName", DictFormat.class.getName()); // DO 类,独有字段 globalBindingMap.put("BaseDOClassName", BaseDO.class.getName()); globalBindingMap.put("QueryWrapperClassName", LambdaQueryWrapperX.class.getName()); globalBindingMap.put("BaseMapperClassName", BaseMapperX.class.getName()); // Util 工具类 globalBindingMap.put("ServiceExceptionUtilClassName", ServiceExceptionUtil.class.getName()); globalBindingMap.put("DateUtilsClassName", DateUtils.class.getName()); globalBindingMap.put("ExcelUtilsClassName", ExcelUtils.class.getName()); globalBindingMap.put("LocalDateTimeUtilsClassName", LocalDateTimeUtils.class.getName()); globalBindingMap.put("ObjectUtilsClassName", ObjectUtils.class.getName()); globalBindingMap.put("DictConvertClassName", DictConvert.class.getName()); globalBindingMap.put("OperateLogClassName", OperateLog.class.getName());
package cn.iocoder.yudao.service.service.infra.codegen.inner; /** * 代码生成的引擎,用于具体生成代码 * 目前基于 {@link org.apache.velocity.app.Velocity} 模板引擎实现 * * 考虑到 Java 模板引擎的框架非常多,Freemarker、Velocity、Thymeleaf 等等,所以我们采用 hutool 封装的 {@link cn.hutool.extra.template.Template} 抽象 * * @author 芋道源码 */ @Component public class CodegenEngine { /** * 后端的模板配置 * * key:模板在 resources 的地址 * value:生成的路径 */ private static final Map<String, String> TABLE_INSERT_TEMPLATES = MapUtil.<String, String>builder(new LinkedHashMap<>()) // 有序 // Java module-biz Main .put(javaTemplatePath("vo/baseVO"), javaBaseVOFilePath("Base")) .put(javaTemplatePath("repository/repository"), javaTableFilePath("repository","${classNameHump}Repository")) .put(javaTemplatePath("model/model"), javaTableFilePath("model","${classNameHump}")) .build(); private static final Map<String, String> TABLE_UPDATE_TEMPLATES = MapUtil.<String, String>builder(new LinkedHashMap<>()) // 有序 // Java module-biz Main .put(javaTemplatePath("vo/baseVO"), javaBaseVOFilePath("Base")) .put(javaTemplatePath("model/model"), javaTableFilePath("model","${classNameHump}")) .build(); private static final Map<String, String> MODULE_TEMPLATES = MapUtil.<String, String>builder(new LinkedHashMap<>()) // 有序 .put(javaTemplatePath("controller/controller"), javaControllerFilePath()) .put(javaTemplatePath("convert/convert"), javaModuleFilePath("convert", "${nameHumpUp}Convert")) .put(javaTemplatePath("service/serviceImpl"), javaModuleFilePath("service", "${nameHumpUp}ServiceImpl")) .put(javaTemplatePath("service/service"), javaModuleFilePath("service", "${nameHumpUp}Service")) .build(); private static final Map<String, String> INTERFACE_TEMPLATES = MapUtil.<String, String>builder(new LinkedHashMap<>()) // 有序 .put(javaTemplatePath("controller/controllerInterface"), javaFilePath("controller/${sceneEnum.basePackage}/${modulePath}/${moduleNameHump}Controller")+ ".java") .put(javaTemplatePath("convert/convertInterface"), javaModuleFilePath("convert", "${moduleNameHump}Convert")) .put(javaTemplatePath("service/serviceImplInterface"), javaModuleFilePath("service", "${moduleNameHump}ServiceImpl")) .put(javaTemplatePath("service/serviceInterface"), javaModuleFilePath("service", "${moduleNameHump}Service")) .put(javaTemplatePath("vo/VOInput"), javaModuleFilePath("vo", "${moduleNameHump}/${moduleNameHumpUp}${interfaceNameHumpUp}Input")) .put(javaTemplatePath("vo/VOOutput"), javaModuleFilePath("vo", "${moduleNameHump}/${moduleNameHumpUp}${interfaceNameHumpUp}Output")) .build(); /* private static final Table<Integer, String, String> FRONT_TEMPLATES = ImmutableTable.<Integer, String, String>builder() // Vue2 标准模版 .put(CodegenFrontTypeEnum.VUE2.getType(), vueTemplatePath("views/index.vue"), vueFilePath("views/${table.moduleName}/${classNameVar}/index.vue")) .put(CodegenFrontTypeEnum.VUE2.getType(), vueTemplatePath("api/api.js"), vueFilePath("api/${table.moduleName}/${classNameVar}.js")) // Vue3 标准模版 .put(CodegenFrontTypeEnum.VUE3.getType(), vue3TemplatePath("views/index.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/index.vue")) .put(CodegenFrontTypeEnum.VUE3.getType(), vue3TemplatePath("views/form.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${simpleClassName}Form.vue")) .put(CodegenFrontTypeEnum.VUE3.getType(), vue3TemplatePath("api/api.ts"), vue3FilePath("api/${table.moduleName}/${classNameVar}/index.ts")) // Vue3 Schema 模版 .put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath("views/data.ts"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${classNameVar}.data.ts")) .put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath("views/index.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/index.vue")) .put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath("views/form.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${simpleClassName}Form.vue")) .put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath("api/api.ts"), vue3FilePath("api/${table.moduleName}/${classNameVar}/index.ts")) // Vue3 vben 模版 .put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath("views/data.ts"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${classNameVar}.data.ts")) .put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath("views/index.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/index.vue")) .put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath("views/form.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${simpleClassName}Modal.vue")) .put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath("api/api.ts"), vue3FilePath("api/${table.moduleName}/${classNameVar}/index.ts")) .build();*/ @Resource private CodegenProperties codegenProperties; @Resource private InfraDatabaseTableRepository infraDatabaseTableRepository; @Resource private InfraInterfaceModuleRepository infraInterfaceModuleRepository; @Resource private InfraInterfaceRepository infraInterfaceRepository; @Resource private InfraInterfaceVoClassRepository infraInterfaceVoClassRepository; @Resource private InfraInterfaceSubclassRepository infraInterfaceSubclassRepository; @Resource private SchemaHistory schemaHistory; /** * 模板引擎,由 hutool 实现 */ private final TemplateEngine templateEngine; /** * 全局通用变量映射 */ private final Map<String, Object> globalBindingMap = new HashMap<>(); public CodegenEngine() { // 初始化 TemplateEngine 属性 TemplateConfig config = new TemplateConfig(); config.setResourceMode(TemplateConfig.ResourceMode.CLASSPATH); this.templateEngine = new VelocityEngine(config); } @PostConstruct private void initGlobalBindingMap() { // 全局配置 globalBindingMap.put("basePackage", codegenProperties.getBasePackage()); globalBindingMap.put("baseFrameworkPackage", codegenProperties.getBasePackage() + '.' + "framework"); // 用于后续获取测试类的 package 地址 // 全局 Java Bean globalBindingMap.put("CommonResultClassName", CommonResult.class.getName()); globalBindingMap.put("PageResultClassName", PageResult.class.getName()); // VO 类,独有字段 globalBindingMap.put("PageParamClassName", PageParam.class.getName()); globalBindingMap.put("DictFormatClassName", DictFormat.class.getName()); // DO 类,独有字段 globalBindingMap.put("BaseDOClassName", BaseDO.class.getName()); globalBindingMap.put("QueryWrapperClassName", LambdaQueryWrapperX.class.getName()); globalBindingMap.put("BaseMapperClassName", BaseMapperX.class.getName()); // Util 工具类 globalBindingMap.put("ServiceExceptionUtilClassName", ServiceExceptionUtil.class.getName()); globalBindingMap.put("DateUtilsClassName", DateUtils.class.getName()); globalBindingMap.put("ExcelUtilsClassName", ExcelUtils.class.getName()); globalBindingMap.put("LocalDateTimeUtilsClassName", LocalDateTimeUtils.class.getName()); globalBindingMap.put("ObjectUtilsClassName", ObjectUtils.class.getName()); globalBindingMap.put("DictConvertClassName", DictConvert.class.getName()); globalBindingMap.put("OperateLogClassName", OperateLog.class.getName());
globalBindingMap.put("OperateTypeEnumClassName", OperateTypeEnum.class.getName());
12
2023-10-27 06:35:24+00:00
16k
frc7787/FTC-Centerstage
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/RoadRunner/drive/SampleMecanumDrive.java
[ { "identifier": "TrajectorySequence", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/RoadRunner/trajectorysequence/TrajectorySequence.java", "snippet": "public class TrajectorySequence {\n private final List<SequenceSegment> sequenceList;\n\n public TrajectorySequence(List<Sequence...
import androidx.annotation.NonNull; import com.acmerobotics.dashboard.config.Config; import com.acmerobotics.roadrunner.control.PIDCoefficients; import com.acmerobotics.roadrunner.drive.DriveSignal; import com.acmerobotics.roadrunner.drive.MecanumDrive; import com.acmerobotics.roadrunner.followers.HolonomicPIDVAFollower; import com.acmerobotics.roadrunner.followers.TrajectoryFollower; import com.acmerobotics.roadrunner.geometry.Pose2d; import com.acmerobotics.roadrunner.trajectory.Trajectory; import com.acmerobotics.roadrunner.trajectory.TrajectoryBuilder; import com.acmerobotics.roadrunner.trajectory.constraints.AngularVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MecanumVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MinVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.ProfileAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryVelocityConstraint; import com.qualcomm.hardware.lynx.LynxModule; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorEx; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.PIDFCoefficients; import com.qualcomm.robotcore.hardware.VoltageSensor; import com.qualcomm.robotcore.hardware.configuration.typecontainers.MotorConfigurationType; import org.firstinspires.ftc.teamcode.RoadRunner.trajectorysequence.TrajectorySequence; import org.firstinspires.ftc.teamcode.RoadRunner.trajectorysequence.TrajectorySequenceBuilder; import org.firstinspires.ftc.teamcode.RoadRunner.trajectorysequence.TrajectorySequenceRunner; import org.firstinspires.ftc.teamcode.RoadRunner.util.LynxModuleUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
10,932
package org.firstinspires.ftc.teamcode.RoadRunner.drive; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config public class SampleMecanumDrive extends MecanumDrive { public static PIDCoefficients TRANSLATIONAL_PID_FB = new PIDCoefficients(0, 0, 0);// was named Translational_PID public static PIDCoefficients TRANSLATIONAL_PID_LR = TRANSLATIONAL_PID_FB ;//new PIDCoefficients(0, 0, 0);// With Mecanum wheels having a lateral PID with different values is useful public static PIDCoefficients HEADING_PID = new PIDCoefficients(8, 0, 0); public static double LATERAL_MULTIPLIER = 41.8 / 41.875; public static double VX_WEIGHT = 1; public static double VY_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner; private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(DriveConstants.MAX_VEL, DriveConstants.MAX_ANG_VEL, DriveConstants.TRACK_WIDTH); private static final TrajectoryAccelerationConstraint ACCEL_CONSTRAINT = getAccelerationConstraint(DriveConstants.MAX_ACCEL); private TrajectoryFollower follower; private DcMotorEx leftFront, leftRear, rightRear, rightFront; private List<DcMotorEx> motors; private VoltageSensor batteryVoltageSensor; private List<Integer> lastEncPositions = new ArrayList<>(); private List<Integer> lastEncVels = new ArrayList<>(); public SampleMecanumDrive(HardwareMap hardwareMap) { super(DriveConstants.kV, DriveConstants.kA, DriveConstants.kStatic, DriveConstants.TRACK_WIDTH, DriveConstants.TRACK_WIDTH, LATERAL_MULTIPLIER); follower = new HolonomicPIDVAFollower(TRANSLATIONAL_PID_FB, TRANSLATIONAL_PID_LR, HEADING_PID, new Pose2d(0.5, 0.5, Math.toRadians(5.0)), 0.5);// Modified to allow L/R tuning with another PID LynxModuleUtil.ensureMinimumFirmwareVersion(hardwareMap); batteryVoltageSensor = hardwareMap.voltageSensor.iterator().next(); for (LynxModule module : hardwareMap.getAll(LynxModule.class)) { module.setBulkCachingMode(LynxModule.BulkCachingMode.AUTO); } leftFront = hardwareMap.get(DcMotorEx.class, "Front Left Drive Motor"); leftRear = hardwareMap.get(DcMotorEx.class, "Back Left Drive Motor"); rightRear = hardwareMap.get(DcMotorEx.class, "Back Right Drive Motor"); rightFront = hardwareMap.get(DcMotorEx.class, "Front Right Drive Motor"); motors = Arrays.asList(leftFront, leftRear, rightRear, rightFront); for (DcMotorEx motor : motors) { MotorConfigurationType motorConfigurationType = motor.getMotorType().clone(); motorConfigurationType.setAchieveableMaxRPMFraction(1.0); motor.setMotorType(motorConfigurationType); } if (DriveConstants.RUN_USING_ENCODER) { setMode(DcMotor.RunMode.RUN_USING_ENCODER); } setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); if (DriveConstants.RUN_USING_ENCODER && DriveConstants.MOTOR_VELO_PID != null) { setPIDFCoefficients(DcMotor.RunMode.RUN_USING_ENCODER, DriveConstants.MOTOR_VELO_PID); } leftFront.setDirection(DcMotorSimple.Direction.REVERSE); leftRear.setDirection(DcMotorSimple.Direction.FORWARD); rightFront.setDirection(DcMotorSimple.Direction.FORWARD); List<Integer> lastTrackingEncPositions = new ArrayList<>(); List<Integer> lastTrackingEncVels = new ArrayList<>(); // TODO: if desired, use setLocalizer() to change the localization method setLocalizer(new StandardTrackingWheelLocalizer(hardwareMap, lastTrackingEncPositions, lastTrackingEncVels)); trajectorySequenceRunner = new TrajectorySequenceRunner( follower, HEADING_PID, batteryVoltageSensor, lastEncPositions, lastEncVels, lastTrackingEncPositions, lastTrackingEncVels ); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose) { return new TrajectoryBuilder(startPose, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, boolean reversed) { return new TrajectoryBuilder(startPose, reversed, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, double startHeading) { return new TrajectoryBuilder(startPose, startHeading, VEL_CONSTRAINT, ACCEL_CONSTRAINT); }
package org.firstinspires.ftc.teamcode.RoadRunner.drive; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config public class SampleMecanumDrive extends MecanumDrive { public static PIDCoefficients TRANSLATIONAL_PID_FB = new PIDCoefficients(0, 0, 0);// was named Translational_PID public static PIDCoefficients TRANSLATIONAL_PID_LR = TRANSLATIONAL_PID_FB ;//new PIDCoefficients(0, 0, 0);// With Mecanum wheels having a lateral PID with different values is useful public static PIDCoefficients HEADING_PID = new PIDCoefficients(8, 0, 0); public static double LATERAL_MULTIPLIER = 41.8 / 41.875; public static double VX_WEIGHT = 1; public static double VY_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner; private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(DriveConstants.MAX_VEL, DriveConstants.MAX_ANG_VEL, DriveConstants.TRACK_WIDTH); private static final TrajectoryAccelerationConstraint ACCEL_CONSTRAINT = getAccelerationConstraint(DriveConstants.MAX_ACCEL); private TrajectoryFollower follower; private DcMotorEx leftFront, leftRear, rightRear, rightFront; private List<DcMotorEx> motors; private VoltageSensor batteryVoltageSensor; private List<Integer> lastEncPositions = new ArrayList<>(); private List<Integer> lastEncVels = new ArrayList<>(); public SampleMecanumDrive(HardwareMap hardwareMap) { super(DriveConstants.kV, DriveConstants.kA, DriveConstants.kStatic, DriveConstants.TRACK_WIDTH, DriveConstants.TRACK_WIDTH, LATERAL_MULTIPLIER); follower = new HolonomicPIDVAFollower(TRANSLATIONAL_PID_FB, TRANSLATIONAL_PID_LR, HEADING_PID, new Pose2d(0.5, 0.5, Math.toRadians(5.0)), 0.5);// Modified to allow L/R tuning with another PID LynxModuleUtil.ensureMinimumFirmwareVersion(hardwareMap); batteryVoltageSensor = hardwareMap.voltageSensor.iterator().next(); for (LynxModule module : hardwareMap.getAll(LynxModule.class)) { module.setBulkCachingMode(LynxModule.BulkCachingMode.AUTO); } leftFront = hardwareMap.get(DcMotorEx.class, "Front Left Drive Motor"); leftRear = hardwareMap.get(DcMotorEx.class, "Back Left Drive Motor"); rightRear = hardwareMap.get(DcMotorEx.class, "Back Right Drive Motor"); rightFront = hardwareMap.get(DcMotorEx.class, "Front Right Drive Motor"); motors = Arrays.asList(leftFront, leftRear, rightRear, rightFront); for (DcMotorEx motor : motors) { MotorConfigurationType motorConfigurationType = motor.getMotorType().clone(); motorConfigurationType.setAchieveableMaxRPMFraction(1.0); motor.setMotorType(motorConfigurationType); } if (DriveConstants.RUN_USING_ENCODER) { setMode(DcMotor.RunMode.RUN_USING_ENCODER); } setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); if (DriveConstants.RUN_USING_ENCODER && DriveConstants.MOTOR_VELO_PID != null) { setPIDFCoefficients(DcMotor.RunMode.RUN_USING_ENCODER, DriveConstants.MOTOR_VELO_PID); } leftFront.setDirection(DcMotorSimple.Direction.REVERSE); leftRear.setDirection(DcMotorSimple.Direction.FORWARD); rightFront.setDirection(DcMotorSimple.Direction.FORWARD); List<Integer> lastTrackingEncPositions = new ArrayList<>(); List<Integer> lastTrackingEncVels = new ArrayList<>(); // TODO: if desired, use setLocalizer() to change the localization method setLocalizer(new StandardTrackingWheelLocalizer(hardwareMap, lastTrackingEncPositions, lastTrackingEncVels)); trajectorySequenceRunner = new TrajectorySequenceRunner( follower, HEADING_PID, batteryVoltageSensor, lastEncPositions, lastEncVels, lastTrackingEncPositions, lastTrackingEncVels ); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose) { return new TrajectoryBuilder(startPose, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, boolean reversed) { return new TrajectoryBuilder(startPose, reversed, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, double startHeading) { return new TrajectoryBuilder(startPose, startHeading, VEL_CONSTRAINT, ACCEL_CONSTRAINT); }
public TrajectorySequenceBuilder trajectorySequenceBuilder(Pose2d startPose) {
1
2023-10-31 16:06:46+00:00
16k
slatepowered/slate
slate-cluster/src/main/java/slatepowered/slate/cluster/ClusterInstance.java
[ { "identifier": "CommunicationKey", "path": "slate-common/src/main/java/slatepowered/slate/communication/CommunicationKey.java", "snippet": "public class CommunicationKey {\r\n\r\n public static class ClusterDeclareCommunicationKey extends CommunicationKey {\r\n @Override\r\n public int...
import slatepowered.slate.allocation.*; import slatepowered.slate.communication.CommunicationKey; import slatepowered.slate.communication.CommunicationStrategy; import slatepowered.slate.logging.Logger; import slatepowered.slate.logging.Logging; import slatepowered.slate.model.ClusterManagedNode; import slatepowered.slate.model.ClusterNetwork; import slatepowered.slate.model.Node; import slatepowered.slate.model.NodeComponent; import slatepowered.slate.action.NodeAllocationAdapter; import slatepowered.slate.network.NetworkInfoService; import slatepowered.slate.packages.PackageAttachment; import slatepowered.slate.packages.PackageManager; import slatepowered.slate.packages.Packages; import slatepowered.slate.packages.service.LateAttachmentService; import slatepowered.slate.plugin.SlatePluginManager; import slatepowered.veru.collection.Sequence; import slatepowered.veru.misc.Throwables; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture;
11,599
package slatepowered.slate.cluster; /** * An instance of this cluster for a specific network. */ public abstract class ClusterInstance extends ClusterNetwork { protected static final Logger LOGGER = Logging.getLogger("ClusterInstance"); /** * The cluster. */ protected final Cluster<?> cluster; /** * The directory for this cluster instance. */ protected final Path directory; /** * Whether this instance is enabled. */ private boolean enabled = true;
package slatepowered.slate.cluster; /** * An instance of this cluster for a specific network. */ public abstract class ClusterInstance extends ClusterNetwork { protected static final Logger LOGGER = Logging.getLogger("ClusterInstance"); /** * The cluster. */ protected final Cluster<?> cluster; /** * The directory for this cluster instance. */ protected final Path directory; /** * Whether this instance is enabled. */ private boolean enabled = true;
public ClusterInstance(Cluster<?> cluster, CommunicationKey communicationKey, CommunicationStrategy communicationStrategy) {
1
2023-10-30 08:58:02+00:00
16k
Melledy/LunarCore
src/main/java/emu/lunarcore/command/commands/GiveCommand.java
[ { "identifier": "CommandArgs", "path": "src/main/java/emu/lunarcore/command/CommandArgs.java", "snippet": "@Getter\npublic class CommandArgs {\n private String raw;\n private List<String> list;\n private Player sender;\n private Player target;\n \n private int targetUid;\n private i...
import java.util.LinkedList; import java.util.List; import emu.lunarcore.command.Command; import emu.lunarcore.command.CommandArgs; import emu.lunarcore.command.CommandHandler; import emu.lunarcore.data.GameData; import emu.lunarcore.data.excel.ItemExcel; import emu.lunarcore.game.avatar.GameAvatar; import emu.lunarcore.game.enums.ItemMainType; import emu.lunarcore.game.inventory.GameItem; import emu.lunarcore.util.Utils;
13,665
package emu.lunarcore.command.commands; @Command( label = "give", aliases = {"g", "item"}, permission = "player.give", requireTarget = true, desc = "/give [item id] x(amount) lv(level) r(rank) p(promotion). Gives the targeted player an item." ) public class GiveCommand implements CommandHandler { @Override public void execute(CommandArgs args) { // Setup items List<GameItem> items = new LinkedList<>(); // Get amount to give int amount = Math.max(args.getAmount(), 1); // Parse items for (String arg : args.getList()) { // Parse item id int itemId = Utils.parseSafeInt(arg); ItemExcel itemData = GameData.getItemExcelMap().get(itemId); if (itemData == null) { args.sendMessage("Item \"" + arg + "\" does not exist!"); continue; } // Add item
package emu.lunarcore.command.commands; @Command( label = "give", aliases = {"g", "item"}, permission = "player.give", requireTarget = true, desc = "/give [item id] x(amount) lv(level) r(rank) p(promotion). Gives the targeted player an item." ) public class GiveCommand implements CommandHandler { @Override public void execute(CommandArgs args) { // Setup items List<GameItem> items = new LinkedList<>(); // Get amount to give int amount = Math.max(args.getAmount(), 1); // Parse items for (String arg : args.getList()) { // Parse item id int itemId = Utils.parseSafeInt(arg); ItemExcel itemData = GameData.getItemExcelMap().get(itemId); if (itemData == null) { args.sendMessage("Item \"" + arg + "\" does not exist!"); continue; } // Add item
if (itemData.getItemMainType() == ItemMainType.AvatarCard) {
5
2023-10-10 12:57:35+00:00
16k
lunasaw/gb28181-proxy
gb28181-server/src/main/java/io/github/lunasaw/gbproxy/server/transimit/response/invite/InviteResponseProcessor.java
[ { "identifier": "ServerSendCmd", "path": "gb28181-server/src/main/java/io/github/lunasaw/gbproxy/server/transimit/cmd/ServerSendCmd.java", "snippet": "public class ServerSendCmd {\n\n /**\n * 设备信息查询\n *\n * @param fromDevice 发送设备\n * @param toDevice 接收设备\n * @return callId\n *...
import java.text.ParseException; import javax.sdp.SdpParseException; import javax.sdp.SessionDescription; import javax.sip.ResponseEvent; import javax.sip.address.SipURI; import javax.sip.message.Response; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import gov.nist.javax.sip.ResponseEventExt; import gov.nist.javax.sip.message.SIPResponse; import io.github.lunasaw.gbproxy.server.transimit.cmd.ServerSendCmd; import io.github.lunasaw.gbproxy.server.user.SipUserGenerateServer; import io.github.lunasaw.sip.common.entity.FromDevice; import io.github.lunasaw.sip.common.entity.SdpSessionDescription; import io.github.lunasaw.sip.common.transmit.event.response.SipResponseProcessorAbstract; import io.github.lunasaw.sip.common.utils.SipRequestUtils; import io.github.lunasaw.sip.common.utils.SipUtils; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j;
12,612
package io.github.lunasaw.gbproxy.server.transimit.response.invite; /** * 发起INVITE响应 * * @author luna */ @Slf4j @Getter @Setter @Component public class InviteResponseProcessor extends SipResponseProcessorAbstract { private static final String METHOD = "INVITE"; private String method = METHOD; @Autowired private InviteResponseProcessorServer inviteResponseProcessorServer; @Autowired private SipUserGenerateServer sipUserGenerate; /** * 处理invite响应 * * @param evt 响应消息 * @throws ParseException */ @Override public void process(ResponseEvent evt) { try { SIPResponse response = (SIPResponse)evt.getResponse(); int statusCode = response.getStatusCode(); if (statusCode == Response.TRYING) { inviteResponseProcessorServer.responseTrying(); } if (statusCode == Response.OK) { ResponseEventExt event = (ResponseEventExt)evt; responseAck(event); } } catch (Exception e) { log.info("[点播回复ACK],异常:", e); } } public void responseAck(ResponseEventExt evt) throws SdpParseException { // 成功响应 SIPResponse response = (SIPResponse)evt.getResponse(); FromDevice fromDevice = (FromDevice)sipUserGenerate.getFromDevice(); String contentString = new String(response.getRawContent());
package io.github.lunasaw.gbproxy.server.transimit.response.invite; /** * 发起INVITE响应 * * @author luna */ @Slf4j @Getter @Setter @Component public class InviteResponseProcessor extends SipResponseProcessorAbstract { private static final String METHOD = "INVITE"; private String method = METHOD; @Autowired private InviteResponseProcessorServer inviteResponseProcessorServer; @Autowired private SipUserGenerateServer sipUserGenerate; /** * 处理invite响应 * * @param evt 响应消息 * @throws ParseException */ @Override public void process(ResponseEvent evt) { try { SIPResponse response = (SIPResponse)evt.getResponse(); int statusCode = response.getStatusCode(); if (statusCode == Response.TRYING) { inviteResponseProcessorServer.responseTrying(); } if (statusCode == Response.OK) { ResponseEventExt event = (ResponseEventExt)evt; responseAck(event); } } catch (Exception e) { log.info("[点播回复ACK],异常:", e); } } public void responseAck(ResponseEventExt evt) throws SdpParseException { // 成功响应 SIPResponse response = (SIPResponse)evt.getResponse(); FromDevice fromDevice = (FromDevice)sipUserGenerate.getFromDevice(); String contentString = new String(response.getRawContent());
SdpSessionDescription gb28181Sdp = SipUtils.parseSdp(contentString);
6
2023-10-11 06:56:28+00:00
16k
Swofty-Developments/Continued-Slime-World-Manager
swoftyworldmanager-plugin/src/main/java/net/swofty/swm/plugin/loader/LoaderUtils.java
[ { "identifier": "CorruptedWorldException", "path": "swoftyworldmanager-api/src/main/java/net/swofty/swm/api/exceptions/CorruptedWorldException.java", "snippet": "public class CorruptedWorldException extends SlimeException {\n\n public CorruptedWorldException(String world) {\n this(world, null)...
import com.flowpowered.nbt.CompoundMap; import com.flowpowered.nbt.CompoundTag; import com.flowpowered.nbt.DoubleTag; import com.flowpowered.nbt.IntArrayTag; import com.flowpowered.nbt.IntTag; import com.flowpowered.nbt.ListTag; import com.flowpowered.nbt.stream.NBTInputStream; import com.github.luben.zstd.Zstd; import net.swofty.swm.api.exceptions.CorruptedWorldException; import net.swofty.swm.api.exceptions.NewerFormatException; import net.swofty.swm.api.loaders.SlimeLoader; import net.swofty.swm.api.utils.NibbleArray; import net.swofty.swm.api.utils.SlimeFormat; import net.swofty.swm.api.world.SlimeChunk; import net.swofty.swm.api.world.SlimeChunkSection; import net.swofty.swm.api.world.properties.SlimePropertyMap; import net.swofty.swm.nms.craft.CraftSlimeChunk; import net.swofty.swm.nms.craft.CraftSlimeChunkSection; import net.swofty.swm.nms.craft.CraftSlimeWorld; import net.swofty.swm.plugin.config.ConfigManager; import net.swofty.swm.plugin.config.DatasourcesConfig; import net.swofty.swm.plugin.loader.loaders.FileLoader; import net.swofty.swm.plugin.loader.loaders.MongoLoader; import net.swofty.swm.plugin.loader.loaders.MysqlLoader; import net.swofty.swm.plugin.log.Logging; import com.mongodb.MongoException; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.EOFException; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.sql.SQLException; import java.util.*;
13,953
package net.swofty.swm.plugin.loader; public class LoaderUtils { public static final long MAX_LOCK_TIME = 300000L; // Max time difference between current time millis and world lock public static final long LOCK_INTERVAL = 60000L; private static Map<String, SlimeLoader> loaderMap = new HashMap<>(); public static void registerLoaders() { DatasourcesConfig config = ConfigManager.getDatasourcesConfig(); // File loader DatasourcesConfig.FileConfig fileConfig = config.getFileConfig(); registerLoader("file", new FileLoader(new File(fileConfig.getPath()))); // Mysql loader DatasourcesConfig.MysqlConfig mysqlConfig = config.getMysqlConfig(); if (mysqlConfig.isEnabled()) { try { registerLoader("mysql", new MysqlLoader(mysqlConfig)); } catch (SQLException ex) { Logging.error("Failed to establish connection to the MySQL server:"); ex.printStackTrace(); } } // MongoDB loader DatasourcesConfig.MongoDBConfig mongoConfig = config.getMongoDbConfig(); if (mongoConfig.isEnabled()) { try { registerLoader("mongodb", new MongoLoader(mongoConfig)); } catch (MongoException ex) { Logging.error("Failed to establish connection to the MongoDB server:"); ex.printStackTrace(); } } } public static List<String> getAvailableLoadersNames() { return new LinkedList<>(loaderMap.keySet()); } public static SlimeLoader getLoader(String dataSource) { return loaderMap.get(dataSource); } public static void registerLoader(String dataSource, SlimeLoader loader) { if (loaderMap.containsKey(dataSource)) { throw new IllegalArgumentException("Data source " + dataSource + " already has a declared loader!"); } if (loader instanceof UpdatableLoader) { try { ((UpdatableLoader) loader).update(); } catch (UpdatableLoader.NewerDatabaseException e) { Logging.error("Data source " + dataSource + " version is " + e.getDatabaseVersion() + ", while" + " this SWM version only supports up to version " + e.getCurrentVersion() + "."); return; } catch (IOException ex) { Logging.error("Failed to check if data source " + dataSource + " is updated:"); ex.printStackTrace(); return; } } loaderMap.put(dataSource, loader); } public static CraftSlimeWorld deserializeWorld(SlimeLoader loader, String worldName, byte[] serializedWorld, SlimePropertyMap propertyMap, boolean readOnly)
package net.swofty.swm.plugin.loader; public class LoaderUtils { public static final long MAX_LOCK_TIME = 300000L; // Max time difference between current time millis and world lock public static final long LOCK_INTERVAL = 60000L; private static Map<String, SlimeLoader> loaderMap = new HashMap<>(); public static void registerLoaders() { DatasourcesConfig config = ConfigManager.getDatasourcesConfig(); // File loader DatasourcesConfig.FileConfig fileConfig = config.getFileConfig(); registerLoader("file", new FileLoader(new File(fileConfig.getPath()))); // Mysql loader DatasourcesConfig.MysqlConfig mysqlConfig = config.getMysqlConfig(); if (mysqlConfig.isEnabled()) { try { registerLoader("mysql", new MysqlLoader(mysqlConfig)); } catch (SQLException ex) { Logging.error("Failed to establish connection to the MySQL server:"); ex.printStackTrace(); } } // MongoDB loader DatasourcesConfig.MongoDBConfig mongoConfig = config.getMongoDbConfig(); if (mongoConfig.isEnabled()) { try { registerLoader("mongodb", new MongoLoader(mongoConfig)); } catch (MongoException ex) { Logging.error("Failed to establish connection to the MongoDB server:"); ex.printStackTrace(); } } } public static List<String> getAvailableLoadersNames() { return new LinkedList<>(loaderMap.keySet()); } public static SlimeLoader getLoader(String dataSource) { return loaderMap.get(dataSource); } public static void registerLoader(String dataSource, SlimeLoader loader) { if (loaderMap.containsKey(dataSource)) { throw new IllegalArgumentException("Data source " + dataSource + " already has a declared loader!"); } if (loader instanceof UpdatableLoader) { try { ((UpdatableLoader) loader).update(); } catch (UpdatableLoader.NewerDatabaseException e) { Logging.error("Data source " + dataSource + " version is " + e.getDatabaseVersion() + ", while" + " this SWM version only supports up to version " + e.getCurrentVersion() + "."); return; } catch (IOException ex) { Logging.error("Failed to check if data source " + dataSource + " is updated:"); ex.printStackTrace(); return; } } loaderMap.put(dataSource, loader); } public static CraftSlimeWorld deserializeWorld(SlimeLoader loader, String worldName, byte[] serializedWorld, SlimePropertyMap propertyMap, boolean readOnly)
throws IOException, CorruptedWorldException, NewerFormatException {
0
2023-10-08 10:54:28+00:00
16k
ZJU-ACES-ISE/chatunitest-core
src/main/java/zju/cst/aces/prompt/PromptGenerator.java
[ { "identifier": "Task", "path": "src/main/java/zju/cst/aces/api/Task.java", "snippet": "public class Task {\n\n Config config;\n Logger log;\n\n public Task(Config config) {\n this.config = config;\n this.log = config.getLog();\n }\n\n public void startMethodTask(String clas...
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import freemarker.template.TemplateException; import zju.cst.aces.api.Task; import zju.cst.aces.api.config.Config; import zju.cst.aces.dto.*; import zju.cst.aces.parser.ProjectParser; import zju.cst.aces.runner.AbstractRunner; import zju.cst.aces.util.TokenCounter; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*;
13,478
package zju.cst.aces.prompt; public class PromptGenerator { public Config config; PromptTemplate promptTemplate; public static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); public PromptGenerator(Config config) { this.config = config; this.promptTemplate = new PromptTemplate(config); } public void setConfig(Config config) { this.config = config; this.promptTemplate = new PromptTemplate(config); } public List<Message> generateMessages(PromptInfo promptInfo) throws IOException { List<Message> messages = new ArrayList<>(); if (promptInfo.errorMsg == null) { // round 0 messages.add(Message.ofSystem(createSystemPrompt(promptInfo))); } messages.add(Message.of(createUserPrompt(promptInfo))); return messages; } private String adaptiveFocalContext(Map<String, Object> data) { String afc = data.get("full_fm").toString(); return ""; } public String createUserPrompt(PromptInfo promptInfo) throws IOException { try { promptTemplate.readProperties(); ExampleUsage exampleUsage = new ExampleUsage(config, promptInfo.className); Map<String, String> cdep_temp = new HashMap<>(); Map<String, String> mdep_temp = new HashMap<>(); // Map<String, String>, key: dependent class names promptTemplate.dataModel.put("dep_packages", getDepPackages(promptInfo.getClassInfo(), promptInfo.getMethodInfo())); promptTemplate.dataModel.put("dep_imports", getDepImports(promptInfo.getClassInfo(), promptInfo.getMethodInfo())); promptTemplate.dataModel.put("dep_class_sigs", getDepClassSigs(promptInfo.getClassInfo(), promptInfo.getMethodInfo())); promptTemplate.dataModel.put("dep_class_bodies", getDepClassBodies(promptInfo.getClassInfo(), promptInfo.getMethodInfo())); promptTemplate.dataModel.put("dep_m_sigs", getDepBrief(promptInfo.getMethodInfo())); promptTemplate.dataModel.put("dep_m_bodies", getDepBodies(promptInfo.getMethodInfo())); promptTemplate.dataModel.put("dep_c_sigs", getDepConstructorSigs(promptInfo.getClassInfo(), promptInfo.getMethodInfo())); promptTemplate.dataModel.put("dep_c_bodies", getDepConstructorBodies(promptInfo.getClassInfo(), promptInfo.getMethodInfo())); promptTemplate.dataModel.put("dep_fields", getDepFields(promptInfo.getClassInfo(), promptInfo.getMethodInfo())); promptTemplate.dataModel.put("dep_gs_sigs", getDepGSSigs(promptInfo.getClassInfo(), promptInfo.getMethodInfo())); promptTemplate.dataModel.put("dep_gs_bodies", getDepGSBodies(promptInfo.getClassInfo(), promptInfo.getMethodInfo())); // String promptTemplate.dataModel.put("example_usage", exampleUsage.getShortestUsage(promptInfo.getMethodInfo().methodSignature)); promptTemplate.dataModel.put("project_full_code", getFullProjectCode(promptInfo.getClassName(), config)); promptTemplate.dataModel.put("method_name", promptInfo.getMethodName()); promptTemplate.dataModel.put("method_sig", promptInfo.getMethodSignature()); promptTemplate.dataModel.put("method_body", promptInfo.getMethodInfo().sourceCode); promptTemplate.dataModel.put("class_name", promptInfo.getClassName()); promptTemplate.dataModel.put("class_sig", promptInfo.getClassInfo().classSignature); promptTemplate.dataModel.put("package", promptInfo.getClassInfo().packageDeclaration); promptTemplate.dataModel.put("class_body", promptInfo.getClassInfo().classDeclarationCode); promptTemplate.dataModel.put("file_content", promptInfo.getClassInfo().compilationUnitCode);
package zju.cst.aces.prompt; public class PromptGenerator { public Config config; PromptTemplate promptTemplate; public static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); public PromptGenerator(Config config) { this.config = config; this.promptTemplate = new PromptTemplate(config); } public void setConfig(Config config) { this.config = config; this.promptTemplate = new PromptTemplate(config); } public List<Message> generateMessages(PromptInfo promptInfo) throws IOException { List<Message> messages = new ArrayList<>(); if (promptInfo.errorMsg == null) { // round 0 messages.add(Message.ofSystem(createSystemPrompt(promptInfo))); } messages.add(Message.of(createUserPrompt(promptInfo))); return messages; } private String adaptiveFocalContext(Map<String, Object> data) { String afc = data.get("full_fm").toString(); return ""; } public String createUserPrompt(PromptInfo promptInfo) throws IOException { try { promptTemplate.readProperties(); ExampleUsage exampleUsage = new ExampleUsage(config, promptInfo.className); Map<String, String> cdep_temp = new HashMap<>(); Map<String, String> mdep_temp = new HashMap<>(); // Map<String, String>, key: dependent class names promptTemplate.dataModel.put("dep_packages", getDepPackages(promptInfo.getClassInfo(), promptInfo.getMethodInfo())); promptTemplate.dataModel.put("dep_imports", getDepImports(promptInfo.getClassInfo(), promptInfo.getMethodInfo())); promptTemplate.dataModel.put("dep_class_sigs", getDepClassSigs(promptInfo.getClassInfo(), promptInfo.getMethodInfo())); promptTemplate.dataModel.put("dep_class_bodies", getDepClassBodies(promptInfo.getClassInfo(), promptInfo.getMethodInfo())); promptTemplate.dataModel.put("dep_m_sigs", getDepBrief(promptInfo.getMethodInfo())); promptTemplate.dataModel.put("dep_m_bodies", getDepBodies(promptInfo.getMethodInfo())); promptTemplate.dataModel.put("dep_c_sigs", getDepConstructorSigs(promptInfo.getClassInfo(), promptInfo.getMethodInfo())); promptTemplate.dataModel.put("dep_c_bodies", getDepConstructorBodies(promptInfo.getClassInfo(), promptInfo.getMethodInfo())); promptTemplate.dataModel.put("dep_fields", getDepFields(promptInfo.getClassInfo(), promptInfo.getMethodInfo())); promptTemplate.dataModel.put("dep_gs_sigs", getDepGSSigs(promptInfo.getClassInfo(), promptInfo.getMethodInfo())); promptTemplate.dataModel.put("dep_gs_bodies", getDepGSBodies(promptInfo.getClassInfo(), promptInfo.getMethodInfo())); // String promptTemplate.dataModel.put("example_usage", exampleUsage.getShortestUsage(promptInfo.getMethodInfo().methodSignature)); promptTemplate.dataModel.put("project_full_code", getFullProjectCode(promptInfo.getClassName(), config)); promptTemplate.dataModel.put("method_name", promptInfo.getMethodName()); promptTemplate.dataModel.put("method_sig", promptInfo.getMethodSignature()); promptTemplate.dataModel.put("method_body", promptInfo.getMethodInfo().sourceCode); promptTemplate.dataModel.put("class_name", promptInfo.getClassName()); promptTemplate.dataModel.put("class_sig", promptInfo.getClassInfo().classSignature); promptTemplate.dataModel.put("package", promptInfo.getClassInfo().packageDeclaration); promptTemplate.dataModel.put("class_body", promptInfo.getClassInfo().classDeclarationCode); promptTemplate.dataModel.put("file_content", promptInfo.getClassInfo().compilationUnitCode);
promptTemplate.dataModel.put("imports", AbstractRunner.joinLines(promptInfo.getClassInfo().imports));
3
2023-10-14 07:15:10+00:00
16k
PfauMC/CyanWorld
cyanworld-cyanuniverse/src/main/java/ru/cyanworld/cyanuniverse/MainListener.java
[ { "identifier": "Cyan1dex", "path": "cyanworld-cyan1dex/src/main/java/ru/cyanworld/cyan1dex/Cyan1dex.java", "snippet": "public class Cyan1dex extends JavaPlugin {\n public static Server server;\n public static Cyan1dex instance;\n public static File dataFolder;\n public static Random random;...
import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.block.Sign; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Item; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.*; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.*; import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; import org.bukkit.scheduler.BukkitRunnable; import ru.cyanworld.cyan1dex.Cyan1dex; import ru.cyanworld.cyan1dex.CyanEcoManager; import ru.cyanworld.cyan1dex.Utils; import ru.cyanworld.cyan1dex.api.CustomItem; import ru.cyanworld.cyan1dex.api.ItemBuilder; import ru.cyanworld.cyanuniverse.commands.CmdNbt; import ru.cyanworld.cyanuniverse.commands.MainCommand; import ru.cyanworld.cyanuniverse.menus.MyWorlds; import ru.cyanworld.cyanuniverse.menus.coding.*; import ru.cyanworld.cyanuniverse.menus.coding.variables.EffectMenu; import ru.cyanworld.cyanuniverse.menus.coding.variables.VariableMenu; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import java.util.UUID; import static ru.cyanworld.cyanuniverse.Coding.cancelEvent; import static ru.cyanworld.cyanuniverse.Coding.codeMap; import static ru.cyanworld.cyanuniverse.CyanUniverse.*;
13,614
package ru.cyanworld.cyanuniverse; public class MainListener implements Listener { public static List<World> unloadwithoutsave = new ArrayList<>(); public List<Player> canceledOpen = new ArrayList<>(); DecimalFormat decimalFormat = new DecimalFormat("#.##"); public MainListener() { server.getPluginManager().registerEvents(this, plugin); server.getScheduler().scheduleSyncRepeatingTask(plugin, () -> canceledOpen.removeAll(canceledOpen), 0, 1); } @EventHandler public void onInteract(PlayerInteractEvent event) { ItemStack itemStack = event.getItem(); Player player = event.getPlayer(); World world = player.getWorld(); UUID eventid = UUID.randomUUID(); String uuid = player.getUniqueId().toString(); switch (WorldManager.getWorldType(world)) { //TODO: Правирить!!1!11! case "building": { try { if (!event.hasItem()) { if (player.getGameMode() != GameMode.CREATIVE) { event.setUseInteractedBlock(Event.Result.DENY); } } if (event.getAction().name().startsWith("RIGHT_CLICK") && itemStack != null) { switch (itemStack.getType()) { case PAPER: { Location location = player.getLocation(); if (location.getX() >= 999) { player.sendTitle("§cОШИБКА!", "Нажмите ЛКМ для телепортации в мир", 5, 60, 10); Utils.playCustomSound("deny", player); } else { String loc = ("§r" + decimalFormat.format(location.getX()) + " " + decimalFormat.format(location.getY()) + " " + decimalFormat.format(location.getZ()) + " " + decimalFormat.format(location.getYaw()) + " " + decimalFormat.format(location.getPitch())).replace(",", "."); player.getInventory().getItemInMainHand().getItemMeta().setDisplayName(loc); player.sendTitle("§aУстановлено местоположение:", loc, 5, 60, 10); Utils.playCustomSound("ok", player); } break; } case COMPASS: { event.setCancelled(true); if (player.getWorld().getName().startsWith(uuid)) player.openInventory(MenusList.myWorldMenu.inventory); else player.openInventory(MenusList.worldsMenu.inventory); break; } case MAP: { event.setCancelled(true); if (world == lobby) { player.openInventory(new MyWorlds(player).getInventory()); } break; } case PRISMARINE_CRYSTALS: { event.setCancelled(true); player.openInventory(MenusList.decoMain.getInventory()); break; } case MAGMA_CREAM: { event.setCancelled(true); player.chat("/lobby"); break; } } } } catch (Exception ex) { } } case "coding": { if (player.getGameMode() == GameMode.SPECTATOR) return; if (event.getAction().name().startsWith("RIGHT_CLICK")) { if (itemStack == null || itemStack.getType() == Material.AIR) return; switch (itemStack.getType()) { case IRON_INGOT: { server.getScheduler().scheduleSyncDelayedTask(plugin, () -> player.openInventory(new VariableMenu().getInventory())); break; } case GLASS_BOTTLE: {
package ru.cyanworld.cyanuniverse; public class MainListener implements Listener { public static List<World> unloadwithoutsave = new ArrayList<>(); public List<Player> canceledOpen = new ArrayList<>(); DecimalFormat decimalFormat = new DecimalFormat("#.##"); public MainListener() { server.getPluginManager().registerEvents(this, plugin); server.getScheduler().scheduleSyncRepeatingTask(plugin, () -> canceledOpen.removeAll(canceledOpen), 0, 1); } @EventHandler public void onInteract(PlayerInteractEvent event) { ItemStack itemStack = event.getItem(); Player player = event.getPlayer(); World world = player.getWorld(); UUID eventid = UUID.randomUUID(); String uuid = player.getUniqueId().toString(); switch (WorldManager.getWorldType(world)) { //TODO: Правирить!!1!11! case "building": { try { if (!event.hasItem()) { if (player.getGameMode() != GameMode.CREATIVE) { event.setUseInteractedBlock(Event.Result.DENY); } } if (event.getAction().name().startsWith("RIGHT_CLICK") && itemStack != null) { switch (itemStack.getType()) { case PAPER: { Location location = player.getLocation(); if (location.getX() >= 999) { player.sendTitle("§cОШИБКА!", "Нажмите ЛКМ для телепортации в мир", 5, 60, 10); Utils.playCustomSound("deny", player); } else { String loc = ("§r" + decimalFormat.format(location.getX()) + " " + decimalFormat.format(location.getY()) + " " + decimalFormat.format(location.getZ()) + " " + decimalFormat.format(location.getYaw()) + " " + decimalFormat.format(location.getPitch())).replace(",", "."); player.getInventory().getItemInMainHand().getItemMeta().setDisplayName(loc); player.sendTitle("§aУстановлено местоположение:", loc, 5, 60, 10); Utils.playCustomSound("ok", player); } break; } case COMPASS: { event.setCancelled(true); if (player.getWorld().getName().startsWith(uuid)) player.openInventory(MenusList.myWorldMenu.inventory); else player.openInventory(MenusList.worldsMenu.inventory); break; } case MAP: { event.setCancelled(true); if (world == lobby) { player.openInventory(new MyWorlds(player).getInventory()); } break; } case PRISMARINE_CRYSTALS: { event.setCancelled(true); player.openInventory(MenusList.decoMain.getInventory()); break; } case MAGMA_CREAM: { event.setCancelled(true); player.chat("/lobby"); break; } } } } catch (Exception ex) { } } case "coding": { if (player.getGameMode() == GameMode.SPECTATOR) return; if (event.getAction().name().startsWith("RIGHT_CLICK")) { if (itemStack == null || itemStack.getType() == Material.AIR) return; switch (itemStack.getType()) { case IRON_INGOT: { server.getScheduler().scheduleSyncDelayedTask(plugin, () -> player.openInventory(new VariableMenu().getInventory())); break; } case GLASS_BOTTLE: {
player.openInventory(new EffectMenu().getInventory());
8
2023-10-08 17:50:55+00:00
16k
ProjectgamesOOP/Adventure_to_the_Fallen_Kingdom
src/entities/Player.java
[ { "identifier": "PlayerConstants", "path": "src/utilz/Constants.java", "snippet": "public static class PlayerConstants{\n\tpublic static final int RUSH = 0;\n\tpublic static final int ATTACK = 1;\n\tpublic static final int GROUND = 2;\n\tpublic static final int DEAD = 3;\n\tpublic static final int FALLI...
import static utilz.Constants.PlayerConstants.*; import static utilz.HelpMethods.*; import static utilz.Constants.*; import java.awt.Color; import java.awt.Graphics; import java.awt.Point; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import audio.AudioPlayer; import gamestates.Playing; import main.Game; import utilz.LoadSave;
11,533
package entities; public class Player extends Entity { private BufferedImage[][] animations; private boolean moving = false, attacking = false; private boolean left, right, jump; private int[][] lvlData; private float xDrawOffset = 25 * Game.SCALE; private float yDrawOffset = 4 * Game.SCALE; // Jumping / Gravity private float jumpSpeed = -2.25f * Game.SCALE; private float fallSpeedAfterCollision = 0.5f * Game.SCALE; //StatusBarUI private BufferedImage statusBarImg; private int statusBarWidth = (int) (192 * Game.SCALE); private int statusBarHeight = (int) (58 * Game.SCALE); private int statusBarX = (int) (10 * Game.SCALE); private int statusBarY = (int) (10 * Game.SCALE); private int healthBarWidth = (int) (150 * Game.SCALE); private int healthBarHeight = (int) (4 * Game.SCALE); private int healthBarXStart = (int) (34 * Game.SCALE); private int healthBarYStart = (int) (14 * Game.SCALE); // private int maxHealth = 100; // private int currentHealth = maxHealth; private int healthWidth = healthBarWidth; private int flipX = 0; private int flipW = 1; private boolean attackChecked; private Playing playing; private int tileY = 0; public Player(float x, float y, int width,int height, Playing playing) { super(x, y, width, height); this.playing = playing; this.state = IDLE; this.maxHealth = 100; this.currentHealth = maxHealth; this.walkSpeed = Game.SCALE * 1.5f; loadAnimations(); initHitbox(20,28); initAttackbox(); } public void setSpawn(Point spawn) { this.x = spawn.x; this.y = spawn.y; hitbox.x = x; hitbox.y = y; } private void initAttackbox() { attackBox = new Rectangle2D.Float(x,y,(int)(20 * Game.SCALE), (int)(20 * Game.SCALE)); } public void update() { updateHealthBar(); if (currentHealth <= 0) { if (state != DEAD) { state = DEAD; aniTick = 0; aniIndex = 0; playing.setPlayerDying(true);
package entities; public class Player extends Entity { private BufferedImage[][] animations; private boolean moving = false, attacking = false; private boolean left, right, jump; private int[][] lvlData; private float xDrawOffset = 25 * Game.SCALE; private float yDrawOffset = 4 * Game.SCALE; // Jumping / Gravity private float jumpSpeed = -2.25f * Game.SCALE; private float fallSpeedAfterCollision = 0.5f * Game.SCALE; //StatusBarUI private BufferedImage statusBarImg; private int statusBarWidth = (int) (192 * Game.SCALE); private int statusBarHeight = (int) (58 * Game.SCALE); private int statusBarX = (int) (10 * Game.SCALE); private int statusBarY = (int) (10 * Game.SCALE); private int healthBarWidth = (int) (150 * Game.SCALE); private int healthBarHeight = (int) (4 * Game.SCALE); private int healthBarXStart = (int) (34 * Game.SCALE); private int healthBarYStart = (int) (14 * Game.SCALE); // private int maxHealth = 100; // private int currentHealth = maxHealth; private int healthWidth = healthBarWidth; private int flipX = 0; private int flipW = 1; private boolean attackChecked; private Playing playing; private int tileY = 0; public Player(float x, float y, int width,int height, Playing playing) { super(x, y, width, height); this.playing = playing; this.state = IDLE; this.maxHealth = 100; this.currentHealth = maxHealth; this.walkSpeed = Game.SCALE * 1.5f; loadAnimations(); initHitbox(20,28); initAttackbox(); } public void setSpawn(Point spawn) { this.x = spawn.x; this.y = spawn.y; hitbox.x = x; hitbox.y = y; } private void initAttackbox() { attackBox = new Rectangle2D.Float(x,y,(int)(20 * Game.SCALE), (int)(20 * Game.SCALE)); } public void update() { updateHealthBar(); if (currentHealth <= 0) { if (state != DEAD) { state = DEAD; aniTick = 0; aniIndex = 0; playing.setPlayerDying(true);
playing.getGame().getAudioPlayer().playEffect(AudioPlayer.DIE);
3
2023-10-07 12:07:45+00:00
16k
yc-huang/bsdb
src/main/java/it/unimi/dsi/sux4j/mph/GOVMinimalPerfectHashFunctionModified.java
[ { "identifier": "ConcurrentBucketedHashStore", "path": "src/main/java/it/unimi/dsi/sux4j/io/ConcurrentBucketedHashStore.java", "snippet": "public class ConcurrentBucketedHashStore<T> implements Serializable, SafelyCloseable, Iterable<ConcurrentBucketedHashStore.Bucket> {\n public static final long se...
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.Serializable; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Iterator; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.zip.GZIPInputStream; import org.apache.commons.math3.random.RandomGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.martiansoftware.jsap.FlaggedOption; import com.martiansoftware.jsap.JSAP; import com.martiansoftware.jsap.JSAPException; import com.martiansoftware.jsap.JSAPResult; import com.martiansoftware.jsap.Parameter; import com.martiansoftware.jsap.SimpleJSAP; import com.martiansoftware.jsap.Switch; import com.martiansoftware.jsap.UnflaggedOption; import com.martiansoftware.jsap.stringparsers.FileStringParser; import com.martiansoftware.jsap.stringparsers.ForNameStringParser; import it.unimi.dsi.Util; import it.unimi.dsi.bits.LongArrayBitVector; import it.unimi.dsi.bits.TransformationStrategies; import it.unimi.dsi.bits.TransformationStrategy; import it.unimi.dsi.fastutil.io.BinIO; import it.unimi.dsi.fastutil.longs.LongBigList; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.io.FileLinesByteArrayIterable; import it.unimi.dsi.io.FileLinesMutableStringIterable; import it.unimi.dsi.logging.ProgressLogger; import it.unimi.dsi.sux4j.io.ConcurrentBucketedHashStore; import it.unimi.dsi.sux4j.io.ConcurrentBucketedHashStore.Bucket; import it.unimi.dsi.sux4j.io.ConcurrentBucketedHashStore.DuplicateException; import it.unimi.dsi.sux4j.mph.solve.Linear3SystemSolver; import it.unimi.dsi.sux4j.mph.solve.Orient3Hypergraph; import it.unimi.dsi.util.XoRoShiRo128PlusRandomGenerator; import it.unimi.dsi.util.concurrent.ReorderingBlockingQueue;
12,801
final boolean givenBucketedHashStore = bucketedHashStore != null; if (bucketedHashStore == null) { bucketedHashStore = new ConcurrentBucketedHashStore<>(transform, tempDir, pl); bucketedHashStore.reset(r.nextLong()); bucketedHashStore.addAll(keys.iterator()); } n = bucketedHashStore.size(); defRetValue = -1; // For the very few cases in which we can decide bucketedHashStore.bucketSize(BUCKET_SIZE); if (n / BUCKET_SIZE + 1 > Integer.MAX_VALUE) throw new IllegalStateException("This class supports at most " + ((Integer.MAX_VALUE - 1) * BUCKET_SIZE - 1) + " keys"); final int numBuckets = (int) (n / BUCKET_SIZE + 1); multiplier = numBuckets * 2L; LOGGER.debug("Number of buckets: " + numBuckets); edgeOffsetAndSeed = new long[numBuckets + 1]; bitVector = LongArrayBitVector.getInstance(2 * (1 + (n * C_TIMES_256 >> 8))); int duplicates = 0; for (;;) { LOGGER.debug("Generating minimal perfect hash function..."); pl.expectedUpdates = numBuckets; pl.itemsName = "buckets"; pl.start("Analysing buckets... "); final AtomicLong unsolvable = new AtomicLong(), unorientable = new AtomicLong(); try { final int numberOfThreads = Integer.parseInt(System.getProperty(NUMBER_OF_THREADS_PROPERTY, Integer.toString(Math.min(4, Runtime.getRuntime().availableProcessors())))); final ArrayBlockingQueue<Bucket> bucketQueue = new ArrayBlockingQueue<>(numberOfThreads * 8); final ReorderingBlockingQueue<LongArrayBitVector> queue = new ReorderingBlockingQueue<>(numberOfThreads * 128); final ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads + 2); final ExecutorCompletionService<Void> executorCompletionService = new ExecutorCompletionService<>(executorService); executorCompletionService.submit(() -> { for(;;) { final LongArrayBitVector data = queue.take(); if (data == END_OF_SOLUTION_QUEUE) return null; bitVector.append(data); } }); final ConcurrentBucketedHashStore<T> chs = bucketedHashStore; executorCompletionService.submit(() -> { try { final Iterator<Bucket> iterator = chs.iterator(); for(int i1 = 0; iterator.hasNext(); i1++) { final Bucket bucket = new Bucket(iterator.next()); assert i1 == bucket.index(); synchronized(edgeOffsetAndSeed) { edgeOffsetAndSeed[i1 + 1] = edgeOffsetAndSeed[i1] + bucket.size(); assert edgeOffsetAndSeed[i1 + 1] <= OFFSET_MASK + 1; } bucketQueue.put(bucket); } } finally { for(int i2 = numberOfThreads; i2-- != 0;) bucketQueue.put(END_OF_BUCKET_QUEUE); } return null; }); final AtomicInteger activeThreads = new AtomicInteger(numberOfThreads); for(int i = numberOfThreads; i-- != 0;) executorCompletionService.submit(() -> { Thread.currentThread().setPriority(Thread.MIN_PRIORITY); long bucketTime = 0; final long outputTime = 0; for(;;) { final long start = System.nanoTime(); final Bucket bucket = bucketQueue.take(); bucketTime += System.nanoTime() - start; if (bucket == END_OF_BUCKET_QUEUE) { if (activeThreads.decrementAndGet() == 0) queue.put(END_OF_SOLUTION_QUEUE, numBuckets); LOGGER.debug("Queue waiting time: " + Util.format(bucketTime / 1E9) + "s"); LOGGER.debug("Output waiting time: " + Util.format(outputTime / 1E9) + "s"); return null; } long seed = 0; final long off = vertexOffset(edgeOffsetAndSeed[(int)bucket.index()]); final Linear3SystemSolver solver = new Linear3SystemSolver((int)(vertexOffset(edgeOffsetAndSeed[(int)(bucket.index() + 1)]) - off), bucket.size()); for(;;) { final boolean solved = solver.generateAndSolve(bucket, seed, null); unorientable.addAndGet(solver.unorientable); unsolvable.addAndGet(solver.unsolvable); if (solved) break; seed += SEED_STEP; if (seed == 0) throw new AssertionError("Exhausted local seeds"); } synchronized (edgeOffsetAndSeed) { edgeOffsetAndSeed[(int)bucket.index()] |= seed; } final long[] solution = solver.solution; final LongArrayBitVector dataBitVector = LongArrayBitVector.ofLength(solution.length * 2); final LongBigList dataList = dataBitVector.asLongBigList(2); for(int j = 0; j < solution.length; j++) dataList.set(j, solution[j]); queue.put(dataBitVector, bucket.index()); synchronized(pl) { pl.update(); } } }); try { for(int i = numberOfThreads + 2; i-- != 0;) executorCompletionService.take().get(); } catch (final InterruptedException e) { throw new RuntimeException(e); } catch (final ExecutionException e) { final Throwable cause = e.getCause();
/* * Sux4J: Succinct data structures for Java * * Copyright (C) 2016-2022 Sebastiano Vigna * * This program and the accompanying materials are made available under the * terms of the GNU Lesser General Public License v2.1 or later, * which is available at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html, * or the Apache Software License 2.0, which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * 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. * * SPDX-License-Identifier: LGPL-2.1-or-later OR Apache-2.0 */ package it.unimi.dsi.sux4j.mph; /** * Modified to use ConcurrentBucketedHashStore instead of BucketedHashStore. * * A minimal perfect hash function stored using the {@linkplain Linear3SystemSolver * Genuzio-Ottaviano-Vigna 3-regular <b>F</b><sub>3</sub>-linear system technique}. It is the * fastest minimal perfect hash function available with space close to 2 bits per key. * * <P> * Given a list of keys without duplicates, the {@linkplain Builder builder} of this class finds a * minimal perfect hash function for the list. Subsequent calls to the {@link #getLong(Object)} * method will return a distinct number for each key in the list. For keys out of the list, the * resulting number is not specified. In some (rare) cases it might be possible to establish that a * key was not in the original list, and in that case -1 will be returned; by <em>signing</em> the * function (see below), you can guarantee with a prescribed probability that -1 will be returned on * keys not in the original list. The class can then be saved by serialisation and reused later. * * <p> * This class uses a {@linkplain ConcurrentBucketedHashStore bucketed hash store} to provide highly scalable * construction. Note that at construction time you can {@linkplain Builder#store(ConcurrentBucketedHashStore) * pass a BucketedHashStore} containing the keys (associated with any value); however, if the store * is rebuilt because of a {@link DuplicateException} it * will be rebuilt associating with each key its ordinal position. * * <P> * For convenience, this class provides a main method that reads from standard input a (possibly * <code>gzip</code>'d) sequence of newline-separated strings, and writes a serialised minimal * perfect hash function for the given list. * * <h2>Signing</h2> * * <p> * Optionally, it is possible to {@linkplain Builder#signed(int) <em>sign</em>} the minimal perfect * hash function. A <var>w</var>-bit signature will be associated with each key, so that * {@link #getLong(Object)} will return -1 on strings that are not in the original key set. As * usual, false positives are possible with probability 2<sup>-<var>w</var></sup>. * * <h2>Multithreading</h2> * * <p> * This implementation is multithreaded: each bucket returned by the {@link ConcurrentBucketedHashStore} is * processed independently. By default, this class uses {@link Runtime#availableProcessors()} * parallel threads, but by default no more than 4. If you wish to set a specific number of threads, * you can do so through the system property {@value #NUMBER_OF_THREADS_PROPERTY}. * * <h2>How it Works</h2> * * <p> * The detail of the data structure can be found in &ldquo;Fast Scalable Construction of (Minimal * Perfect Hash) Functions&rdquo;, by Marco Genuzio, Giuseppe Ottaviano and Sebastiano Vigna, * <i>15th International Symposium on Experimental Algorithms &mdash; SEA 2016</i>, Lecture Notes in * Computer Science, Springer, 2016. We generate a random 3-regular hypergraph and give it an * {@linkplain Orient3Hypergraph orientation}. From the orientation, we generate a random linear * system on <b>F</b><sub>3</sub>, where the variables in the <var>k</var>-th equation are the * vertices of the <var>k</var>-th hyperedge, and the known term of the <var>k</var>-th equation is * the vertex giving orientation to the <var>k</var>-th hyperedge. Then, we * {@linkplain Linear3SystemSolver solve the system} and store the solution, which provides a * perfect hash function. * * <p> * To obtain a minimal perfect hash function, we simply notice that we whenever we have to assign a * value to a vertex, we can take care of using the number 3 instead of 0 if the vertex is actually * the output value for some key. The final value of the minimal perfect hash function is the number * of nonzero pairs of bits that precede the perfect hash value for the key. To compute this number, * we use use in each bucket {@linkplain #countNonzeroPairs(long) broadword programming}. * * Since the system must have &#8776;10% more variables than equations to be solvable, a * {@link GOVMinimalPerfectHashFunctionModified} on <var>n</var> keys requires 2.2<var>n</var> bits. * * @author Sebastiano Vigna * @since 4.0.0 */ public class GOVMinimalPerfectHashFunctionModified<T> extends AbstractHashFunction<T> implements Serializable { public static final long serialVersionUID = 6L; private static final Logger LOGGER = LoggerFactory.getLogger(GOVMinimalPerfectHashFunctionModified.class); private static final LongArrayBitVector END_OF_SOLUTION_QUEUE = LongArrayBitVector.getInstance(); private static final Bucket END_OF_BUCKET_QUEUE = new Bucket(); /** The local seed is generated using this step, so to be easily embeddable in {@link #edgeOffsetAndSeed}. */ private static final long SEED_STEP = 1L << 56; /** The lowest 56 bits of {@link #edgeOffsetAndSeed} contain the number of keys stored up to the given bucket. */ private static final long OFFSET_MASK = -1L >>> 8; /** The ratio between vertices and hyperedges. */ private static double C = 1.09 + 0.01; /** Fixed-point representation of {@link #C}. */ private static int C_TIMES_256 = (int)Math.floor(C * 256); /** * Counts the number of nonzero pairs of bits in a long. * * @param x a long. * @return the number of nonzero bit pairs in <code>x</code>. */ public final static int countNonzeroPairs(final long x) { return Long.bitCount((x | x >>> 1) & 0x5555555555555555L); } /** Counts the number of nonzero pairs between two positions in the given arrays, * which represents a sequence of two-bit values. * * @param start start position (inclusive). * @param end end position (exclusive). * @param array an array of longs containing 2-bit values. * @return the number of nonzero 2-bit values between {@code start} and {@code end}. */ private final static long countNonzeroPairs(final long start, final long end, final long[] array) { int block = (int)(start >>> 5); final int endBlock = (int)(end >>> 5); final int startOffset = (int)(start & 31); final int endOffset = (int)(end & 31); if (block == endBlock) return countNonzeroPairs((array[block] & (1L << (endOffset << 1)) - 1) >>> (startOffset << 1)); long pairs = 0; if (startOffset != 0) pairs += countNonzeroPairs(array[block++] >>> (startOffset << 1)); while(block < endBlock) pairs += countNonzeroPairs(array[block++]); if (endOffset != 0) pairs += countNonzeroPairs(array[block] & (1L << (endOffset << 1)) - 1); return pairs; } /** The system property used to set the number of parallel threads. */ public static final String NUMBER_OF_THREADS_PROPERTY = "it.unimi.dsi.sux4j.mph.threads"; /** A builder class for {@link GOVMinimalPerfectHashFunctionModified}. */ public static class Builder<T> { protected Iterable<? extends T> keys; protected TransformationStrategy<? super T> transform; protected int signatureWidth; protected File tempDir; protected ConcurrentBucketedHashStore<T> bucketedHashStore; /** Whether {@link #build()} has already been called. */ protected boolean built; /** Specifies the keys to hash; if you have specified a {@link #store(ConcurrentBucketedHashStore) BucketedHashStore}, it can be {@code null}. * * @param keys the keys to hash. * @return this builder. */ public Builder<T> keys(final Iterable<? extends T> keys) { this.keys = keys; return this; } /** Specifies the transformation strategy for the {@linkplain #keys(Iterable) keys to hash}. * * @param transform a transformation strategy for the {@linkplain #keys(Iterable) keys to hash}. * @return this builder. */ public Builder<T> transform(final TransformationStrategy<? super T> transform) { this.transform = transform; return this; } /** Specifies that the resulting {@link GOVMinimalPerfectHashFunctionModified} should be signed using a given number of bits per key. * * @param signatureWidth a signature width, or 0 for no signature. * @return this builder. */ public Builder<T> signed(final int signatureWidth) { this.signatureWidth = signatureWidth; return this; } /** Specifies a temporary directory for the {@link #store(ConcurrentBucketedHashStore) BucketedHashStore}. * * @param tempDir a temporary directory for the {@link #store(ConcurrentBucketedHashStore) BucketedHashStore} files, or {@code null} for the standard temporary directory. * @return this builder. */ public Builder<T> tempDir(final File tempDir) { this.tempDir = tempDir; return this; } /** Specifies a bucketed hash store containing the keys. * * @param bucketedHashStore a bucketed hash store containing the keys, or {@code null}; the store * can be unchecked, but in this case you must specify {@linkplain #keys(Iterable) keys} and a {@linkplain #transform(TransformationStrategy) transform} * (otherwise, in case of a hash collision in the store an {@link IllegalStateException} will be thrown). * @return this builder. */ public Builder<T> store(final ConcurrentBucketedHashStore<T> bucketedHashStore) { this.bucketedHashStore = bucketedHashStore; return this; } /** Builds a minimal perfect hash function. * * @return a {@link GOVMinimalPerfectHashFunctionModified} instance with the specified parameters. * @throws IllegalStateException if called more than once. */ public GOVMinimalPerfectHashFunctionModified<T> build() throws IOException { if (built) throw new IllegalStateException("This builder has been already used"); built = true; if (transform == null) { if (bucketedHashStore != null) transform = bucketedHashStore.transform(); else throw new IllegalArgumentException("You must specify a TransformationStrategy, either explicitly or via a given BucketedHashStore"); } return new GOVMinimalPerfectHashFunctionModified<>(keys, transform, signatureWidth, tempDir, bucketedHashStore); } } /** The expected bucket size. */ public final static int BUCKET_SIZE = 1500; /** The multiplier for buckets. */ private final long multiplier; /** The number of keys. */ protected final long n; /** The seed used to generate the initial signature. */ protected final long globalSeed; /** A long containing the cumulating function of the bucket edges (i.e., keys) in the lower 56 bits, * and the local seed of each bucket in the upper 8 bits. The method {@link #vertexOffset(long)} * returns the bucket (i.e., vertex) cumulative value starting from the edge cumulative value. */ protected final long[] edgeOffsetAndSeed; /** The final magick&mdash;the list of modulo-3 values that define the output of the minimal perfect hash function. */ protected final LongBigList values; /** The bit vector underlying {@link #values}. */ protected final LongArrayBitVector bitVector; /** The bit array supporting {@link #bitVector}. */ protected transient long[] array; /** The transformation strategy. */ protected final TransformationStrategy<? super T> transform; /** The mask to compare signatures, or zero for no signatures. */ protected final long signatureMask; /** The signatures. */ protected final LongBigList signatures; protected static long vertexOffset(final long edgeOffsetSeed) { return ((edgeOffsetSeed & OFFSET_MASK) * C_TIMES_256 >> 8); } /** * Creates a new minimal perfect hash function for the given keys. * * @param keys the keys to hash, or {@code null}. * @param transform a transformation strategy for the keys. * @param signatureWidth a signature width, or 0 for no signature. * @param tempDir a temporary directory for the store files, or {@code null} for the standard temporary directory. * @param bucketedHashStore a bucketed hash store containing the keys, or {@code null}; the store * can be unchecked, but in this case <code>keys</code> and <code>transform</code> must be non-{@code null}. */ protected GOVMinimalPerfectHashFunctionModified(final Iterable<? extends T> keys, final TransformationStrategy<? super T> transform, final int signatureWidth, final File tempDir, ConcurrentBucketedHashStore<T> bucketedHashStore) throws IOException { this.transform = transform; final ProgressLogger pl = new ProgressLogger(LOGGER); pl.displayLocalSpeed = true; pl.displayFreeMemory = true; final RandomGenerator r = new XoRoShiRo128PlusRandomGenerator(); pl.itemsName = "keys"; final boolean givenBucketedHashStore = bucketedHashStore != null; if (bucketedHashStore == null) { bucketedHashStore = new ConcurrentBucketedHashStore<>(transform, tempDir, pl); bucketedHashStore.reset(r.nextLong()); bucketedHashStore.addAll(keys.iterator()); } n = bucketedHashStore.size(); defRetValue = -1; // For the very few cases in which we can decide bucketedHashStore.bucketSize(BUCKET_SIZE); if (n / BUCKET_SIZE + 1 > Integer.MAX_VALUE) throw new IllegalStateException("This class supports at most " + ((Integer.MAX_VALUE - 1) * BUCKET_SIZE - 1) + " keys"); final int numBuckets = (int) (n / BUCKET_SIZE + 1); multiplier = numBuckets * 2L; LOGGER.debug("Number of buckets: " + numBuckets); edgeOffsetAndSeed = new long[numBuckets + 1]; bitVector = LongArrayBitVector.getInstance(2 * (1 + (n * C_TIMES_256 >> 8))); int duplicates = 0; for (;;) { LOGGER.debug("Generating minimal perfect hash function..."); pl.expectedUpdates = numBuckets; pl.itemsName = "buckets"; pl.start("Analysing buckets... "); final AtomicLong unsolvable = new AtomicLong(), unorientable = new AtomicLong(); try { final int numberOfThreads = Integer.parseInt(System.getProperty(NUMBER_OF_THREADS_PROPERTY, Integer.toString(Math.min(4, Runtime.getRuntime().availableProcessors())))); final ArrayBlockingQueue<Bucket> bucketQueue = new ArrayBlockingQueue<>(numberOfThreads * 8); final ReorderingBlockingQueue<LongArrayBitVector> queue = new ReorderingBlockingQueue<>(numberOfThreads * 128); final ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads + 2); final ExecutorCompletionService<Void> executorCompletionService = new ExecutorCompletionService<>(executorService); executorCompletionService.submit(() -> { for(;;) { final LongArrayBitVector data = queue.take(); if (data == END_OF_SOLUTION_QUEUE) return null; bitVector.append(data); } }); final ConcurrentBucketedHashStore<T> chs = bucketedHashStore; executorCompletionService.submit(() -> { try { final Iterator<Bucket> iterator = chs.iterator(); for(int i1 = 0; iterator.hasNext(); i1++) { final Bucket bucket = new Bucket(iterator.next()); assert i1 == bucket.index(); synchronized(edgeOffsetAndSeed) { edgeOffsetAndSeed[i1 + 1] = edgeOffsetAndSeed[i1] + bucket.size(); assert edgeOffsetAndSeed[i1 + 1] <= OFFSET_MASK + 1; } bucketQueue.put(bucket); } } finally { for(int i2 = numberOfThreads; i2-- != 0;) bucketQueue.put(END_OF_BUCKET_QUEUE); } return null; }); final AtomicInteger activeThreads = new AtomicInteger(numberOfThreads); for(int i = numberOfThreads; i-- != 0;) executorCompletionService.submit(() -> { Thread.currentThread().setPriority(Thread.MIN_PRIORITY); long bucketTime = 0; final long outputTime = 0; for(;;) { final long start = System.nanoTime(); final Bucket bucket = bucketQueue.take(); bucketTime += System.nanoTime() - start; if (bucket == END_OF_BUCKET_QUEUE) { if (activeThreads.decrementAndGet() == 0) queue.put(END_OF_SOLUTION_QUEUE, numBuckets); LOGGER.debug("Queue waiting time: " + Util.format(bucketTime / 1E9) + "s"); LOGGER.debug("Output waiting time: " + Util.format(outputTime / 1E9) + "s"); return null; } long seed = 0; final long off = vertexOffset(edgeOffsetAndSeed[(int)bucket.index()]); final Linear3SystemSolver solver = new Linear3SystemSolver((int)(vertexOffset(edgeOffsetAndSeed[(int)(bucket.index() + 1)]) - off), bucket.size()); for(;;) { final boolean solved = solver.generateAndSolve(bucket, seed, null); unorientable.addAndGet(solver.unorientable); unsolvable.addAndGet(solver.unsolvable); if (solved) break; seed += SEED_STEP; if (seed == 0) throw new AssertionError("Exhausted local seeds"); } synchronized (edgeOffsetAndSeed) { edgeOffsetAndSeed[(int)bucket.index()] |= seed; } final long[] solution = solver.solution; final LongArrayBitVector dataBitVector = LongArrayBitVector.ofLength(solution.length * 2); final LongBigList dataList = dataBitVector.asLongBigList(2); for(int j = 0; j < solution.length; j++) dataList.set(j, solution[j]); queue.put(dataBitVector, bucket.index()); synchronized(pl) { pl.update(); } } }); try { for(int i = numberOfThreads + 2; i-- != 0;) executorCompletionService.take().get(); } catch (final InterruptedException e) { throw new RuntimeException(e); } catch (final ExecutionException e) { final Throwable cause = e.getCause();
if (cause instanceof DuplicateException) throw (DuplicateException)cause;
2
2023-10-07 03:32:27+00:00
16k
wise-old-man/wiseoldman-runelite-plugin
src/main/java/net/wiseoldman/ui/CodeWordOverlay.java
[ { "identifier": "WomUtilsConfig", "path": "src/main/java/net/wiseoldman/WomUtilsConfig.java", "snippet": "@ConfigGroup(WomUtilsPlugin.CONFIG_GROUP)\npublic interface WomUtilsConfig extends Config\n{\n\t@ConfigSection(\n\t\tname = \"Group\",\n\t\tdescription = \"The group configurations\",\n\t\tposition ...
import com.google.common.base.Strings; import net.wiseoldman.WomUtilsConfig; import net.wiseoldman.WomUtilsPlugin; import java.awt.Dimension; import java.awt.Graphics2D; import java.time.Instant; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import javax.inject.Inject; import net.runelite.client.ui.overlay.OverlayPanel; import net.runelite.client.ui.overlay.OverlayPosition; import net.runelite.client.ui.overlay.OverlayPriority; import net.runelite.client.ui.overlay.components.LineComponent; import net.runelite.client.ui.overlay.components.TitleComponent;
11,668
package net.wiseoldman.ui; public class CodeWordOverlay extends OverlayPanel {
package net.wiseoldman.ui; public class CodeWordOverlay extends OverlayPanel {
private final WomUtilsConfig config;
0
2023-10-09 14:23:06+00:00
16k
PeytonPlayz595/c0.0.23a_01
src/main/java/com/mojang/minecraft/level/tile/LiquidTile.java
[ { "identifier": "Level", "path": "src/main/java/com/mojang/minecraft/level/Level.java", "snippet": "public class Level implements Serializable {\n\tpublic static final long serialVersionUID = 0L;\n\tpublic int width;\n\tpublic int height;\n\tpublic int depth;\n\tpublic byte[] blocks;\n\tpublic String na...
import com.mojang.minecraft.level.Level; import com.mojang.minecraft.level.liquid.Liquid; import com.mojang.minecraft.phys.AABB; import com.mojang.minecraft.renderer.Tesselator; import java.util.Random;
13,161
package com.mojang.minecraft.level.tile; public class LiquidTile extends Tile { protected Liquid liquid; protected int calmTileId; protected int tileId; protected LiquidTile(int var1, Liquid var2) { super(var1); this.liquid = var2; this.tex = 14; if(var2 == Liquid.lava) { this.tex = 30; } this.tileId = var1; this.calmTileId = var1 + 1; float var4 = 0.01F; float var3 = 0.1F; this.setShape(var4 + 0.0F, 0.0F - var3 + var4, var4 + 0.0F, var4 + 1.0F, 1.0F - var3 + var4, var4 + 1.0F); this.setTicking(true); if(var2 == Liquid.lava) { this.setTickSpeed(16); } }
package com.mojang.minecraft.level.tile; public class LiquidTile extends Tile { protected Liquid liquid; protected int calmTileId; protected int tileId; protected LiquidTile(int var1, Liquid var2) { super(var1); this.liquid = var2; this.tex = 14; if(var2 == Liquid.lava) { this.tex = 30; } this.tileId = var1; this.calmTileId = var1 + 1; float var4 = 0.01F; float var3 = 0.1F; this.setShape(var4 + 0.0F, 0.0F - var3 + var4, var4 + 0.0F, var4 + 1.0F, 1.0F - var3 + var4, var4 + 1.0F); this.setTicking(true); if(var2 == Liquid.lava) { this.setTickSpeed(16); } }
public final void onBlockAdded(Level var1, int var2, int var3, int var4) {
0
2023-10-10 17:10:45+00:00
16k